The relation between the Löwenheim–Skolem theorem and construction of reals

Question: The Löwenheim–Skolem theorem directly implies that if a countable first-order theory has an infinite model then it has a countable model. That leads to peculiar things like the so-called Skolem's "paradox", which can be recast as saying that ZFC has a countable model.
I wonder if we can turn that paradox on its head, so to say. If we start with natural numbers, we can construct integers, rationals and, finally, by eg Dedekind cuts, reals. And the final step is not like the others, because we suddenly jump from countable infinity to uncountable infinity. And those real numbers are not really numbers in the conventional sense of atomic objects but rather a model of them that behaves just like reals given an appropriate interpretation.
What I am getting at, to put in a succinct but sloppy phrase, we only need to believe in natural numbers to be able to reason about real numbers.
And I can't help but to see a connection between an ability to move through cardinalities implied by the Löwenheim–Skolem theorem and the ability to construct reals out of natural numbers. Is there a conceptual connection between those two phenomena or am I overthinking it?
Comment: There is a sort of connection. The real numbers are uncountable, yet they are constructed from the natural numbers. This implies that there cannot be a first-order characterisation of the reals using a countable language. We need to move beyond first-order logic into the realm of second-order logic, which we can do by describing the reals in terms of sets of rational numbers or by using second-order axioms like Dedekind or Cauchy completeness.
Answer:
And I can't help but to see a connection between an ability to move through cardinalities implied by the Löwenheim–Skolem theorem and the ability to construct reals out of natural numbers. Is there a conceptual connection between those two phenomena or am I overthinking it?

I don't quite understand what you have in mind but two comments.

We always do mathematics in a language with a finite alphabet, e.g. English or the language of mathematics or first-order logic or what have you. That means we only ever have the ability to talk directly about countably many things in mathematics. In that sense no matter how complicated the objects we define are we only ever talk about them using a countable set of utterances. This could be considered part of the conceptual point of Lowenheim-Skolem, although this general observation applies even to second-order logic while Lowenheim-Skolem doesn't.

The Lowenheim-Skolem paradox applies to the first-order theory of the real numbers as well, and implies that it has a countable model. This theory is the theory of real closed fields, and an explicit example of a countable model of it is the field $\mathbb{R}_{alg}$ of real algebraic numbers. This means that first-order logic is not capable of expressing completeness; to do that we need second-order logic.


Is there a token for the key of a text list?

Question: I need to get the key of the key|value pair from a text list field in a token.
Say the field configuration shows the following options:
no|No Way Jose!
yes|Why yes, that'd do nicely!

and the field is named field_doc_textlist
the token [node:field_doc_textlist] is returning a value like 'No Way Jose!' when what I want is 'no'.  Is there a way to get that from tokens.  I'm using this in the filefield paths module if that matters.
I saw other similar answers here, with no real answers, but I've tried [node:field_doc_textlist:key] [node:field-doc-textlist] [node:field_doc_textlist:machine_name] [node:field_doc_textlist:machine-name] all to no avail
Some additional information: All of the above result in an error similar to

The File path is using the following invalid tokens:
  [node:field-doc-type-book].

A lot of the information I've found suggests using the hyphenated version of the token name instead of the underscore version, but that seems not to work at all.
Comment: @NoSssweat.  I did end up using that sandbox module and it worked.  If you wouldn't mind quickly adding it to an answer I'll gladly accept.
Comment: I found the answer over here [option to output key value for fields of "List (text)" type](https://www.drupal.org/node/1781498) (oops pasted the wrong url before, not sure if you went there, fixed now.)
Comment: Could you be more specific about what part of that you think will fix this?  So far, nothing I'm trying is working.
Comment: did you try the sandbox module [roborew's sandbox: Entity Token Display](https://www.drupal.org/sandbox/roboco/2709617) ?
Comment: I hadn't tried that yet, because it meant I was going to need to go update a  bunch of field instances, I guess I'll go try it now, and write a script to build the instances.
Answer: You could use roborew's sandbox: Entity Token Display

This simple module was created to handle the formatting of entity
  tokens.
When using certain field entities the entity token module will provide
  formatting and data sanitisation for display. However, there are times
  when you need the default value of the original field.
Answer: Say you have field_textlist on node_mytype.

Go to admin/structure/types/manage/node-mytype/display and in the custom display settings tab, enable the token display mode
Go to admin/structure/types/manage/node-mytype/display/token, go to field_textlist and and set key as formatter
Use [node:field_textlist] (underscores) provided by token module, not [node:field-textlist] (dash) provided by entity api module.
Comment: Thanks, I'll have to check that out.  I always kind of wondered about the token display because I couldn't see anywhere that is was actually affecting anything.


Why are Kaplan-Meier curves crossing when Cox PH assumption is not violated (Global Shoenfeld non-significant)?

Question: I am not sure how to interpret the results given from the Cox PH model and the Kaplan-Meier curves. The analyses are conducted in R.
In an observational study, 172 patients are categorized based on tumor profileration status (Ki67): 0-2%, 3-4%, 5-10% and >10% (an index of tumor activity).
I am investigating the correlation between Ki67-status and the event of tumor recurrence.
 library(survival)  library(survminer)
Call:
coxph(formula = Surv(time.to.recurrence, event.recurrence) ~ 1 +
    factor(ki67), data=p)

  n= 172, number of events= 30
   (4 observations deleted due to missingness)

                  coef exp(coef) se(coef)     z Pr(>|z|)
factor(p$ki67)1 0.1109    1.1172   0.5781 0.192  0.84793
factor(p$ki67)2 0.7136    2.0412   0.6065 1.176  0.23942
factor(p$ki67)3 1.8830    6.5731   0.6774 2.780  0.00544 **

I want to test if the proportional hazard assumption is violated:
                   rho chisq     p
factor(p$ki67)1  0.064 0.123 0.726
factor(p$ki67)2 -0.151 0.702 0.402
factor(p$ki67)3 -0.222 1.450 0.229
GLOBAL              NA 4.686 0.196

By using ggcoxzph(), I have the following print:

Interpretation
1) Each covariate is non-significant correlated to time - thus, time independent supporting that the proportional hazard assumption is valid and the model is fit for use
2) The graphic visualizes a non-random pattern further supporting the PH assumption
The Kaplan-Meier analysis was subsequently conducted
Call: survfit(formula = Surv(time.to.recurrence, event.recurrence) ~ 1 +
    factor(ki67), data = p, conf.type = "log")

   4 observations deleted due to missingness
                  n events median 0.95LCL 0.95UCL
factor(p$ki67)=0 30      4     NA      NA      NA
factor(p$ki67)=1 86     12     NA     124      NA
factor(p$ki67)=2 44      9     NA     118      NA
factor(p$ki67)=3 12      5     56       7      NA

The Kaplan-Meier curves were then computed:

1) How can this graph be interpreted?
Intuitively, that curves should not be crossed if the PH assumption is valid?
Answer: The only crossings of survival curves in your data are between the first 2 groups (0-2% and 3-4% Ki67+), between which there is no significant difference in survival (HR 1.1, p-value 0.85). This is not of concern with respect to the proportional hazard assumption. If you took the 116 cases initially at risk in those 2 groups and randomly broke them into groups of the sizes of those two groups (30 and 86) I suspect that you would find similar "crossings" in Kaplan-Meier curves, as one or another group randomly has higher survival fractions at different times. That is, what you see is normally expected variability between essentially identical survival curves.


Can WiFi direct group owner connect to other device group?

Question: If one device has created a WiFi direct group (access point) this device can connect at the same time to other device group?
Answer: TLDR - theoretically yes, practically (in Android) no.
Group OWNER and CLIENT operation mode specify a role of a node within WifiDirect connection.
In theory it should be possible although it would mean that a single node can simultaneously connect to more than one WifiDirect group (your picture represents 3 groups). And 'in theory' means that an OPTIONAL (according to this post and WifiDirect whitepaper) feature has been implemented.

Wi-Fi Direct Device maintains membership in multiple Groups simultaneously: Optional

Ok. Back to Android (since I can see it in your tag): from my experience, I know that Android's implementation of WifiP2p will not let you get two simultaneous connections with two seperate nodes.


Get the time spent by a process on Linux

Question: I want to measure the time it takes to backup a PostgresSql database, I know I can do time pg_dump ...., but what if I already launched the pg_dump command?.
The process already took more than half an hour, and I don't want to break it right know. I'm pretty sure it will take one more hour (and I'll be at home at that time). I would like to know tomorrow how much time it took.
Answer: You are writing this to file, do you? File modification time would be your answer.
Comment: simple answers are always awesome.
Answer: Just show start time
ps -ax  -o cmd,lstart | grep pg_dump

Or timestamp
ls --time-style=+%s -ld /proc/PROCESS_PID

Or secs elapsed
ls --time-style=+%s -ld /proc/PROCESS_PID | cut -d " " -f6 | \
xargs echo "`date +%s` - $1" | bc

Answer: find the pid of your process, say it 999
run this:
while ps -p 999 -o pid; do  date; sleep 20; done

in a shell. the above will quit when your process is done.
you can sleep more if granularity you want is bigger.


Diferença de tempo na execução da mesma query entre PHP e PHPMYADMIN

Question: Estou tentando melhorar a performance de minhas paginas para melhorar a experiencia do usuário, mas, não estou conseguindo identificar o problema.
Segundo o Google, é recomendável que as paginas respondam em menos de 0,4 segundos, porem, só a conexão com o banco de dados, esta levando 0,41 segundos. Sendo por mysql_connect ou mysqli_connect
Além disso, a mesma query que executo para montar um menu, no PHP demora em média 0,14 mas no phpMyAdmin demora apenas 0,0009 conforme mostra na execução

A mostrar registos de 0 - 24 (35 total, O Query demorou 0.0009 sec)

Criei uma pagina vazia, apenas com a conexão e a query para medir os tempos
http://omenorpreco.com/teste.php

Alguém tem ideia como posso diminuir o tempo para fazer a conexão, e, diminuir o tempo da query para ficar igual o PHPMyAdmin?
UPDATE:
//PHP
    $sql = "select cd_categoria, linha, slug, cd_categoria_site, qtd from ( SELECT cd_categoria, if (menu.cd_categoria_pai=0,menu.nm_categoria,concat((select nm_categoria from tb_st_category where cd_categoria = menu.cd_categoria_pai),';',nm_categoria)) as linha , if (menu.cd_categoria_pai=0,menu.nm_slug,concat((select nm_slug from tb_st_category where cd_categoria = menu.cd_categoria_pai),'/',menu.nm_slug)) as slug , cd_categoria as cd_categoria_site , 0 as qtd FROM tb_st_category menu where cd_categoria_pai = 0 ) as a order by linha";
    $pagespeed = microtime_float();
    $query = $mysqli->query($sql);
    echo "Query Time:".number_format(microtime_float()-$pagespeed, 2, ',', '')."
";

Meu servidor SQL é Windows (WAMP)
Ja inclui a variável skip-name-resolve no arquivo de configuração do WAMP
A conexão é remota, feita através do IP, e não do nome do servidor
Comment: Isso é query ou isso é diferença do php? Mostre como fez o seu código php de teste. Todavia acho que esta confundindo.
Comment: Atualizei o post com os dados do PHP (só não coloquei o código da conexão com o banco, mas é mysqli (já tentei com mysql também)
Answer: Esse teste de performance é do PHP e não da query, assim vai dar resultados diferentes sempre, pra depurar uma query você pode usar o set profiling=1;
mysql> set profiling=1;
mysql> EXPLAIN SELECT ...
mysql> SELECT ...
mysql> ALTER ...
mysql> show profiles;
+----------+------------+-------------------------
| Query_ID | Duration   | Query
+----------+------------+-------------------------
|        1 | 0.00036500 | EXPLAIN SELECT sbvi.id a
|        2 | 0.00432700 | SELECT sbvi.id as sbvi_i
|        3 | 2.83206100 | alter table sbvi drop in
|        4 | 0.00047500 | explain SELECT sbvi.id a
|        5 | 0.00367100 | SELECT sbvi.id as sbvi_i
+----------+------------+-------------------------

Documentação: http://dev.mysql.com/doc/refman/5.7/en/show-profile.html
Comment: Ola Guilherme,

Usei o comando que me indicou e aparentemente, o resultado é inferior
1 - 0.00067650 - select cd_categoria, linha, slug, cd_categoria_sit...
Comment: Queria entender porque pelo PHP é mais demorado mesmo? Porque tem o trafego de rede? E pelo PHPMyAdmin é direto na mesma maquina o servidor PHP e o banco?
Comment: @RodrigoMendes o phpmyadmin é uma ferramenta escrita em php, no entanto o resultados deles de tempo deve ser com o profile e nada tem haver com o PHP, como no exemplo, já o teste que você criou é usando funções PHP, ou seja um teste não tem nada haver com o outro, não tem porque comparar ambos.
Comment: Ok Guilherme, agora entendi o que estavam querendo dizer. Mas existe uma forma de eu diminuir este tempo no php? Pois através do Google speed test, minha pagina esta demorando 2 ou 3 segundos para carregar, mas as querys ja estão super otimizadas. Como teste, coloquei umas variáveis de tempo de execução de cada query no rodape http://omenorpreco.com/produto/oculos-oakley-conquest-polarizado-bronze. O recomendado pelo google é o servidor responder em menos de 200ms.

Tentei colocar o comando flush(); apos o  para minimizar o tempo, mas nao adiantou nada.
Comment: Acredito que a melhor solução é usar cache e CDN, assim como usar servidores mais robustos e com maior largura de banda. Acredito que o problema possa está na configuração do _NGINX_ ou do _Apache_ (não sei qual usa). Claro, utilize também uma versão atualizada do PHP, geralmente versões recentes são mais rapidas do que anteriores. :P
Comment: Utilizo o servidor godaddy, consigo mexer nestas configuracoes desta forma? Cache eu ja utilizo, mas CDN? É um serviço pago? Desculpa nao conheco.


Baire space is homeomorphic to countably many copies of itself

Question: On wikipedia I found that the Baire space $\mathcal{N}$ is homeomorphic to the product of a countable number of copies of itself, however, I haven't been able to find a proof.
The Baire space is defined as $\mathcal{N}:=\mathbb{N}^{\mathbb{N}}$ with the product topology, $\mathbb{N}$ being endowed with the discrete topology.
Can anyone help me, please?
Answer: Well, note that $\Bbb N \times \Bbb N$ has a bijection with $\Bbb N$, call it $h$, and let $g: \Bbb N \to \Bbb N \times \Bbb N$, $g(n) = (g_1(n), g_2(n))$ be the inverse, with $h(g_1(n), g_2(n)) = n$ for all $n$ etc.
Then map $f \in (\Bbb N^{\Bbb N})^{\Bbb N}$ to $\Phi(f) \in \Bbb N^{\Bbb N}$ by the rule $$\Phi(f)(n) = f(g_1(n))(g_2(n))$$
and show it's a bijection and a homeomorphsim in the product topologies.
This is ofetn summarized as
$$\mathcal{N}=\Bbb N^{\Bbb N} \simeq \Bbb N^{\Bbb N \times \Bbb N} \simeq (\Bbb N^{\Bbb N})^{\Bbb N}=\mathcal{N}^{\Bbb N}$$
where all homeomorphisms are natural (categorical), basically coordinate shuffles.
Answer: HINT: consider the left-shift map $$S:\mathcal{N}\rightarrow\mathcal{N}: f\mapsto \lambda x.f(x+1).$$
E.g. $S(0,1,2,3,4,5,...)=(1,2,3,4,5,...)$ and so on.
In more detail:

 For each $i\in\mathbb{N}$, let $\mathcal{N}_i=\{f\in\mathcal{N}: f(0)=i\}$. Now think about what $S\upharpoonright \mathcal{N}_i$ does, topologically.


Even after entering proper bytes32 value and address value. Setaddress function is not working

Question: I am getting generic error every time I try to modify the code. I am passing byte32 value as "0xabcd" and address value as "0xca35b7d915458ef540ade6068dfe2f44e8fa733c" in Setaddress function.
The error is as below:

"transact to EternalStorage.setAddress errored: VM error: revert.
  revert  The transaction has been reverted to the initial state.
  Note: The constructor should be payable if you send value.  Debug the transaction to get more information."

Below is my code
pragma solidity ^0.4.17;
contract EternalStorage {

address owner = msg.sender;
address latestVersion;

mapping(bytes32 => uint) uIntStorage;
mapping(bytes32 => address) addressStorage;

modifier onlyLatestVersion() {
   require(msg.sender == latestVersion);
    _;
}

function upgradeVersion(address _newVersion) public {
    require(msg.sender == owner);
    latestVersion = _newVersion;
}

// *** Getter Methods ***
function getUint(bytes32 _key) external view returns(uint) {
    return uIntStorage[_key];
}

function getAddress(bytes32 _key) external view returns(address) {
    return addressStorage[_key];
}

// *** Setter Methods ***
function setUint(bytes32 _key, uint _value) onlyLatestVersion external {
    uIntStorage[_key] = _value;
}

function setAddress(bytes32 _key, address _value) onlyLatestVersion external  payable{
    addressStorage[_key] = _value;
}

// *** Delete Methods ***
function deleteUint(bytes32 _key) onlyLatestVersion external {
    delete uIntStorage[_key];
}

function deleteAddress(bytes32 _key) onlyLatestVersion external {
    delete addressStorage[_key];
}
}

Answer: The error message says that the transaction to setAddress() reverted:

transact to EternalStorage.setAddress errored: VM error: revert.

There is only one requre() statement in setAddress(), in onlyLatestVersion():
require(msg.sender == latestVersion);

So it's virtually certain that the sender of the transaction (msg.sender) is not set to latestVersion. That means you either need to:

Make sure you are sending from the account that the contract has as the latestVersion, or...
Change latestVersion using the contract's function upgradeVersion(), so that it matches your transaction sender.


Best backup strategy with Symantec Backup Exec?

Question: I am not proficient in the use of Symantec Backup Exec, I will like to know what is the best known backup strategies for a simple file server.  I have 5 LTO 3 cartriges new and available to start this strategy but don't know what will be the best approach.
I though to do one weekly on Friday (full in disk 1) and then an incremental everyday until next friday (in disk 0) then another full in disk 2 and so on.  Is this the best way.
Thanks.
Comment: What does "full in disk 1" mean?  How much data are you backing up?  Is it just a single tape drive or some sort of auto-loader/library?
Comment: Now that I re-read the question, I agree that I could use better wording.  As soon as I get a few minutes I will modify it. Thanks for all your time.
Comment: You should probably read my post on "Overwrite Protection" in Backup Exec-- I suspect you're going to need to know about it.
http://serverfault.com/questions/38887/what-does-it-means-a-media-set-with-26-weeks-overwrite-protection-period-and-1-ye/38900#38900
Answer: A related question and answers:
Setting up a new backup scheme
Without knowing what the answers to my questions in the comment, I'd go with:

Friday - full backup
Weekdays - differential backups (not incremental)
Sat/Sun - either nothing if there's no work done on the weekend, or treat them the same as weekdays

Tape rotation will depend on how much data.  I'd have separate tapes (or sets of tapes) that I use for full backups and for the differentials.  If your full backup fits on one tape and all the differentials also fit on one then you'd get something like:

Fri - Full01
Mon/Tue/Wed/Thu - Diff01
Fri - Full02
Mon/Tue/Wed/Thu - Diff02
Fri - Full03
and so on...

You say you have 5 cartridges, but LTO3's are cheap enough now that you can buy some more.  I'd keep at least the last 4 fulls, and I'd have at least 3 or 4 diff tapes to rotate through.  When we were only using tape, we'd keep the last full of each month for one year, and we'd keep two of the fulls forever.  You'll need more tapes w/in a month if you want to do something like this.
If it takes more than one tape for a full, you'd adjust as necessary, and obviously you'd need more tapes up-front.
Comment: Tapre rotation does not depend on data it depends on retention- basing tape rotation on dataset is a common mistake.
Answer: "Best" is a relative term. It really depends on what you're backing up and how important it is to get that data quickly.
Most important items first: make sure you take backups offsite! I know that's not mentioned in your question specifically, but the reminder never hurts. You can pay Iron Mountain to do it for you, take the tape to a safe-deposit box, or take it home. And encrypt that tape while you're at it.
A pretty easy-looking way to set up BE is to use the Policy wizard. In Backup Exec 11d (assume it's still there for newer versions) that will help setup a Grandfather-Father-Son media rotation for you to the backup device of your choice. In 11d, select Backup-->New Policy Using Wizard. I just skimmed it on my backup server, but it should walk you through the details of setting it up. This will let you go back up to a year. Also, if you use the Vaults, you can tell exactly where your tape is (off-site, online, under the mattress, etc.)...if you tell BE where your tape is when you Inventory.
The drawback is that by default it will require more tapes. In fact, you'll need 6 tapes just to make it through the week, as each daily incremental will be on a tape and overwrite protected. This can be nice, but 5 LTOs won't cut it! Best case, you'd have 12 tapes for a year's worth of monthlies, 5 tapes for a month's worth of weeklies, and 5 more for a week's worth of dailies.
Remember that if this is doing any sort of database stuff (mail, SQL, etc.), you probably need some sort of agent for BE to really back it up.
Hope this helps!
CC
Comment: Ummm...while I agree GFS may be overkill, no offsite means no backup. If the building burns while your tapes are in it, you don't have a backup. Unless perhaps you mean an internet-based solution, but that's still offsite.
Comment: Backups do NOT have to be offsite. Media rotation can't even be thought of until you know how long you need to retain backups (eg you would be silly to do GFS if your retention is weekly)
Answer: There is no best strategy.  Backup type, frequency and content are all determined by whatever the buisness requirements are.


R: Joining Tables where t1.key1 = t2.key1 and t2.key2 partially matches t2.key2

Question: I have an interesting join that I need to accomplish in R. So here are my two tables.
Table Number 1:
Date                           Name
2016-01-02 10:18:00            CARDOSO, RAMON
2016-01-02 15:02:00            HARRISON, KATHYANNE M
2016-01-02 15:02:00            PALEO, SHERI
2016-01-03 02:09:00            PHANOR, RENALDY
2016-01-03 09:42:00            GUAMAN, ANGEL
2016-01-03 18:47:00            AIME, MADELINE
2016-01-03 18:47:00            CADET, GARDY
2016-01-03 19:31:00            REID, ARTHUR D
2016-01-03 22:11:00            HERNANDEZ-JONES, FREDRICK JOSHUA
2016-01-04 12:32:00            AGUERO, RAUL

Table number 2:
Date                     ID                  Name
2016-01-02 10:18:00      16-22-AR            CARDOSO, RAMON
2016-01-02 15:02:00      16-24-AR            HARRISON, KATHYANNE M", " PALEO, SHERI"
2016-01-02 15:02:00      16-25-AR            HARRISON, KATHYANNE M", " PALEO, SHERI"
2016-01-03 02:09:00      16-31-AR            PHANOR, RENALDY
2016-01-03 09:42:00      16-32-AR            GUAMAN, ANGEL
2016-01-03 18:47:00      16-39-AR            AIME, MADELINE", " CADET, GARDY"
2016-01-03 18:47:00      16-40-AR            AIME, MADELINE", " CADET, GARDY"
2016-01-03 19:31:00      16-42-AR            REID, ARTHUR D
2016-01-03 22:11:00      16-44-AR            HERNANDEZ-JONES, FREDRICK JOSHUA
2016-01-04 12:32:00      16-49-AR            AGUERO, RAUL

My goal is to have ID in table 1 as its own column, but in order to do so I would need to do a join on date and somehow do a match on name where we lookup the names from table 1 in table 2.
UPDATE:
The original dataset looks like this
2016-01-02 10:18:00  16-22-AR               CARDOSO, RAMON
2016-01-02 15:02:00  16-24-AR, 16-25-AR     HARRISON, KATHYANNE M", " PALEO, SHERI"
2016-01-03 02:09:00  16-31-AR               PHANOR, RENALDY
2016-01-03 09:42:00  16-32-AR               GUAMAN, ANGEL
2016-01-03 18:47:00  16-39-AR, 16-40-AR     AIME, MADELINE", " CADET, GARDY"
2016-01-03 19:31:00  16-42-AR               REID, ARTHUR D
2016-01-03 22:11:00  16-44-AR               HERNANDEZ-JONES, FREDRICK JOSHUA
2016-01-04 12:32:00  16-49-AR               AGUERO, RAUL

The goal is to have each name on its own row with its respective ID. The IDs follow the same order as the names, first ID goes with the fist name.
Hope this clarification helps.
Comment: Use code block formatting `{}` for tables. Dont use snippet.
Comment: You could [split `Name` column](http://stackoverflow.com/q/7069076/5977215) into multiple columns, then [melt the table to long form](http://stackoverflow.com/q/2185252/5977215) and join on `Date` and `Name`
Comment: @joel.wilson, I'm not sure what you mean by confusing?
Answer: I assume when you have something like
2016-01-02 15:02:00      16-24-AR            HARRISON, KATHYANNE M", " PALEO, SHERI"
2016-01-02 15:02:00      16-25-AR            HARRISON, KATHYANNE M", " PALEO, SHERI"

The first ID corresponds to the first name, and the second ID corresponds to the second name.  Then one approach is to create a new column that has the correct name.
d$order <- unlist(sapply(rle(paste0(d$Date, d$Name))$lengths, seq_len))

split_names <- function(name, order = 1) {
  names <- strsplit(name, '\\", \\"')[[1]] # Split
  names <- gsub('^\\s|\\"', "", names) # Clean up leading space and trailing "
  names[order]
}

d$Newname <- mapply(split_names, d$Name, d$order)
d[, c("Date", "ID", "Newname")]
#                   Date       ID                          Newname
# 1  2016-01-02 10:18:00 16-22-AR                   CARDOSO, RAMON
# 2  2016-01-02 15:02:00 16-24-AR            HARRISON, KATHYANNE M
# 3  2016-01-02 15:02:00 16-25-AR                     PALEO, SHERI
# 4  2016-01-03 02:09:00 16-31-AR                  PHANOR, RENALDY
# 5  2016-01-03 09:42:00 16-32-AR                    GUAMAN, ANGEL
# 6  2016-01-03 18:47:00 16-39-AR                   AIME, MADELINE
# 7  2016-01-03 18:47:00 16-40-AR                     CADET, GARDY
# 8  2016-01-03 19:31:00 16-42-AR                   REID, ARTHUR D
# 9  2016-01-03 22:11:00 16-44-AR HERNANDEZ-JONES, FREDRICK JOSHUA
# 10 2016-01-04 12:32:00 16-49-AR                     AGUERO, RAUL

Data:
structure(list(Date = c("2016-01-02 10:18:00", "2016-01-02 15:02:00",
"2016-01-02 15:02:00", "2016-01-03 02:09:00", "2016-01-03 09:42:00",
"2016-01-03 18:47:00", "2016-01-03 18:47:00", "2016-01-03 19:31:00",
"2016-01-03 22:11:00", "2016-01-04 12:32:00"), ID = c("16-22-AR",
"16-24-AR", "16-25-AR", "16-31-AR", "16-32-AR", "16-39-AR", "16-40-AR",
"16-42-AR", "16-44-AR", "16-49-AR"), Name = c("CARDOSO, RAMON",
"HARRISON, KATHYANNE M\", \" PALEO, SHERI\"", "HARRISON, KATHYANNE M\", \" PALEO, SHERI\"",
"PHANOR, RENALDY", "GUAMAN, ANGEL", "AIME, MADELINE\", \" CADET, GARDY\"",
"AIME, MADELINE\", \" CADET, GARDY\"", "REID, ARTHUR D", "HERNANDEZ-JONES, FREDRICK JOSHUA",
"AGUERO, RAUL")), .Names = c("Date", "ID", "Name"), row.names = c(NA,
-10L), class = "data.frame")

Comment: I'm having some difficulty understanding how the ordering works and implement this solution to my code.


Sorting a negative Arrays

Question: So i want to sort an arrays that contain negative number. I have this in my method. When i run it with negative input , java.lang.negativeArray exception is out. here is the code:
protected int size;
protected int offset;

public CountSort2(int nilaiMax,int nilaiMin)
{
   this.size = nilaiMax-nilaiMin+1;
   this.offset=nilaiMin;
}

public void sort(int[] arrInput)
{
    int[] arrFrek = new int[size];
    for(int i=0;i<arrFrek.length;i++)
    {
        arrFrek[i]=0;
    }

    for(int i=0;i<arrInput.length;i++)
    {
        arrFrek[arrInput[i]-offset]+=1;
    }

    for(int i =1; i<arrFrek.length;i++)
    {
        arrFrek[i] = arrFrek[i]+arrFrek[i-1];
    }
    int[] newArrInput = new int[arrInput.length];
    for(int i=0;i<arrInput.length;i++)
    {
        newArrInput[i]=arrInput[i];
    }

    for(int i=0;i<newArrInput.length;i++)
    {
        arrInput[arrFrek[newArrInput[i]-offset]-1]=newArrInput[i];
        arrFrek[newArrInput[i]-offset]-=1;
    }
}

did I miss something ?
Comment: The exception is not `NegativeArray` but `NegativeArraySizeException`, whose documentation clearly says `Thrown if an application tries to create an array with negative size`. The stack trace will tell you at what line exactly this happens.
Answer: Reason is you are passing negative index while creating the array. So consider your statement like:
int[] arrFrek = new int[size];

Where you defined size as
this.size = nilaiMax-nilaiMin+1;

So your nilaiMin > nilaiMax and hence you get negative array size exception. You can read about the exception from javadoc here
Als note, if say your arrInput[i] is 0 and offset is 2, you are trying to access aray with index -2 which is why you will get array index out of bound exception. Note that array index starts from 0 hence it can't be negative.
Comment: No it will throw `java.lang.ArrayIndexOutOfBoundsException` if index is negative. Try  `int[] arr = new int[4];
  System.out.println(arr[-2]);`
Comment: And then try this :`int[] arr = new int[-4];`
Answer: Yes, there is a place in your code which could potentially lead to this exception.
int[] arrFrek = new int[size];
From javadocs
NegativeArraySizeException
Thrown if an application tries to create an array with negative size.

Sorting a negative Arrays


Showing that the mapping $a\in M, a^3=1,x\mapsto ax^2a^2$ is an automorphism of $M$

Question: I am confused I have noticed. Perhaps you can clear up my confusion, which I can't pinpoint the origin of.

Let $M$ be a monoid and $a\in M$ such that $a^3=1$, show that the mapping $x\mapsto ax^2a^2$ is an automorphism of $M$

So I know an automorphism to be a self-isomorphism(here $f:M\to M$), that seems alright. I know an isomorphism to be a bijective homomorphism, fair enough. So let's find if we have a homomorphism from above.
A homomorphic map must satisfy $f(xy)=f(x)f(y)$:
$$f(x)f(y)=ax^2a^2ay^2a^2=ax^2a^3y^2a^2=ax^2y^2a^2=f(xy)$$
Happy days, we have the homomorphic property, and we are mapping from $f:M\to M$ so it is an endomorphism(so far).
What about bijection though to upgrade this endomorphism to an automorphism(so to speak), and we must satisfy $f(1_M)=1_M$ for an isomorphism.

Here is where my confusion comes in, $1_M$ I believe is the identity element of $M$, okay, let's find the identity element, we just take the binary operation $x\cdot 1_M = 1_M \cdot x = x$. Now I realise I don't know what my binary operation is. My function takes a single element?
Perhaps I need not show $f(1_M)=1_M$ or perhaps I truly am just confused, any ideas?

Cohn - Classic Algebra - Chapter 3.1 - Monoids - Exercise 11$^*$ - Page 43
$*$I had a mistake in transcribing the exercise, and hence no fault of Cohn - $x \mapsto axa^2$ - Apologies!
Comment: As stated, the problem statement is wrong. It has already been noted that $M$ needs to be *commutative*. Moreover, $f$ may fail to be onto: Let $(M,\cdot)=(\mathbb N_0,+)$ and $a=0$. Then $f(x)$ is even for all $x$.
Comment: Actually $f(xy) = a(xy)^2 a^2 = a (xyxy) a^2$, which need *not* be the same as $a (x^2 y^2) a^2 = f(x)f(y)$.  (Is $M$ assumed to be a *commutative* monoid?)
Comment: It might help to read what Cohn (3rd edition, 2000) actually writes, which is to consider $x\mapsto axa^2$.
Comment: No worries. At the end of the day, this helped you to see why $x\mapsto ax^2a^2$ is *not* a morphism, in general, when the monoid is not abelian.
Comment: Offtopic: It is 2:34AM perhaps that is the true problem.
Comment: Showing that $f(1_M)=1_M$ is not very difficult. The most important thing you have left to show is that $f$ is bijective, i.e. surjective (sometimes called onto) and injective ("one-to-one").
Comment: I am confused about what your question is.  You began by specifying $a^3=1$.  Is that not a good way to "find the identity element" as you put it?  And you say you do not know what your binary operation is.  Neither do I, if it is not just the monoid multiplication.
Comment: @mathmandan Ahhh yes, valid point, it isn't specified. In fact everything I know is in the shaded area of the post.
Comment: @Arthur What is $1_M$, or how do I find it here?
Comment: @ColinMcLarty That is a good way to find it, I missed the monoid multiplication(despite using it to prove homomorphism) since I am still having trouble with the 'abstract' part of abstract-algebra, e.g. breaking what I have always known apart($\Bbb R$). I suppose I must have $(M,\times)$ as my monoid
Comment: @HagenvonEitzen That is definitely a shame. Thank you!

I will amend that this is Cohn - Classic Algebra - Chapter 3.1 - Monoids - Exercise 11 - Page 43
Comment: The element $1_M$ is guaranteed to exist by the definition of a monoid. That is how you "get" to it.
Comment: @Did Apologies you are totally right. This is entirely my mistake. I'll add to the reference(as to not slander it)
Answer: Even if $M$ is a group (not just a monoid), and even if $M$ is commutative (not specified), the conclusion is false.  Let $M = \mathbb{C}^*$, the group of nonzero complex numbers under multiplication, and let $a = e^{2\pi i / 3}$, so that $a^3 = e^{2\pi i} = 1$.  Now define $f: M \to M$ by $f(x) = ax^2 a^2$.
Then $f$ is indeed a (group) homomorphism, but it is not one-to-one:
$$
f(-1) = a (-1)^2 a^2 = a(1) a^2 = a^3 = 1,
$$
and
$$
f(1) = a(1)^2 a^2 = a^3 = 1.
$$
Actually for this example we could restrict to just the circle group, or indeed even the cyclic group of order $6$.


Shorthand for "sequence of subsets"

Question: May I ask does $\{A_n\}_{n=1}^\infty\subseteq P (B)$ mean $\{A_n\}$ is a sequence of subsets of $B$? (Here $P(B)$ means the power set of $B$)
p.s. Also, Is there some shorter way to say "$\{A_n\}$
is a sequence of subsets of $B$
"?
Comment: It is a very awkward way of writing $A_n \subset B$.
Comment: Why not instead, "For each $n\in\mathbb{N},\ A_n \subset B.$" ?
Comment: FYI, there is a slight [abuse of notation](https://en.wikipedia.org/wiki/Abuse_of_notation) in writing $\{A_n\}_{n=1}^\infty\subseteq P (B)$ because $\{A_n\}_{n=1}^\infty$ is a **sequence** in $P(B),$ not a **subset** of $P(B).$
Comment: @DaveL.Renfro What differences are there? I know the sequence is ordered and subset is not.
Comment: @HIH: *What differences are there?* -- The difference is similar to the difference between the **set** $\{1,\,2\}$ and the **ordered pair** $(1,\,2).$
Comment: @DaveL.Renfro Thanks a lot!
Answer: Correct, $x=\{x_n\}_{n\in\mathbb{N}}\subset\mathcal{A}$ can generally be read as $x$ being a sequence in $\mathcal{A}$, i.e., $x_n\in\mathcal{A}$ for each $n\in\mathcal{A}$. In your case, you have $A_n\in\mathcal{P}(B)$ (so $A_n$ is a subset of $B$) for each $n\in\mathbb{N}$, making $\{A_n\}_{n\in\mathbb{N}}$ a sequence of subsets of $B$.
Comment: Is there some shorter way to say "$\{A_n\}$ is a sequence of subsets of $B$"?
Comment: Not shorter, but a more intuitive could be "$\{A_n\}_{n\in\mathbb{N}}:A_n\subset B,\,\forall n\in\mathbb{N}$" (read ''$:$'' as ''such that'')
Comment: Thank you so much!

Shorthand for "sequence of subsets"


Android Media Support

Question: I want to know whether following media are supported natively in Android or not I am not sure about Audio/Video as I am not well versed with media formats, so please enlighten me on following formats. I had already referenced http://developer.android.com/guide/appendix/media-formats.html

WMA file (As per my knowledge not supported)
Flash Media only Audio H.264 MP4( I dont know much about flash but only this that we can play flash file in android 2.2+ using webview)
Quick Time only Audio H.264 MP4
Real Media

Regards
Saurabh
Answer: You can find the list of supported formats here:
http://developer.android.com/guide/appendix/media-formats.html
Comment: Thanks for you answer, I had already checked that but I am not sure whether my formats are there in it or not as I am not good at them :(
Comment: ok, then I don't know anything more than you know I guess. But as far as I understand, #1, #4 not supported; #2 & #3 are supported. I'm not sure though.

Android Media Support


JSON CSS parser

Question: my recursive function is breaking and I cannot figure out why. I am trying to write a parser for json to css with barebone javascript and can't seem to wrap my head around why my function doesn't work. Can anyone lend me a hand?
In css you would get elements that are children of that particular element you are addressing with something like this
#nav li{
  some style here
}

Trying to manipulate the same thing in javascript only it doesn't work. My code works fine for simple selectors so far.
var json = {
    "body" : {
        "background": "#303030",
        "color": "#FFFFFF",
        "font-family": "Arial, Helvetica, sans-serif"
    },
    "#nav": {
        "li": {
            "display": "inline-block",
            "list-styles": "none",
            "margin-right": "10px",
            "padding": "10px, 10px"
        }
    }
}
// How to use:
// json is an obj
// body is a selector
// background is a property belong to a selector
// #303030 is a value for the property

//apply css changes to document without writing any css
//by default the first values are
//               selector = background
//               parent   = document
//               object   = json
function styleApply(selector, parent, object){
    var element, onSelector, signal;

    //checks the first character of the selector and grabs element from page depending on what type of element it is
    switch(selector[0]){
        case ".":
            element= parent.getElementsByClassName(selector.substring(1));
            newParent = element[0]; //checks to see what is in the first index of the obtained element
            break;
        case "#":
            element= parent.getElementById(selector.substring(1));
            newParent = element;
            break;
        default:
            element= parent.getElementsByTagName(selector);
            newParent = element[0];
            break;
    }

    //only works if there is actually an element in the page corresponding with the selector
    if(newParent != null){
        //loops through all elements with the same selector or in the case of id just does one loop
        for(var i=0; i<element.length; i++){

            //loops through all properties in the selector
            for (var property in object[selector]){
                //grabs the associated value with the selector could be string or object
                var value= object[selector][property];

                //if it is a string it is a style, if it is an object, it is targeting the elements inside the current selector only
                if(typeof(value) === "string"){
                    element[i].style.setProperty(property, value);
                }else{

/*I am breaking my code right here*/

                    //reusing the same function, this time selector is equal to property for the case of nav, it is the element 'li'
                    //newParent is the element who is a parent of the current element (e.g 'nav' is parent of 'li')
                    //value is the new object that is replacing json,
                    styleApply(property, newParent, value); //since value is an object it did not pass the string test and now the new object is value
/*Problem ends here */

                }
            }
        }
    }
}

my code for looping over all the values in json
for (var selector in json){
    styleApply(selector, document, json);
}

Comment: `getElementById` returns a single element, not a collection. You need to wrap it in an array.
Comment: When you call your function recursively, you need to pass `element[i]` as the new parent, not `newParent`.
Comment: YAY Thanks a lot Barmar, I managed to shorten my code and got the inheritor working! and thanks xbonez for looking over my work. One extra change I made is in my value = object[selector]
I needed to go back one param to replicate the structure of my json
Comment: Object iteration order is implementation dependent and browsers are not reliable with this, so this approach will not work consistently with css rules where order is important
Answer: I just happen to look into json to write a cleaner css than straight up concatenating strings and numbers together. Instead of applying the style directly to each element, I put them into a

JSON CSS parser


The relation between prime ideal and simple ring

Question: I saw "Any simple ring is a prime ring" as an example in Prime ring@wiki.
Can anyone show me how to proof it?
Also, on the other side, is any prime ring a simple ring?
Thanks.
Comment: All finite integral domains are fields. See here for more: http://math.stackexchange.com/questions/62548/why-is-a-finite-integral-domain-always-field
Comment: For the second question, not all prime rings are simple. Consider any integral domain which is not a field, e.g. the integers.
Comment: What if it is finite?
Answer: A unital ring $R$ is called simple iff $R$ is not zero ring and the only ideals of $R$ are $R$ and $0$; prime iff $R$ is not zero ring and for any nonzero ideals $I,J$ of $R$, $IJ\neq 0$. Since the only nonzero ideal of a simpile ring $R$ is $R$ itself, and $R^2=R\neq 0$, it's clear that simple rings are prime rings.
If $R$ is commutative, simple rings = fields, prime rings= integral domains. Not every integral domain is a field, the simplest example is $\mathbb Z$ I think.
Comment: That is, "Any simple ring is a prime ring" is a wrong statement?
Comment: @user131605 It's a right statement if you only consider rings with identity. It is the converse statement that is wrong.


Negative Reciprocals

Question: What is the negative reciprocal of (-1 + n) / n? I know how to convert simple fractions (such as 1/2) to their negative reciprocals, however, I don't know what to do if there is an extra element (such as adding 1 to the numerator). How would it work?
Comment: $$-\frac{n}{-1 + n}$$ Or if you prefer: $$\frac{n}{1 - n}$$
Comment: What is the "negative reciprical"?
Answer: The reciprocal of $ \frac{-1+n}{n}$ is $ \frac{n}{-1+n}$. Thus, what you are looking for is given by $ \frac{n}{1-n}$.

Negative Reciprocals


Can VS Code display modified files by folder in git version manager?

Question: look at the screenshot:

vscode lists all modified files, and shows which folder the file belongs to, but it is not clear enough, I want modified files to be displayed by folder, just like in file tree. is it possible?
Comment: Tree functionality:  See https://stackoverflow.com/questions/51476096/visual-studio-code-group-pending-changes-by-folder/58274085#58274085  You can display your source control files like a tree - that is, by folder - since v1.43.
Answer: It appears the issue 40712 "SCM: Support sort" (mentioned by alefragnani) might finally (for VSCode 1.47, June 2020) be resolved.
See PR 99768 "View/Sort feature for SCM viewlet", which proposes:

a sort by status
a sort by path

See View sort:

View and Sort

We have added support for sorting your changes in the source control view by name, path (default), and state when using the list view option.
We have consolidated the view options (list vs. tree) and sort options into a new View & Sort menu item in the context menu.

And with VSCode 1.64 (Jan. 2022), this sort order will be persistent.
See issue 120271 / PR 123232 and commit 9152469

Add scm view default sort setting.
Add scm view sort to workspace storage.

The options are:

Sort the repository changes by path
Sort the repository changes by file name
Sort the repository changes by SCM status
Comment: I don't have access to that menu in VS Code 1.75
Comment: @Myer I do, in VSCode 1.75.1. Are you in the "Source Control" view?
Comment: I am able to see it now! I was in the source control view before, but I had to look up above the workspace panel toolbar to the source control panel toolbar @VonC
Comment: @Myer OK, I am glad you found it. This menu is not very intuitive.
Answer: You can't do that, yet.
There is an open issue which asks a few improvements for the Git tab, and one of the comments asks for "Sort by folder".
You should upvote on that issue, making it more visible to the VS Code team.
Comment: The linked issue #40712 is marked as solved in PR #99768 in June 2020, which locked the issue; upvotes aren't possible anymore.
Comment: Yes, which is good, since my answer was made in 2018. The @VonC answer, made in 2020 has more details about the "next steps", after the issue being solved.


Dhcrelay init.d script runs improperly

Question: I am trying to use dhcrealy on a CentOs 5 kernel which have kernel version 3.5.3.
I configured /etc/sysconfig/dhcrelay file like that
dhcrelay -i eth1 192.168.0.1

While dhcrealy is stopped, I run /etc/init.d/dhcrelay status and I get this output.
Internet Systems Consortium DHCP Relay Agent V3.0.5-RedHat
Copyright 2004-2006 Internet Systems Consortium.
All rights reserved.
For info, please visit http://www.isc.org/sw/dhcp/
Listening on LPF/eth1/08:00:27:49:5e:e7
Sending on   LPF/eth1/08:00:27:49:5e:e7
Sending on   Socket/fallback
dhcrelay (pid 27536) is running...

Then I check ps aux | grep dhcrelay and see that dhcrelay was started. Although It returns OK, I could not stop it by calling /etc/init.d/dhcrelay stop and whenever I check status It starts new proccess. Then I can only stop it by calling killall dhcrelay command
My installed dhcp package is dhcp-3.0.5-23.el5_6.4
I wonder is there anybody faced with same problem?
Answer: most likely this is simply a broken init.d-script, that does not honor the arguments (start, stop, status), but always starts the dhcprelay.
you might want to report that as a bug with the maintainers of the package.
Answer: I figure out the reason of this error. Conf file should not contain commands.
I change it as like that and problem solved.
INTERFACES="eth1"
DHCPSERVERS="192.168.0.1"

Dhcrelay init.d script runs improperly


How to get ranges of groups of data in sqlite table

Question: I'm not sure if this can be done but if it can:
Suppose I have a simple table that has a time field (for simplicity sake we'll just use integers) and a activity field.  The data can be sorted on time.  For example:
| time  |  activity
--------------------
|  1    |  sitting
|  3    |  sitting
|  5    |  sitting
|  9    |  running
|  10   |  running
|  11   |  sitting
|  13   |  sitting
|  15   |  walking
|  18   |  walking
|  20   |  running
|  31   |  sitting
|  32   |  sitting

Is there an easy way to get a list of the start/stop times for each activity?  Thus my result would be:
sitting (1, 5)
sitting (9, 10)
sitting (11, 13)
running (9, 10)
running (20, 20)
walking (15, 18)

I know I could do a greedy search and, for each activity, gather the start/stop times each unique cluster and store them that way.  But as this data is stored in an sqlite file I'd like to think there would be a query I could write to quickly give me the same data I am looking for.  The data does not have to be in the exact format as I listed it below but rather give me all start/stop times for all occurrences of like activities...
Answer: SQL is a set-oriented language, so the query, while working, is not pretty:
SELECT activity,
       time AS start_time,
       (SELECT MAX(a3.time)
        FROM activity AS a3
        WHERE a3.time < ifnull((SELECT MIN(time)
                                FROM activity AS a4
                                WHERE a4.time > a1.time
                                  AND a4.activity != a1.activity),
                               'inf')
       ) AS end_time
FROM activity AS a1
WHERE (SELECT a2.activity
       FROM activity AS a2
       WHERE a2.time < a1.time
       ORDER BY a2.time DESC
       LIMIT 1
      ) IS NOT a1.activity

How it works:
The outer query (a1) returns a record for every start of a group.
A record is the start of a group if it is the first record with an activity, i.e., if the previous record has a different activity.
The previous record is the record with the largest time that is still smaller, and is computed by the a2 subquery.
The comparison uses IS NOT instead of != because the subquery returns NULL if there is no previous record.
The third column, computed by the a3 subquery, gives the end time of the group.
The last record of the group is the last record before the first record of the next group.
The first record of the next group (computed by the a4 subquery) is the record with the smallest timestamp that is still larger but has a different activity.
At the end of the table, there is no next group; the ifnull converts that NULL into the string 'inf' which compares larger than any number.
Comment: Then add the same condition to the `a2` subquery.
Comment: This is awesome, thanks!  One last question, can this be modified to only show items in a range?  For example if time is greater than 3?  I tried making all of the a#.time's greater than my range but that didn't work....
Comment: What time? Start? End? Length?
Comment: I guess I meant is it possible to perform the same query as above but limit the query to a certain range over the ENTIRE table.  For example, I am only interested in finding the ranges for the subset of all data tuples where the time is greater than 9.  So essentially get the same results as I would with your original query but omit any data whose timestamps are 9 or earlier.  If i need to write a new question I will :)
Comment: Add `AND WHERE start_time > 9` at the end.
Comment: I tried that but got an error saying I cannot do that 'Error: near "WHERE": syntax error'
Comment: Sorry, I meant `AND start_time > 9`.
Comment: That ALMOST works.  That code will remove the entire cluster of consecutive values, not just the ones in question.  Continuing with my example if I chose `AND start_time > 9` I would expect the first entry in my results to be a single instance of `running` with time stamp 10.  This query as written will remove the entire tuple.
Answer: select a1.activity, min(a1.time), max(a2.time)
from activity as a1
   inner join activity as a2 on a1.activity = a2.activity
group by a1.activity

performance hint: make sure of you have activity index
Comment: This merges the start/stop times of activities that are interrupted by *other* activities.


Pointwise limit of the sequence of functions $h_n(x)=1,\, \forall x\ge 1/n$ and $h_n(x)=nx,\,\forall x\in[0,1/n)$

Question: Pointwise limit of the sequence of functions
$$h_n(x)=\begin{cases}1,&\text{if }x\ge \frac1n\\nx,&\text{if }x\in[0,\frac1n)\end{cases}$$
The trouble with this question is that I think that $h(0)$ is not defined but Im not completely sure. We can see that for any $n\in\Bbb N$ we have that $h_n(0)=0$. But the sequence $h_n(x)=1$ is approaching to zero as well but only reach zero in the limit cause $\lim 1/n=0$.
Are my assumptions correct? It is $h(0)$ undefined?
Comment: You have that $h_n(0)=0$ for all $n$ since $0\in[0,\frac{1}{n})$ for all $n$. So $h(0)=0$. Your point about $h_n(x)=1$ is a different point, that just shows that $h(x)$ is not continuous at $x=0$.
Answer: Assuming that by $h$ you mean the pointwise limit of $(h_n)$: no, $h(0)$ is defined. In fact, $h(0) :=\lim_{n \to \infty} h_n(0) = 0$.
What is confusing you is that $h$ is not continuous. We have for $x > 0$, there exists $k \in \Bbb N$ such that $x > 1/k$, so $h_n(x) = 1$ for all $n \ge k$, thus $h_n(x) \to 1$. This shows that:
$$h(x) = \begin{cases} 0, x = 0 \\ 1, x > 0 \end{cases}$$
Comment: I understand... I get confused due the interval $x\ge 1/n$ and it convergence. But I realized that what define the value of a limit is not the interval, just the points that are converging prior to "reach" the limit.
Answer: You have $h_1(0)=0$, $h_2(0)=0$, $h_3(0)=0$, $h_4(0)= 0$, etc.  So the sequence $h_1(0), h_2(0), h_3(0), h_4(0), h_5(0),\ldots$ is just the sequence $0,0,0,0,0,\ldots$ in which every term is $0$.  That sequence does have a limit and the limit is $0$.  In other words $\lim_{n\to\infty} h_n(0) = 0$.  The limit does exist and is $0$.
If $x>0$, then $\lim_{n\to\infty} h_n(x)=1$.  So this is an example of a sequence of continuous functions converging pointwise to a discontinuous function.


How to handle two ajax request?

Question: Hello i have sequence like this
$(document).ready(function() {

    $("#ctl00_txtsearch").autocomplete({
        source: function(request, response) {
            $.ajax({
            // Here is the code of autocomplete which is requesting
            // data and binding as autocomplete
            });
        });
 });
        var aa=bindonload();
    });

Here is the another function which i want to call on page load
function bindonload() {
    $.get( "minicart.aspx#mydatacontent", function( data ) {
        var resourceContent = data;
        var mini=$(resourceContent).find('div#pnlminicart');
        $('#smallcart').html(mini);
    });
    return false;
}

So , my actual problem is when page is loaded
first of all

bindonload()

called and then autocomplete if textbox have some values right?
But when page is loaded and suddenly i started to write into autocomplete textbox then untill bindlonload function gets executed autocomplete will not work.
I don't have idea how to handle it i have used async:true but its not working i don't want to wait for second process
Thanks in advance....
Comment: var aa=bindonload(); this is for sure not correct. You can not have var inside method call.
Comment: I have @JernejNovak its working all right are you suggesting to do something else?
Comment: Oh sorry. Now looks OK.
Comment: How about if you block the input field until the request ends?
Comment: No request time is not fixed its can take 5-6 seconds and by the way i can not block it
Answer: Well..what i guess..should be..you loaddata() should not be taking too much of time to load.
If there is any way to optimize , look of that.
If you ajax request has a dependency on the other, then you can not make it parallel
If you really intend to make parallel ajax requests, you have to make use of the following:
$.when($.ajax("URL1"), $.ajax("URL2"))
  .then(myFunc, myFailure);

Hope it helps..
Note : The Ajax calls should not be dependent
Updated:
    $.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) ).done(function( a1, a2 )
 {

     // a1 and a2 are arguments resolved for the page1 and page2 ajax requests, respectively.
    // Each argument is an array with the following structure:
    [ data, statusText, jqXHR ]
    var data = a1[ 0 ] + a2[ 0 ]; // a1[ 0 ] = "Whip", a2[ 0 ] = " It"  if ( /Whip It/.test( data ) ) {    alert( "We got what we came for!" );
}});

In the above example , you can see two ajax requests executes parallel
After the two requests are done, i.e on sucess of two functions , the add operation is being performed
Similarly , you can replace $.ajax("/page1.php") with your loaddata() and then
$.ajax("page2.php") with your Auto Complete request.
Both of them will execute Parallely
Comment: nice one but i already have used it i forget to add only its not working
Comment: can you give me one example?
Comment: i still not understand how i will implement this into my question

How to handle two ajax request?


Why doesn't "drush --debug en color" show any output?

Question: Running drush en color from the /xampp/htdocs/drupal directory doesn't output anything. The same happens with drush --debug en color. Why?
Comment: try drush --debug en color and add the output to your question
Comment: Have you tried reinstalling drush? Did you get any errors while installing? Are you starting drush with the .bat file it has for windows?
Comment: Try the answer here:
http://drupal.stackexchange.com/questions/60882/can-i-set-drush-to-always-use-verbose
Answer: It seems that your drush installation is broken. So you have to reinstall it again.
The easiest way would be to install Composer and follow the instructions from drush-ops (especially check Windows section). Then check How to configure Drush on Windows 7?
If this is still happening, check your PATH environment variable if it contains the correct directories (maybe you have some non-drush binary within your system list of folders which could cause some conflict).


Update entries of a dictionary in parallel?

Question: No idea if this is possible, but rather than iterate over a dictionary and modify entries based on some condition, sequentially, I was wondering if it is possible to do this in parallel?
For example, rather than:
Dictionary<int, byte> dict = new Dictionary<int, byte>();
for (int i = 0; i < dict.Count; i++)
{
    dict[i] = 255;
}

I'd like something like:
Dictionary<int, byte> dict = new Dictionary<int, byte>();
dict.Parallel(x => x, <condition>, <function_to_apply>);

I realise that in order to build the indices for modifying the dict, we would need to iterate and build a list of ints... but I was wondering if there was some sneaky way to do this that would be both faster and more concise than the first example.
I could of course iterate through the dict and for each entry, spawn a new thread and run some code, return the value and build a new, updated dictionary, but that seems really overkill.
The reason I'm curious is that the <function_to_apply> might be expensive.
Comment: *Don't* do that. Use ConcurrentDictionary if you want a thread-safe collection.
Comment: @Boo You should never modify an IEnumerable from different threads.
Comment: dictionary is enumerable so it can be used in a Parallel.Foreach loop
Comment: BTW *why* update a dictionary in parallel like this? How many entries do you have and why do you assume that updating the dictionary is slow?
Comment: Depending on your scenarion, you could run `` in parallel, and then "merge" the results in the main thread.
Comment: @Bigiansen I was thinking about update the value, read it too fast and did not notice values where not created, indeed you should not
Comment: Consider the case, multiple keys in the Dictionary refers to same memory location and updating them in parallel is a race condition, so better use ConcurrentDictionary for thread safe update
Comment: @MrinalKamboj there's no `better`. Dictionary will throw if you try to update it from multiple threads
Comment: @PanagiotisKanavos other option would be update inside a lock / mutex, which would work and not throw up AV exception
Comment: @MrinalKamboj At that point just use ConcurrentDictionary
Comment: If you only store *bytes* with an `int` index, a simple array is probably faster *and* uses less memory. A Dictionary calculates int-sized *hashes* for each entry and stores items with the same hash in the same bucket. A hash is Another option could be a `byte` indexed array of `List` that stores the integer values that correspond to the 256 distinct byte values.
Comment: @Bigiansen both are not same, ConcurrentDictionary is convenient but in certain cases an explicit lock for a Dictionary or and Interlock would be faster
Comment: @MrinalKamboj in which case using a *single* thread could be even faster. There's no point in parallel processing if you use *locks*. Remember, parallel doesn't mean *concurrent*
Comment: First calculate all values in parallel, then add\update them in your dictionary, sequentially (now when they are all calculated - it's fast).
Answer:
I could of course iterate through the dict and for each entry, spawn a new thread and run some code, return the value and build a new, updated dictionary, but that seems really overkill.

Assuming you don't need the dictionary while it's rebuilt it's not that much:
var newDictionary = dictionary.AsParallel()
                              .Select(kvp =>
                                     /* do whatever here as long as
                                       it works with the local kvp variable
                                       and not the original dict */
                                     new
                                     {
                                          Key = kvp.Key,
                                          NewValue = function_to_apply(kvp.Key, kvp.Value)
                                     })
                                     .ToDictionary(x => x.Key,
                                                   x => x.NewValue);

Then lock whatever sync object you need and swap the new and old dictionaries.
Answer: First of all, I mostly agree with others recommending ConcurrentDictionary<> - it is designed to be thread-safe.
But if you are adventurous coder ;) and performance it super-critical for you, you could sometimes try doing what you (I suppose) is trying to do in case no new keys are added and no keys are removed from dictionary during your parallel manipulations:
int keysNumber = 1000000;
Dictionary<int, string> d = Enumerable.Range(1, keysNumber)
                                .ToDictionary(x => x, x => (string)null);

Parallel.For(1, keysNumber + 1, k => { d[k] = "Value" + k; /*Some complex logic might go here*/ });

To verify data consistency after these operations you can add:
Debug.Assert(d.Count == keysNumber);
for (int i = 1; i <= keysNumber; i++)
{
    Debug.Assert(d[i] == "Value" + i);
}
Console.WriteLine("Successful");

WHY IT WORKS:
Basically we have created dictionary in advance from SINGLE main thread and then popullated it in parallel. What allows us to do that is that current Dictionary implementation (Microsoft does not guarantee that, but most likely won't ever change) defines it's structure solely on keys, and values are just assigned to corresponding cells. Since each key is being assigned a new value from single thread we do not have race condition, and since navigating the hashtable concurrently does not alter it, everything works fine.
But you should be really careful with such code and have very good reasons not to use ConcurrentDictionary.
PS: My main idea is not even a "hack" of using Dicrionary concurrently, but to draw attention that not always every data structure need to be concurrent. I saw ConcurrentDictionary<int, ConcurrentStack<...>>, while each stack object in dictionary could be accessed only from single thread and that is an overkill and doesn't make your performance better. Just keep in mind what are you affecting and what can go wrong with multithreading scenarios.
Comment: You can surely access keys in parallel, but problem would be then value is not an immutable type, its better to create a local value and then assign to the key as in the answer by @nvoigt
Comment: @MrinalKamboj, I agree, but it's mostly other topic, not specifically  related to Dicrionary and nobody here mentioned which value type does OP use.
Comment: *"current Dictionary implementation [...] but most likely won't ever change"* -- What is the current implementation? The implementation of .NET Core 2.1? The implementation of .NET Framework 4.7.1? Have you verified that your code is safe on all previous and subsequent .NET versions and platforms? I am not a fan of hacks like that, because I don't want to impose on myself the obligation to scrutinize the source code of each and every MS .NET runtime version, in order to assert the correctness of my code.
Comment: @TheodorZoulias, all those versions of .NET have exactly the same behavior regarding my 5-year-old comment: "in case no new keys are added and no keys are removed from dictionary during your parallel manipulations" (and of course, different threads should manipulate on values of different keys) - you should be fine.
Moreover, I cannot imagine ANY implementation of a hash table, which wouldn't be thread-safe under those circumstances. This is easy to prove: if hash-table structure was dependent on values, - you wouldn't be able to identify location by key, - so it's not, and can never be.
Comment: There are numerous benchmarks showing ConcurrentDictionary<> being ~5-10 times slower than Dictionary<> (and similar magnitude on memory consumption difference). If performance isn't too critical (which is the case for 99% of projects), - with no hesitation go with ConcurrentDictionary! But if you cannot have such a luxury, - you have to be creative and understand what you are doing really well.


Get to neighbor jquery

Question: I have part of HTML. I need write jquery script, which change "Error" to "Valid"
Phone: <input type="text" name="Phone" title="title1" value="(XXX) XXX-XXXX">

 Error!//REplace here to "Valid"

My Jquery:

Comment: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide
Comment: @adeneo hahaha, just fill in this comment with everything RocketHazmat said.  Good to know.  :)
Answer: You need to find the 2nd next sibling element and its child
$(document).ready(function(){
    var test = $('input[title="title1"]');
    test.next().next().children().text('valid')
});

Demo: Fiddle
Another way is to find the next span sibling like
$(document).ready(function(){
    var test = $('input[title="title1"]');
    test.nextUntil('span').last().next().children().text('valid')
});

Demo: Fiddle
Answer: Try,
$(document).ready(function(){
   var xEle = $('input[title="title1"]');
   xEle.next().next().find("span[role='alert']").text('valid')
});

DEMO

Get to neighbor jquery


Attach Event Handler ".on()" on dynamic button

Question: I have a button which is dynamically added on the page (via mustache).
There is a class on it.
But when I click on this button, the JQuery method is not executed.
My HTML:

My HTML with the dynamically added button:

    Hello

My jQuery:
$(function(){
    $('.hello').on('click', function(e){
        e.preventDefault();
        console.log('Hello');
    });
});

Comment: put the code that creates the button and i will help
Answer: You can't use on() on elements that dont exist, asign them to the first wrapper that exists (ideally an id), and use another parameter to tell jQuery to look for the class in the selector:
$('#layout').on('click', '.hello', function(e){ /* ... */ });

"Can't I just add everything to document?"
Yes you could, but you shouldn't. Everytime you click on something, it goes up the DOMtree:
 1. You click a button, it fires the click event
 2. while there is a parent, trigger the click event for the parent aswell
 3. After you did the last (document), stop.
As you can see, step 2 could be a heavy step if you have lots of html. Binding events as 'local' as possible is the prefered method.


validação de formulario na mesma página

Question: Olá, para que o formulário seja validado na mesma página, o que é mais seguro como valor para o atributo 'action' html? Obrigado.
    <form method="post" action="">

    <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

Comment: O action é um URL. Tem de ser um valor válido para URL, um destino que o servidor aceite. Não percebo porque usar `htmlspecialchars()` ou porque pensar que ele não é seguro.
Comment: Olá nilson, não está claro qual é sua dúvida. Passando a URL pelo htmlspecialchars o que você está tentando fazer?
Comment: @RafaelMenaBarreto, vou estudar ajax. Eu queria um norte e consegui com a ajuda de vcs, obrigado.
Comment: Sugiro que você pesquise sobre Jquery + ajax, alem de fazer a mesma coisa, é mais elegante ao usuario, e não precisa dar refresh na pagina;
Comment: O objetivo é que as mensagens de erro, ou de sucesso de envio, permaneçam na mesma página. Mas, parece que devo pesquisar melhor, para evitar o refresh na página, como foi sugerido. Obrigado.
Comment: @Nilson veja esse exemplo basico de uso. http://forum.imasters.com.br/topic/514131-envio-de-formulario-com-ajax/
Comment: Opá, vou estudar sim esse exemplo, obrigado. Uma dúvida, nesse caso, o script php que valida o formulário, não precisa ficar na mesma página do formulário? Minha duvida começou ao tentar fazer isso da forma com descrito no exemplo baseado em estudos feitos aqui http://www.w3schools.com/php/php_form_validation.asp e descobrir que usando htmlspecialchars($_SERVER["PHP_SELF"]) evitaria a manipulação da url por terceiros, já que o valor atribuído a action, nesse caso, viria da url atual. E depois, pesquisando mais, achei esta outra forma: action="", que disseram ser mais segura. Blz, vou estudar +
Comment: @Nilson não há como evitar manipulação de absolutamente nada que venha do lado do usuário. A aplicação (lado do servidor) tem que estar sempre preparada para isso.
Comment: @Nilson não precisa ser a mesma página no action. Não precisa nem ter action no form, dependendo de como tu vai fazer a requisição ajax.
Answer: 1º Não inventa.
2º Não é uma questão de qual é melhor, deves saber o que faz cada um.
htmlentities codifica qualquer caractere especial, de modo que não seja possível injectar tags ou algum js.
Deixar o atributo action vazio, faz com que essa página referencie a si mesma. Por isso não desperdices funções usando-as onde não são necessárias, porque o que o PHP_SELF faz, é retornar o nome do ficheiro que está a executar o script, por isso, se não há QUERY_STRING porquê devo eu utilizar o htmlentities ou urlencode ? Simplesmente não deves, porque a principal razão para usa-las, é retornar estes valores no formato certo, para que possam ser usadas sem problemas, isso caso existirem.
Um exemplo disto é:
<?php
    echo ''."\n";
?>

A url contém parâmetros, logo possui caracteres especiais que precisam de ser escapados, mas o que faz o urlencode aí ? Simplesmente faz o que faz, quando ser quer passar o valor de uma variável como parte de uma url, é aí que se torna útil.
Eu diria o que muita gente diz normalmente em situações como esta, usa uma biblioteca js qualquer, ou usa simplesmente o js, e o teu problema desaparece.
Seria fácil pensar assim, devido ao avanço tecnológico até os sites mais simples utilizam javascript, sendo que grande parte dos dispositivos atualmente usados para acessar estes sites possuem também suporte ao javascript. Mas é o que é, javascript pode falhar, uma ou outra vez, e há vezes em que simplesmente alguns preferem não usar, mas isso já é outra perspectiva.
Analisa melhor as tuas prioridades, e procure uma solução que se adeque a ti.
Se quiseres ler mais sobre sobre alguns destes processos, eis algumas páginas que recomendo:

Dealing with Forms
PHP and HTML
Comment: Obrigado pela sugestão, vou continuar estudando, e quando estiver mais bem preparado, retorna aqui.
Comment: Experimenta trabalhar com exemplos práticos, é melhor forma entender o comportamento destas funções e atributos.
Answer: Qualquer valor. A action não influencia em validação por parte de cliente. A validação em página normalmente é feita em JS, e o PHP tem pouco papel nisso.
Neste caso, uma ótima opção é o jQuery Validation. Veja funcionando aqui.

validação de formulario na mesma página


Estimating variances components for a 2-way structure with all factors random using r

Question: My data is a balanced 2-way structure with weight as the response, and day and operator as the random factors. I want to obtain the estimates of the variance components for the main effects and the 2-factor interaction. I have tried using the function lmer in r, where I can include the main effects, i.e. lmer(weight~(1|dia)+(1|opdr), data=balz), but I cannot find a way to include the interaction.
Thank you for your help. JC
Answer: The lmer does not accept the specification of the model as 1|AB or as 1|A + 1|B + 1|AB.  I obtained the desired results specifying the model as 1|A + 1|B + 1|A:B.
JCF


Different views for taxonomy terms

Question: I am having vocabulary containing hierarchical taxonomy like this :

Category1

subcategory1

lastcategory1
lastcategory2

subcategory2

category2

I am using pathauto to taxonomies path .
Path are like this :
www.example.com/category1
www.example.com/category1/subcategory1
www.example.com/category1/subcategory1/lastcategory1
At first path i want to show all subcategories taxonomy of category1 .
At second path i want to show taxonomy detail page of subcategory1 and below details i want to show subcategories  of subcategory1 taxonomy .
At last path i want to show content connected to lastcategory1 taxonomy .
How can i accomplish this using views .
Note : I don't want to change the taxonomy paths . I am using drupal 7
Answer: See this tutorial. Looks like it does exactly what you ask.
The tutorial includes a video but here is the written explanation:
1) Create a Taxonomy Vocabulary here: admin/structure/taxonomy (And create a few terms)
2) Create a Taxonomy View here: admin/structure/views/add
You want to make sure that you choose "taxonomy" entities.
3) Add a contextual filter for "Taxonomy term: Parent term"
Make sure to select "Default Filter" and choose "Taxonomy term from url." Also, specify a "Default validation criteria" for "Taxonomy term" and choose "Convert taxonomy name to ID" and select "Transform dashes in url..."
4) Add a new page to this view, remove the contextual filter from this view and add a filter for "Taxonomy term: Parent term" and set it to "equal to" and leave the field there blank.
5) Save that view and create a new view here: admin/structure/views/add
Make sure this view is for a "Content" of type "Product Display" (or whatever entity bundle has the field for your taxonomy terms).
6) Add a contextual filter for your taxonomy term, mine was called "Product Categories"
Make sure this contextual filter displays "Contents of No Results." Also, specify a "Default validation criteria" for "Taxonomy term" and choose "Convert taxonomy name to ID" and select "Transform dashes in url..."
7) Add a "No results" item called a "View Area" and select "Page_1" from your first view (this is the second page we created)
8) Save this view and go back to the first view.
9) Add a "No results" item called a "View Area" and select the second view that we just made.
10) Make sure your title field in the Taxonomy View doesn't link to the taxonomy term, but it outputs the field as a link to "catalog/[name]" that way your catalog names are clickable
Comment: While that link provides an answer to the question. It would be better to add necessary part here. Link only answers became invalid if the link changes
Comment: Have updated to show step by step instructions.
Comment: @Lance1412 i have written i don't want to change the taxonomies path and accoriding to this tutorial i have to make cutom path . I want three different view on taxonomt term path i.e taxonomy/term/% .

Different views for taxonomy terms


What type of rich response google uses to display flight info in the assistant

Question: I am trying to create a similar rich response to what google provides for the flight status and was wondering what kind of rich response they use to display this fancy formatting? Is that just a dynamically generated image? Thanks.
screen shot
Answer: I think The card/response in the above image are custom cards built by google, Maybe there is no option to replicate those once unless you work with Google, But as of now the only responses/cards you can build are here.
Comment: I think you are right. It's a bit anti-competitive but what's new, it's google.


String Similarity for all possible combination in Optimised fashion

Question: I am facing a problem while finding string similarity.
Scenario: The string which consisits of following fields
first_name, middle_name and last_name
What I have do is to find string similarity between A and B (both have same fields) but making sure all possibilities are considered.
Case 1:
say string A has first name is : Rahul
middle name is: Kumar
last name is : " "
And string B has first name : Kumar
middle name: " "
last name: Rahul
By seeing we can say both names might be same. But Current Similarity algorithms are giving around 71% similarity.
Case 2:
Say, string B has first name : Rahul
middle name: " "
last name: K.
In this case similarity %age falls down, but the name might be same.
What should I do to similarity ,considering all possibile combinations of first,middle and last name and in an optimised fashion?
E.g Rahul Rakesh Kumar can be written as
Rahul Kumar
Rahul
Rahul K.
Kumar Rahul
Kumar rakesh Rahul.
Rahul R. Kumar   etc.
I had tried using Jaccard, Cosine, Jaro-Wrinklr similarity algorithms but result are not satisafactory.
Note: I have to find dedupe based on Names that's why I have to consider all possible of Names.
Answer: For this kind of string similarity I have recently implemented an algorithm that works great for my use-case, which is very similar to yours. Here is the blog post: http://www.catalysoft.com/articles/strikeamatch.html
To compare two strings:
1. Make a list of overlapping letter-pairs. "kumar" gives us pairs: "ku", "um", "ma", "ar".
2. Say the second string is "maria". Pairs: "ma", "ar", "ri", "ia".
3. Count how many pairs are the same: "ma" and "ar".
4. The similarity is computed as: 2 * same_pairs / (pairs_1 + pairs_2) = 2*2/(4+4) = 0.5

The great thing about this algorithm is that it considers the ordering of the strings by using letter-pairs, which are ordered. Then on the other hand it does not consider ordering, because all pairs can be mixed in any order. This makes it perfect for my specific use case, where similar to your situation, I want to treat "abc def" as exact match to "def abc".
You can also modify the algorithm. Part of my use-case is searching a short string in a longer text. For this I will use the similarity measure same_pairs / pairs_1, number of same pairs over pair count in the search term. If a word appears in the text, this gives me similarity 1.0, no matter how long the search text is. The similarity described above will penalize longer texts in this case.
Another note on the implementation. You can make it really efficient and robust. I first reduced my alphabet to lower-case letters, digits and space. That is 26+10+1 = 37 symbols. I map A to a, ä to a etc. The number of possible letter pairs is now 37*37 = 1369. The way I count my pairs is by using an array pairCounts [37*37]byte where pair aa maps to 0, ab maps to 1 etc. So if I find pair ac in the string, ac maps to index 2, so I say pairCounts[2]++. Each pair can appear 256 times (I use byte) this way.
Normalizing the letters make it case-insensitive, using an array instead of a full-blown map makes it run really fast.
Comment: Re your Java implementation on the linked blog post: I think it should use hash maps rather than array lists to run in O(n + m) where n, m are the lengths of the two strings. Currently it runs in O(nm).
Comment: I was just updating my answer as you typed this. This run-time can be greatly improved by using a simple array.
Comment: Upvote the ques guys and Thanks for your suggestions.


How to efficiently compare an array of objects with another array in JavaScript?

Question: I have a function where I have to return an array of elements with matching filters. Here's the function code:
filter_getCustomFilterItems(filterNameToSearch: string, appliedFilters: Array<any>) {
   let tempFilterArray = [];
   let masterFilterList = getMasterFilterList();
   /*
   filterNameToSearch can be a string either as `Item2` or `Item3`

   masterFilterList will be of type
   masterFilterList: Array<any> = [
   {
      Item1: 'some-item-1',
      Item2: 'some-item-2',
      Item3: 'some-item-3',
      Item4: 'some-item-5',
   },
   {
      Item1: 'some-item-10',
      Item2: 'some-item-11',
      Item3: 'some-item-12',
      Item4: 'some-item-13',
   },......
  ];

  appliedFilters will be of type
  appliedFilters: Array<any> = [
   {
      name: 'Item1',
      filters: [
          {value: 'some-item-1', status: 'selected'},
          {value: 'some-item-10', status: 'selected'}
      ]
   },......
  ];
 */

 for (let masterFilterItem of masterFilterList) {
   //Missing logic here
 }
}

I would like to filter the masterFilterList to return an array of items
filterNameToSearch = 'Item2' under the following conditions:
1) for each array element (assume appliedFilterItem) in appliedFilters, compare appliedFilterItem.name with masterFilterItem[appliedFilterItem.name] and check if any of the filters in appliedFilterItem has the same value as masterFilterItem[appliedFilterItem.name]
2) The condition has to look like something like masterFilterItem[appliedFilterItem[0].name] == appliedFilterItem[0].filters[0].value && appliedFilterItem[0].filters[0].status === 'selected' && masterFilterItem[appliedFilterItem[1].name] == appliedFilterItem[1].filters[0].value && appliedFilterItem[1].filters[0].status === 'selected' and so on for all appliedFilterItems. But the number of elements in the appliedFilters is dynamic.
So please help me out with this issue?
Comment: Its unclear what your required output is
Comment: The output will be an array of items in `masterFilterList`, with the conditions applied. If given filterNameToSearch = "Item2", it has to return all `Item2` elements in `masterFilters` with conditions from `appliedFilters`
Answer:   return masterFilterList.map(el => el[filterNameToSearch])
      .filter(value =>
         appliedFilters.some(({name, filters}) =>
            name === filterNameToSearch &&
            filters.some(filter =>
              filter.status === "selected" &&
              filter.value === value
            )
         )
      );


How to solve this trig equation , $\tan^{-1}(x) = 1 / \tan (x)$?

Question: Given the equation $$\tan^{-1}(x) = \frac{1}{\tan(x)},\quad x\in[0,2\pi],$$ find the value/values of $x$.
I tried to take $\tan (x)$ for the both sides but the equation had more complicated !
Comment: I doubt if yu can find an analytic solution.  Graphing can get you approximations, which can be refined by Newton's method.
Comment: What is $\tan ^{-1}x $? Is it $\arctan (x) $ or $1/\tan (x) $?
Comment: Where is this coming from ?
Comment: tan−1(x) = arctan (x)
Comment: I wrote it , And it has solutions , but i don't know how to find them handly .
Answer: I believe you will not be able to find exact solutions, only numerical. However, as you note, it does have solutions, it has $2n$ solutions in every interval of the form $[-n \pi, n \pi]$.
Comment: In fact, there is a single solution for each $[k\pi, (k+1)\pi]$ interval. Moreover, if $x $ is a solution,  $-x $ is a solution as well.
Answer: There are two solutions in the given interval and you can find them only numerically.


Is it possible to synchronize contents of a directory only?

Question: With the following task
- name: synchronising ...
  synchronize: src=files/to/synchronize dest=/tmp/1

the files/to/synchronize directory is synchronized, and after it's done there is a /tmp/1/synchronize directory on the target machine.
Is it possible to use the syncrhonize task to recursively synchronize only contents of the source directory, so that all its contents was in the /tmp/1 without extra level of depth?
What I've done:

I went through documentation
I tried to google
I went through ansible synchronize module source
Comment: Try adding a trailing slash to the source directory, ie `src=files/to/synchronize/`.  As for the downvote, mouse over the down arrow; the popup says "*This question does not show any research effort; it is unclear or not useful*".  Downvotes without comment may be presumed to be for at least one of those reasons.
Comment: take a look at the documentation. `dirs=yes` parameter (_Transfer directories without recursing_) might be what you are looking for.
Answer: All you need to do is add a trailing slash to the end of the source path.  This will tell Ansible it is the files in the directory, and not the directory and its contents, that you want to transfer.
This behaviour is identical to that of rsync.
Comment: Yes, and it's in the `rsync` man page ("*A trailing slash on the source changes this behavior to avoid creating an additional directory level at the destination*").  You may or may not wish to see some linkage between your not finding that in your extensive research phase and the downvotes you complain so loudly about.
Comment: Slash did the job, and wildcard turns it into "file not found" - there is no shell to expand it. Thanks. Is there an official explanation for the behaviour?
Comment: I don't think there is a reference... This is just the way such commands work by convention.  I am not sure if it is in POSIX anywhere but it might be.
Comment: @zerkms No.  In your question *as originally written* you gave no indication of what work, if any, you had done on the question before answering it.  That, coupled with a basic spelling error in the title, didn't speak well of its quality, and (possibly because of that) it started collecting downvotes.  Now, you've improved the question, we've fixed the spelling error, and no more downvotes are appearing.  **This is the system working as it should.**  You might want to relax a little!
Comment: `s/answering it/asking it/   # my bad!`
Comment: @zerkms not by me; only a moderator can do that.  Seriously, please consider what that says about how your argument is seen, step back and have a cup of tea, and relax.  Continuing to chase this issue may not end well.
Comment: @zerkms the discussion here would be better served by meta.serverfault.com.
Comment: @FalconMomot I completely agree, and had posted a comment to that effect (which I edited away when zerkms' comment was removed, because it looked odd in isolation).  Me, I'd advise against escalating it to meta, but it's his/her right, and it's definitely the appropriate forum for this issue.
Answer: example of coping only the content current directory to the remote one:
- name: copy project to remote location
  synchronize:
   src: "./"
   dest: "/better_spots"


Greek letters in R legend

Question: How can I add greek letters like "gamma" in the legend?

My program:
library(FAdist)
x<-seq(0,6,length=200)
gf1<-function(x)
dlnorm3(x,shape=1,scale=0,thres=0)
gf2<-function(x)
dlnorm3(x,shape=1,scale=0,thres=1)
gf3<-function(x)
dlnorm3(x,shape=1,scale=0,thres=2)
plot(x,gf1(x),type='l',lty=1,cex=5,xlab="X",ylab="f(x)",lwd=2)
lines(x,gf2(x),type='l',lty=2,lwd=2)
lines(x,gf3(x),type='l',lty=3,lwd=2)
legend(x=4.3,y=0.5,paste("  =",c(0,1,2)),lty=1:3,lwd=2)

Comment: I really wish people wouldn't downvote these questions.  It's not a bad question; it's just off topic.  A close vote is more appropriate.
Comment: Answered dozens of times on SO. [Try this search](http://stackoverflow.com/search?q=[r]+expression+greek+legend)
Answer: expression(gamma)
This page has more information on how to add such annotations.

Greek letters in R legend


Is this an example of a univariate analysis?

Question: Nonstatistician needs help with terms.
Is the following an example of a univariate analysis?: Chances of getting a job at Microsoft with respect to demographic variables such as age, gender, race, etc. The odds are calculated both for individual variables (say, gender) and for combinations of variables (say, gender + age). What's the best way to describe such a study?

This study consists of a _______ analysis of Microsoft employees to determine the correlation between getting a job at Microsoft and demographic variables such as ...

What's stumping me is the presence of multiple variables, so how can this be a univariate analysis?
Comment: In a regression setting, we typically use "multivariate" with respect to the response. An example of a multivariate regression variant of what you posted is one variable measuring the probability of working for Microsoft and one variable measuring the probability of having a dog.
Answer: This is a great question.  Univariate means you have a single outcome you are studying -- chances of getting a job.  To describe the multiple factors involved in analyzing this outcome, you would describe the analysis as multivariable.  This refers to the independent variables age, gender, etc.  The study could be described as both univariate (one outcome) and multivariable (many factors).  The term multivariate would describe analyzing more than one outcome in the same analysis.
Comment: Hi: both answers  above were great but just to add  slightly to this: if you have muitiple independent factors-variables, then rather than referring to this as multivariate analysis ( because, as Geoffrey pointed out,  the term multivariate analysis is referring to the response ), they refer to this case as multiple regression.. If you had multiple responses in the regression setting, this would be referred to as multivariate regression. So, definitely the terminology can be confusing. Usually, one can figure out the setting from the context and not worry too much about the  terminology.
Comment: Aha! I see I was confusing "multivariate" with "multivariable." Thanks so much for clarifying the difference! So I think this should be written as: "This study consists of a univariate analysis of Microsoft employees to determine the correlation between getting a job at Microsoft and demographic variables such as . . ."
Comment: Given that this is an intersectional study that also considers combinations of variables, is there anything I need to add to that basic description of the study?


Como faz para quando o usuário tocar no simbolo do menu aparecer a mensagem no Toast?

Question: Tenho esse método mas ele nao funciona o que faço? :(
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    super.onCreateOptionsMenu(menu);

    getMenuInflater().inflate(R.menu.menu, menu);
    MenuItem menuTeste = menu.add(0, 0, 0, "Item teste");
    menuTeste.setIcon(R.drawable.adcsimbolo);
    menuTeste.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
    return true;
}

  public boolean onMenuItemSelected (MenuItem menuItem){
    //super.onMenuItemSelected(add,menuItem);
    switch (menuItem.getItemId()){
        case 0 :
            Toast.makeText(CadastroActivity.this, "Tocado", Toast.LENGTH_SHORT).show();
            break;
    }
    return true;
}

}
Answer: Se você está inflando o layout do menu, você pode adicionar o item lá no xml mesmo, não precisa ser programaticamente.
exemplo:
<menu
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/item_teste"
        android:icon="@drawable/adcsimbolo"
        android:title="Item teste"
        app:showAsAction="always" />

</menu>

E pra pegar o item que foi clicado e mostrar o Toast, pegue pelo ID.
exemplo:
switch (menuItem.getItemId()){
   case R.id.item_teste:
       Toast.makeText(CadastroActivity.this, "Tocado", Toast.LENGTH_SHORT).show();
   break;
}

Answer: Tente trocar  onMenuItemSelected  por onOptionsItemSelected!
Segue um exemplo:
@Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()){
            case 0 :
                Toast.makeText(this, "Tocado", Toast.LENGTH_SHORT).show();
                break;
        }
        return true;
    }


How can I minimize future long-term reward in deep Q-learning?

Question: I'm trying to implement deep Q-learning on a problem were the rewards the agent receives are errors from another model. The RL agents job is to minimize the long-term reward (error) instead of maximizing it as is typically the case in Q-learning.
So what I wonder is, how can the conventional DQN target value equation:
$$\mathrm{Target} = r + \gamma * \max(Q(s'))$$
be rewritten for RL problems were the feedback from the environment (reward) should be minimized instead of maximized?
(I realize that multiplying the error with negative 1 converts any minimization problem to a maximization task, but for sake of brevity I won't dwell on why that's not ideal to do in my situation).
Comment: Since multiplying by $-1$ is the easiest answer, and the only one that immediately comes to mind, I think you should indeed explain why this is not possible for you.
Answer: There are two changes you must make if you want to minimise a cost instead of maximise a reward.

Change the Q value TD target to

$$\mathrm{Target} = r + \gamma * \min_{a'}(Q(s', a'))$$
NB I have added in the action to be explicit what the minimisation is over, it should be in your formula too. Also kept with the symbol $r$, although you might want to go with $c$ for cost.

Action selection should be based around minimum Q value. E.g. the greedy action choice in state $s$ is now $\text{argmin}_{a} Q(s,a)$

As commented on your question, there is not usually a good reason to do this, when you can just use negative cost as a reward. However, you may see this used in e.g. zero-sum games, alternating between min and max operations depending on the player.
Comment: That was exactly the answer I was searching for! Thank you, I will try it out!


Como evitar que o evento focusout dispare ao minimizar o navegador?

Question: Estou usando o evento focusout para chamar uma função quando o campo perder o foco. O problema é que quando eu minimizo a janela do browser, o evento dispara, pois parece perder o foco. O Mesmo ocorre, quando a função calcular_financeiro_parcela_movimento_calculos_padrao() efetua uma chamada ajax, pois parece que o foco se perde e o evento dispara.
Existe alguma forma de impedir que o evento focusout dispare nessas situações?
$('#txt-financeiro-parcela-movimento-valor-pago').focusout(function (e) {
    e.preventDefault();
    calcular_financeiro_parcela_movimento_calculos_padrao();
});

function calcular_financeiro_parcela_movimento_calculos_padrao(tipoCalculo = FINANCEIRO_PARCELA_MOVIMENTO_CALCULOS_PADRAO_TIPO_CALCULAR_APENAS_PERCENTUAIS) {

    //startLoadGlobal(SPINNER_CALCULAR_VALOR_PARCELA);

    var financeiroParcelaId = $('#hid-financeiro-parcela-movimento-financeiro-parcela-id').val();

    var valorASerPago = $("#txt-financeiro-parcela-movimento-valor-a-ser-pago").val();
    var valorPago = $("#txt-financeiro-parcela-movimento-valor-pago").val();
    var valorTotal = $("#txt-financeiro-parcela-movimento-valor-total").val();
    var valorJuros = $('#txt-financeiro-parcela-movimento-valor-juros').val();
    var percentualJuros = $('#txt-financeiro-parcela-movimento-percentual-juros').val();
    var valorDesconto = $('#txt-financeiro-parcela-movimento-valor-desconto').val();
    var percentualDesconto = $('#txt-financeiro-parcela-movimento-percentual-desconto').val();
    var valorMulta = $('#txt-financeiro-parcela-movimento-valor-multa').val();
    var percentualMulta = $('#txt-financeiro-parcela-movimento-percentual-multa').val();
    var valorDesconto = $('#txt-financeiro-parcela-movimento-valor-desconto').val();

    var financeiroParcelaMovimentoCalculosPadraoViewModel = {
        FinanceiroParcelaId: financeiroParcelaId,
        FinanceiroParcelaMovimentoCalculosPadraoTipo: tipoCalculo,
        ValorASerPago: valorASerPago ? converterFormatoMoedaBrasileiraParaFormatoPadrao(valorASerPago) : 0,
        ValorTotal: valorTotal ? converterFormatoMoedaBrasileiraParaFormatoPadrao(valorTotal) : 0,
        ValorPago: valorPago ? converterFormatoMoedaBrasileiraParaFormatoPadrao(valorPago) : 0,
        ValorJuros: valorJuros ? converterFormatoMoedaBrasileiraParaFormatoPadrao(valorJuros) : 0,
        PercentualJuros: percentualJuros ? converterFormatoMoedaBrasileiraParaFormatoPadrao(percentualJuros) : 0,
        ValorMulta: valorMulta ? converterFormatoMoedaBrasileiraParaFormatoPadrao(valorMulta) : 0,
        PercentualMulta: percentualMulta ? converterFormatoMoedaBrasileiraParaFormatoPadrao(percentualMulta) : 0,
        ValorDesconto: valorDesconto ? converterFormatoMoedaBrasileiraParaFormatoPadrao(valorDesconto) : 0,
        PercentualDesconto: percentualDesconto ? converterFormatoMoedaBrasileiraParaFormatoPadrao(percentualDesconto) : 0
    };

    var dataParameter = $.param(financeiroParcelaMovimentoCalculosPadraoViewModel);

    $.ajax({
        url: "/financeiro-parcela-movimento-gerenciar/financeiro-parcela-movimento-calcular-valores-padrao",
        type: "GET",
        data: dataParameter,
        traditional: true,
        success: function (data) {

            stopLoadGlobal();

            if (typeof data.success !== 'undefined') {
                if (!data.success) {
                    swal("Oops", data.message, "error");

                    return false;
                }
            }

            $("#txt-financeiro-parcela-movimento-valor-a-ser-pago").val(data.financeiroParcelaMovimentoCalculosPadrao.valorASerPago.toLocaleString('pt-br', { minimumFractionDigits: 2 }));
            $("#txt-financeiro-parcela-movimento-percentual-desconto").val(data.financeiroParcelaMovimentoCalculosPadrao.percentualDesconto.toLocaleString('pt-br', { minimumFractionDigits: 2 }));
            $("#txt-financeiro-parcela-movimento-percentual-juros").val(data.financeiroParcelaMovimentoCalculosPadrao.percentualJuros.toLocaleString('pt-br', { minimumFractionDigits: 2 }));
            $("#txt-financeiro-parcela-movimento-percentual-multa").val(data.financeiroParcelaMovimentoCalculosPadrao.percentualMulta.toLocaleString('pt-br', { minimumFractionDigits: 2 }));
            $("#txt-financeiro-parcela-movimento-valor-total").val(data.financeiroParcelaMovimentoCalculosPadrao.valorTotal.toLocaleString('pt-br', { minimumFractionDigits: 2 }));
            $("#txt-financeiro-parcela-movimento-valor-pago").val(data.financeiroParcelaMovimentoCalculosPadrao.valorPago.toLocaleString('pt-br', { minimumFractionDigits: 2 }));
        },
        error: function () {
            stopLoadGlobal();
            alert("Oops! Algo deu errado.");
            return false;
        }
    });

Answer: Penso que a única forma de conseguir impedir este comportamento é utilizando uma flag de controlo. Veja o seguinte exemplo:

let windowFocused = true;

$(window).blur(function(){
  windowFocused = false;
});

$(window).focus(function(){
  windowFocused = true;
});

$('#txt-financeiro-parcela-movimento-valor-pago').focusout(function(e) {
  setTimeout(() => {
    if (!windowFocused) return;

    e.preventDefault();
    console.log('Focus out ...');
  }, 0);
});

<input type="text" id="txt-financeiro-parcela-movimento-valor-pago" />
Comment: Não sei como agradecê-lo @dfvc. Funcionou corretamente :)