Mathematical tripos part III at Cambridge University

Question: I am currently pursuing a Bachelor+Master program in mathematics and physics. While the material is very interesting, I feel it sometimes is lacking in the mathematical rigour necessary for Phd studies in mathematics.
A while ago, I discovered the one-year Master program (part III of the tripos) in mathematics at Cambridge University, and it seemed to feature a lot of highly interesting material. I think it would be a nice complement to my current program, and I am very interested in taking the course.
My only concern is, that at the time of graduating from my current program, I will be 26 years old. Would this be much too old for taking the part III course, and also, would I, upon (hopefully) completing the course, be too old for pursuing a Phd at a good university?
Thanks!
Comment: FWIW, when I took Part III, most of the students were 21--22, but certainly a nonzero number were older, some 30+. As long as you're prepared for the course, age shouldn't be a factor.
Comment: No. 27 is not too late to start a PhD, and not much older than 26 if you skipped the Masters program anyway. Many people have made a contribution to mathematics after late starts. Besides, you are not wasting that year. During that one year masters you are still learning standard material, which is what you do when you start a PhD.
Comment: @GitGud As a student there, your assertion is correct. While our first two terms aren't too stressful, the exam terms are probably best described as hell. And thanks Zhen Lin, I guess I now know what to aim for in my third year (for those curious, the top 40% corresponds to the top quarter of $2.1$'s and higher).
Comment: Thank you for your reply. But would you say it's very late to start part III of the tripos at 26? Since the BA program is 3 years in UK and since most students begin their undergraduate studies at the age of 18, I guess most students who take the part III are 21. Do you happen to know if there are any "older" students taking the part III?
Comment: @AsalBeagDubh Thank you for your comment! How old would you say that some of the older students were?
Comment: Is the [mature student](http://www.study.cam.ac.uk/undergraduate/access/mature/) thing relevant in anyway?
Comment: @GitGud By the looks of it, the link is useful for when considering colleges to apply to, but I can't see much for the specific Faculty - it also seems to apply mainly for Undergraduate programs, and not grad ones. While age can sometimes be a factor when applying for the undergraduate BA program in Maths, I'm fairly sure that this isn't case for the Masters/Graduate programs.
Comment: @GitGud Thank you for your reply! I do not think the "mature student" thing is relevant if I already have a degree. The "affiliated student" was something I hadn't heard about before, but I guess it would only be relevant if I wanted to take the BA (which (hopefully) would not be necessary).
Comment: @AndrewD Agreed. However part III is part of their undergrad course, I believe.
Comment: @J.F.Sebastian Anyway, I wish you luck. You shoulkd also consider asking about this at [Academia S.E.](http://academia.stackexchange.com/).
Comment: @GitGud For the undergraduates, we can automatically go onto Part III if we get a first in Part II; otherwise we can appeal to the Graduate Board, and if the person has a high enough 2.1 and a few good words by their Director of Studies, they can also go onto Part III. While for us the Masters/Part III is indeed intergrated, we can only go onto it under certain conditions.
Comment: @AndrewD Interesting, thanks. What does 'high enough 2.1' mean?
Comment: @GitGud Thank you, and thank you for the link that you provided!
Comment: @GitGud It is the second-highest degree classification one can get in universities in England.
Comment: @GitGud Unfortunately the vagueness is because there is no well-defined cutoff (or at least of that I'm aware of). Certainly if you were the highest rank person with a $2.1$, then you could be allowed on, but even if you had a mid $2.1$ you could presumably continue on - I would assume the Graduate Board would look at the person's supervision reports and hear what their Director of Studies has to say; if a person was really talented but happened to have a nightmare during the exams, I doubt that would stop their progression onto Part III.
Comment: @ZhenLin [this](http://en.wikipedia.org/wiki/British_undergraduate_degree_classification#Upper_second-class_honours), got it. Thanks.
Comment: @AndrewD Seems like students there are constantly under huge pressure.
Comment: @AndrewD You _should_ be in the top 40%: see [here](http://www.maths.cam.ac.uk/postgrad/mathiii/partiimeeting/), but it's not a hard rule.
Comment: @AndrewD Can I invite you to a chat room? I'm curious about how stuff works there. Zhen Lin, OP and whoever else is interested in welcome.
Comment: @GitGud Sure (adding more characters...)
Comment: An additional question: My university uses a grading system 1-5, where 5 is the highest and usually corresponds to 80%+ on exams. Because this grading system does not contain anything equivalent of the usual 'A', do you think it will be difficult to convert the grades in a satisfactory way?
Comment: Guys, try to join the [chat room](http://chat.stackexchange.com/rooms/10524/a-d-g-g-j-f-s-and-z-l).
Comment: @J.F.Sebastian I assume the University would get in contact with your University to get specific details.
Comment: @AndrewD Alright, I guess that makes sense.
Comment: I've been following your discussion in the chat room. Unfortunately I could not join due to a lack of rep, but I still got some useful info. Thanks! I have to log off now.
Answer: Personally, I would suggest emailing the relevant part of the University's Faculty of Mathematics, where you can find contact information on the bottom of the this page: http://www.maths.cam.ac.uk/postgrad/mathiii/.
I don't know how much you know about how the University of Cambridge operates, but if you were to apply for the one-year Masters, you would also need to look at the different colleges at Cambridge (there's more information available here: http://www.admin.cam.ac.uk/students/gradadmissions/prospec/studying/colleges/index.html). The University also has open days (both generally and faculty specific) throughout the year, so it may be worth having a look to see when they are.
On a more personal note, I doubt your age would be a barrier to getting onto the Part III course, provided there is a satisfactory explanation as to why - my expeirence with the Faculty members (I'm an undergraduate studying Maths at Cambridge) is that they only really care for a person's mathematical ability.
Comment: Thank you for your reply and for the links that you provided! The 'excuse' for my high age is mainly that I was initially very uncertain about what I wanted to study, and it took me some time to settle with my current program.
Comment: I can't see your reason for your high age being a hinderence then.


Three20 "pull down to update" isn't showing last update time

Question: When I implement this method in my TTTableViewController:
<code>- (id<UITableViewDelegate>)createDelegate {
    return [[[TTTableViewDragRefreshDelegate alloc] initWithController:self] autorelease];
}
</code>
I get the "pull down to update..." feature, however, it's not displaying the date and time of the last update (like I see on the facebook and twitter apps).
I'm sure this is because I'm not implementing some protocol method or something like that, but I'm not sure exactly which method(s) I need to implement. The table is displaying my data just fine, so I'm not sure what I'm missing.
Any ideas?
This is what I'm seeing:

But this is what I want to see:
Answer: Is your model inheriting from TTURLRequestModel? If so, as the last thing in your
<code>- (void)requestDidFinishLoad:(TTURLRequest*)request
</code>
call
<code>[super requestDidFinishLoad:request];
</code>
Updating the timestamp is what happens in there. If your model is not inheriting from TTURLRequestModel you can still check the source code of that one to see what's involved.


View does not display results when added as a block to a region

Question: UPDATE 2: I'm not sure if this is relevant but when click 'demonstrate block regions' the only region it displays is content

UPDATE: I have just discovered that the block displays just fine when added to the content region. However when added to any other region such as the left sidebar or any custom region it does not display at all

I currently have a view that displays the results just fine in the view preview. It also works when I create a basic page and embed it like so:
<?php print views_embed_view('mobile_slide_menu','block');?>

However when I add this view to a region it displays no results. However I know that it's trying to display something because I see this in my source.

My info file that is defining the regions looks like this
;regions
regions[main_menu] = Main Menu
regions[header] = Header
regions[content] = Content
regions[help] = Help
regions[slide_menu] = Slide Menu
regions[footer] = Footer
regions[sidebar_first] = Left Sidebar
regions[sidebar_second] = Right Sidebar

and I'm calling the region like this
<?php print render($page['slide_menu']);?>

I'm using Drupal 7 and this is a custom theme I've built. I've cleared the cache multiple times.
Answer: Verify which of the blocks you have enabled for the theme you're using. To do so, navigate to admin/structure/block. Somewhere your "block created with views" should be listed there. If it is within "Disabled" (near the bottom), then you need to indicate there in which region (like sidebar 1st, sidebar 2nd  or something similar?) you want that block to be displayed.
From what you seem to experience, it seems that hardly any block is enabled (most seem to be disabled).
PS: just to be sure, try to clear the cache ... it doesn't hurt, but sometimes that is what is required ...
Comment: I'm not sure what you mean. I have the region slide_menu and the block is assigned to that region. It is set to display on all pages except  would there be any other way for it to be disabled?
Comment: It is a custom theme I have built using Drupal 7
Comment: Hm, a "custom" theme ... That's another story. From what I read/know now, I believe your problem is not in the view. But just some problem to have your theme correctly process (display) all data of all enabled blocks in each of your regions. Try this: create a custom bock with just some "test"-text in the block to be displayed. via admin, make that block show up in (eg) region sidebar 1st. And then verify if the block is actually shown. I'm about sure it won't show up either. That eliminates the possibility that the error is in your view. And something in your theme's php files is the issue.
Answer: The issue was the location of
<?php print render($page['slide_menu']);?>

Placing it inside of a unordered list prevented it from rendering anything. Not even in the source.
Placing it outside of the list allowed it to render properly.


one form, two submit buttons for two different hidden values

Question: I have a basic post form that submits some data to an SMS gateway.
One of the hidden fields "message" is the text of the message that i wish to be sent out.
I need two submit buttons for two different sitations (case1 and case2) - each one transmits a different text in the "message" value.
I cant do anything server side as the data is sent to a third party gateway.
Any advice?
current code is:
I just need two submit buttons - one for case1 and one for case2.
<form action="https://gatway.com/send.php" method="post">
<input name="key" type="hidden" value="APIKEYxxxxx" />
<input name="message" type="hidden" value="message to send in case 1" />
<input name="message" type="hidden" value="message to send in case 2" />
To: <input name="to" type="text" />
<input name="username" type="hidden" value="username" />
<input name="from" type="hidden" value="+44xxxxxxxxxx" />

<input type="submit" value="Submit" /></form>

Comment: if you can edit the form, then you can add a change in the form parameters using javascript onSubmit. edit form.action, for example
Answer: You could use buttons with the same name.
They will populate the message variable based on which one was clicked.
<form action="https://gatway.com/send.php" method="post">
    <input name="key" type="hidden" value="APIKEYxxxxx" />
    To: <input name="to" type="text" />
    <input name="username" type="hidden" value="username" />
    <input name="from" type="hidden" value="+44xxxxxxxxxx" />
    <button type="submit" name="message" value="message to send in case 1">Submit 1</button>
    <button type="submit" name="message" value="message to send in case 2">Submit 2</button>
</form>

Answer: How about instead of having two submit buttons, have one then have the two message fields as text then user can type the message based on whatever case. then instead of submitting the form directly to the sms gateway send the form to your script in your server to validate which case was used then send the post data to the sms gateway with CURL.
<form action="smschecker.php" method="post">
    <input name="key" type="hidden" value="APIKEYxxxxx" />
    <input name="message1" type="text" value="message to send in case 1" />
    <input name="message2" type="text" value="message to send in case 2" />
    To: <input name="to" type="text" />
    <input type="submit" value="Submit" />
</form>

smschecker.php
<?php
define('SMS_SERVICE_URL', 'https://gatway.com/send.php');
define('username', 'username_here');
define('password', 'password_here');
define('key', 'YOUR_KEY/SID_HERE');
define('from', "+44xxxxxxxxxx");

if (isset($_POST['message1']) && !empty($_POST['message1'])) {

    $message = $_POST['message1'];
}

if (isset($_POST['message2']) && empty($_POST['message2'])) {

    $message = $_POST['message2'];
}

$to   = $_POST['to'];
$from = $_POST['from'];

$sms = array(
    "to" => $to,
    "message" => $message,
    "from" => from
);

$post = array(
    'user' => username,
    'pass' => password,
    'key' => key,
    'sms' => $sms
);

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, SMS_SERVICE_URL);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$result = curl_exec($ch);

curl_close($ch);
?>


Raspberry Pi - Firestore timestamp issue

Question: So in my project, I'm trying to send a timestamp to my firestore database. When I tested my datetime in my python code it would give me the right date and time, after sending the data to firestore, the timestamp data in the database is always +8 hours from the current time
from 2018-05-20 07:11:19.833275 to 2018-05-20 15:11:19.833275
everything else is correct, even the timezone, only except for the hour. Our time zone btw is UTC+8.
I dont understand what I am doing wrong.
Here's my code:
import firebase_admin
from firebase_admin import credentials
from google.cloud import firestore
from firebase_admin import firestore
import datetime, sys

now = datetime.datetime.now()

# Use a service account
cred = credentials.Certificate('*some key*')
firebase_admin.initialize_app(cred)
db = firestore.client()
path = db.collection("*somepath*")

doc_ref = path.document()
doc_ref.set({
    'date': now,
    'rate': 60,
    'used': 1
})

print ("current: %s" %now)

Comment: Why are you getting `now` and then passing `datetime.datetime.now()`?
Comment: sorry, let me edit that. I forgot to change that
Comment: Did you manage to solve this?
Answer: For a more consistent timestamp, consider using the Firestore SERVER_TIMESTAMP constant:
doc_ref.set({
    'date': firestore.SERVER_TIMESTAMP,
    'rate': 60,
    'used': 1
})

https://google-cloud-python.readthedocs.io/en/latest/firestore/constants.html
You can then convert your timestamp client-side, if you need to.


Declare generic Java class in an android project

Question: i'm making a simple game for android and i need to declare a generic class to cast later in the code, i have 3 classes to chose from and they are chose dinamically, how can i achieve so?
enum difficulty {
    SIMPLE,
    MEDIUM,
    HARD
};

difficulty dif;

//assign dif

switch(dif) {
    case SIMPLE:
         ...
         break;
    case MEDIUM:
         ...
         break;
    case HARD:
         ...
         break;
}

it all depends on which of these gets chosen..
Comment: First: Generics are for avoiding casts. Second: Generics don't work at runtime because of type ereasure. Thrid: I can't see anything to be solved with generics. Are you sure You are talking about generics?
Comment: This is the same approach java used.
Comment: can you elaborate more?
Comment: i need to have a generic class to declare outside of the functions since i don't know which one will be called
Comment: you should look at the factory design pattern
Comment: for "generic" i mean something that can be converted into any class, for example: xxx newclass; newclass = new Simple();
Comment: Can you please check my answer?
Answer: Create an interface or abstract class then implements(for interface)/ extends(for abstract) the parent class on the corresponding child classes.
e.g.
public interface IEasy{

}

public class EasyClassA implements IEasy{

}

public class EasyClassB implements IEasy{

}

Answer: Perhaps use a Difficulty base class and then extend from that a class for each of the 3 levels of difficulty, then in these classes set up stuff for the difficult level??
So like this:
public virtual DifficultyLevel
{

}

public EasyDifficulty extends DifficultyLevel
{
    // do stuff here to set difficulty to easy
}

public MediumDifficulty extends DifficultyLevel
{
    // do stuff here to set difficulty to medium
}

Then you can cast from a base type of DifficultyLevel to anything that inherits it :D
Comment: that's not java. Since the question has not the C++ tag you shouldnt put C++ code
Answer: If you want to keep your game simple, I don't see that you need to implement subclasses at all. If some behavior or logic (for example, a different AI, or boundary properties) changes between difficulties, then sure, subclass. But if it's just a matter of configuring some numbers (e.g., board size, movement speed, number of tries, physics constants), then just use 3 init functions or a switch like you do in the question.


Set of all finite subsets of $\mathbb{N}$ not equal to the to set of subsets of $\mathbb{N}$

Question: I can kind of grasp why this is the case as if we take the union of all finite subsets of cardinality $i$ as $i$ runs through every natural number, we are listing finitely many elements each time.
Whereas with the set of all subsets we can just keep adding new elements via Cantor's argument.
However I do not feel very secure on this type of understanding, I was just wondering if someone could deliver a good explanation as to why they aren't equivalent.
Comment: $\mathbb{N}$ is a subset of $\mathbb{N}$ and it is certainly not finite!
Comment: Are you trying to compare their cardinality?
Comment: I guess simply put I just want to know why the two aren't equivalent
Answer: The first set is a strict subset of the second: if for example you consider the set of natural numbers $\mathbb{N}$, then the set of even numbers or the set of all natural numbers above a certain value, are all infinite sets and thus are only contained in the set of all subsets, but not in the set of finite subsets.
Actually the cardinality of the first is equal to $\mathbb{N}$, whereas the cardinality of the second (which is the power set or $\mathbb{N}$) is equal to the one of the real numbers.


Clarification regarding EclipseLink JPA properties

Question: I am using EclipseLink JPA version 2.6 and I wanted to use connection pool properties to set minimum and maximum connection in persistence.xml file. But I have two different set of properties as follows
<property name="eclipselink.connection-pool.default.initial" value="1" />
  <property name="eclipselink.connection-pool.default.min" value="64" />
 <property name="eclipselink.connection-pool.default.max" value="64" />

And
<property name="eclipselink.connection-pool.default.initial" value="1" />
<property name="eclipselink.connection-pool.node2.min" value="16"/>
<property name="eclipselink.connection-pool.node2.max" value="16"/>

I have doubt that which set I have to use in persistence.xml file. Anyone suggest me a best possible way for handling multiple connections.
Answer: Check the documentation about partitioning your connection pool. If you not plan to partition your pool, the first settings-block is fine. Check the Connection Pool settings for eclipselink.


Unir resultados de uma sql em apenas uma linha

Question: Tenho o seguinte banco de dados:
CREATE DATABASE  IF NOT EXISTS `materiais`;
USE `materiais`;
 --
-- Table structure for table `categoria`
--

 CREATE TABLE `categoria` (
  `id_categoria` int(11) NOT NULL,
  `descricao_categoria` varchar(100) NOT NULL,
  `sin_ativo` char(1) NOT NULL DEFAULT 'S',
  PRIMARY KEY (`id_categoria`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dumping data for table `categoria`
--

 INSERT INTO `categoria` VALUES (1,'travessas','S'),(2,'Capa Cromada','S'),(3,'Coifas Vedante','S'),(4,'Chassis Metálicos','S'),(5,'Quadros Hidráulicos','S'),(6,'Tampa de Inspeção','S'),(7,'Abraçadeira Sextavada Tipo M','S'),(8,'Ponto de Filtro','S'),(9,'TE Ducha higiênica','S'),(10,'Carenagens Plásticas','S');

--
-- Table structure for table `metricas`
--

 CREATE TABLE `metricas` (
  `id_metricas` int(11) NOT NULL,
  `descricao` varchar(45) NOT NULL,
  PRIMARY KEY (`id_metricas`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dumping data for table `metricas`
--

 INSERT INTO `metricas` VALUES (1,'A Máx (mm)'),(2,'A Min (mm)'),(3,'B'),(4,'C'),(5,'B (mm)');

--
-- Table structure for table `imagem`
--

 CREATE TABLE `imagem` (
  `id_imagem` int(11) NOT NULL,
  `caminho` varchar(100) NOT NULL,
  `sin_ativo` varchar(45) DEFAULT 'S',
  `produto_id_produto` int(11) NOT NULL,
  PRIMARY KEY (`id_imagem`),
  KEY `fk_imagem_produto1` (`produto_id_produto`),
  CONSTRAINT `fk_imagem_produto1` FOREIGN KEY (`produto_id_produto`) REFERENCES `produto` (`id_produto`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dumping data for table `imagem`
--

 --
-- Table structure for table `especificacao`
--

DROP TABLE IF EXISTS `especificacao`;
 CREATE TABLE `especificacao` (
  `id_codigo` varchar(15) NOT NULL,
  `id_metricas` int(11) NOT NULL,
  `valor` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id_codigo`,`id_metricas`),
  KEY `fk_codigo_has_metricas_metricas1` (`id_metricas`),
  KEY `fk_codigo_has_metricas_codigo1` (`id_codigo`),
  CONSTRAINT `fk_codigo_has_metricas_codigo1` FOREIGN KEY (`id_codigo`) REFERENCES `codigo` (`id_codigo`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `fk_codigo_has_metricas_metricas1` FOREIGN KEY (`id_metricas`) REFERENCES `metricas` (`id_metricas`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dumping data for table `especificacao`
--

 INSERT INTO `especificacao` VALUES ('CAN16',3,'57'),('CAN16',4,'63'),('CC00000016',1,'457'),('CC00000016',2,'317'),('CC00000016',5,'53'),('ESP400',1,'394'),('ESP400',2,'254');

--
-- Table structure for table `codigo`
--

 CREATE TABLE `codigo` (
  `id_codigo` varchar(15) NOT NULL,
  `id_produto` int(11) NOT NULL,
  `sin_ativo` char(1) NOT NULL DEFAULT 'S',
  `descricao` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id_codigo`),
  KEY `fk_codigo_produto1` (`id_produto`),
  CONSTRAINT `fk_codigo_produto1` FOREIGN KEY (`id_produto`) REFERENCES `produto` (`id_produto`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 --
-- Dumping data for table `codigo`
--

 INSERT INTO `codigo` VALUES ('CAN16',7,'S',NULL),('CC00000016',8,'S',NULL),('ESP400',7,'S',NULL),('TMMC390100',2,'S',NULL),('TMRP1239070',1,'S',NULL),('TMRP3439070',1,'S',NULL);

--
-- Table structure for table `produto`
--

 CREATE TABLE `produto` (
  `id_produto` int(11) NOT NULL,
  `descricao` varchar(75) NOT NULL,
  `sin_ativo` char(1) NOT NULL DEFAULT 'S',
  `id_categoria` int(11) NOT NULL,
  PRIMARY KEY (`id_produto`),
  KEY `fk_produtos_categoria` (`id_categoria`),
  CONSTRAINT `fk_produtos_categoria` FOREIGN KEY (`id_categoria`) REFERENCES `categoria` (`id_categoria`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dumping data for table `produto`
--

 INSERT INTO `produto` VALUES (1,'Travessa para Registro de Pressão','S',1),(2,'Travessa para Monocomando','S',1),(3,'Travessa Tubular Para Cotovelo','S',1),(4,'Travessa para Distribuidor','S',1),(5,'Travessa para Aquecedor e tanque','S',1),(6,'Travessa para registro de gaveta','S',1),(7,'Conjunto Capa Cromada','S',2),(8,'CONJUNTO CAPA CROMADA CANOPLA EM LATÃO CROMADO','S',2),(9,'CONJUNTO CAPA CROMADA CANOPLA EM ABS','S',2),(10,'COIFA SIMPLES','S',3),(11,'COIFA SILICONE','S',3),(12,'COIFA TRIPLA','S',3),(13,'COIFA DUPLA','S',3),(14,'COIFA QUADRUPLA','S',3),(15,'CARENAGEM TANQUE','S',10),(16,'CHASSI TANQUE','S',4),(17,'QUADRO CHUVEIRO DE SOBREPOR - 2 TRAVESSAS','S',5),(18,'TAMPA DE INSPEÇÃO VENTILADA','S',6),(19,'ABRAÇADEIRA SEXTAVADA TIPO M','S',7),(20,'PONTO DE FILTRO','S',8),(21,'TE DUCHA HIGIÊNICA','S',9);

Ao realizar a sql:
select p.id_produto, p.descricao, c.id_codigo, m.descricao,e.valor
from produto as p inner join codigo as c ON p.id_produto =
c.id_produto inner join especificacao as e ON e.id_codigo =
c.id_codigo inner join metricas as m ON e.id_metricas  = m.id_metricas
where c.id_produto = 7

O resultado para cada produto é dado em duas linhas com no exemplo:
id_produto  descricao             id_codigo     descricao   valor
7          Conjunto Capa Cromada    CAN16           B       57
7          Conjunto Capa Cromada    CAN16           C       63
7          Conjunto Capa Cromada    ESP400      A Máx (mm)  394
7          Conjunto Capa Cromada    ESP400      A Min (mm)  254

Preciso que o valor retornado apareça separado por produto em apenas uma linhas, por exemplo:
id_produto   descricao id_codigo   descricao valor descricao   valor
7      Conjunto Capa Cromada CAN16       B    57    C              63

Como resolver?
Comment: Quais os critérios para passar do resultado com 4 linhas para 1 linha só? Pode agrupar os resultados com `GROUP BY` por exemplo ou então especificar melhor o seu `WHERE`. Esclareça melhor o que pretende ver no fim como resultado. (O seu código no [SQLFiddle](http://sqlfiddle.com/#!2/98c12b/3))
Comment: Gostaria que o resultado de id_codigo, ficasse em apenas uma linha. Algo como 7          Conjunto Capa Cromada    CAN16           B       57 C       63
Comment: olhei mas observe que o valor da linha de baixo o C       63 não apareceu.
Comment: Sugiro você achar outra solução para o problema, pois para cada opção possível de 'descricao' você teria 2 colunas a mais na sua consulta. Não funciona assim. De repente, você faz outra pergunta relatando o problema que você quer resolver e alguém responde a melhor forma.
Comment: Um problema é o que o número de colunas pode variar, talvez o uso de um CASE com MAX  resolva mas não creio em solução via sql , talvez o uso de um gerador de relatório que faça referência cruzada (Crystal Reports por exemplo) seja o melhor.
Answer: Então acho que para resolver seu problema você pode usar uma função de agregação como  GROUP_CONCAT do mysql.
select
    p.id_produto
  , p.descricao
  , c.id_codigo
  , group_concat(m.descricao order by p.id_produto, ', ') as descricao
  , group_concat(e.valor  order by p.id_produto, ', ') as valor
from produto as p
inner join codigo as c ON p.id_produto = c.id_produto
inner join especificacao as e ON e.id_codigo = c.id_codigo
inner join metricas as m ON e.id_metricas  = m.id_metricas
where c.id_produto = 7
group by p.id_produto
  , p.descricao
  , c.id_codigo
;

obs: Não tenho certeza se a sintaxe está correta, achei essa informação aqui, usando como base o listagg do Oracle 11g.
Comment: Era isso mesmo, Obrigado.
Comment: Opa. Fico feliz por ter ajudado!


Why is my Tukey post hoc test is not significant while my values are visually different?

Question: can anyone help me to understand this.
I have data to compare among 3 experiments with 2 treatments each.I want to compare a measured variable between the 2 conditions for each experiment.  I first ran an ANOVA (significant) then a post hoc tukey test. One of comparison is not significant although the values between the conditions are different (please see the boxplot, exp1). I pasted a part of the post hoc output with the result confusing me Exp1:U-Exp1:B where pvalue>0.05.

can anyone help me understand this?
test <- structure(list(exp = c("Exp1", "Exp1", "Exp1", "Exp1", "Exp1",
                   "Exp1", "Exp2", "Exp2", "Exp2", "Exp2", "Exp2", "Exp2", "Exp2",
                   "Exp2", "Exp3", "Exp3", "Exp3", "Exp3", "Exp3"), cond = c("B",
                                                                             "B", "B", "U", "U", "U", "B", "B", "B", "B", "U", "U", "U", "U",
                                                                             "B", "B", "B", "U", "U"), variable = c(0.00838203, 0.0103495,
                                                                                0.00757493, 0.02157368, 0.0132083, 0.01336677, 0.03054078, 0.01570897,
                                                                                0.028895, 0.02730669, 0.05822746, 0.05476223, 0.05476223, 0.05814691,
                                                                                0.00358898, 0.00721144, 0.01070452, 0.00348329, 0.00613196)), class = c("tbl_df",
                                                                                "tbl", "data.frame"), row.names = c(NA, -19L))

ggboxplot(test , x="exp", y='variable',fill='cond')+facet_wrap(.~exp,scales = 'free')

#run an anova
# Compute the analysis of variance
anova <- aov(variable ~ exp*cond, data = test )
# Summary of the analysis
summary(anova)

#apply a post hoc tukey test ukey HSD (Tukey Honest Significant Differences, R function: TukeyHSD())
TukeyHSD(anova)

>  Tukey multiple comparisons of means
    95% family-wise confidence level
>
> Fit: aov(formula = variable ~ exp * cond, data = test)
>
> $exp
>     >               diff         lwr           upr     p adj
>     > Exp2-Exp1  0.028634582  0.02268322  0.0345859455 0.0000000
>     > Exp3-Exp1 -0.006185164 -0.01285797  0.0004876468 0.0706136
>     > Exp3-Exp2 -0.034819746 -0.04110199 -0.0285375024 0.0000000
>     >
>     > $cond
>           diff        lwr        upr   p adj
> U-B 0.01473809 0.01059542 0.01888076 3.5e-06
>
> $`exp:cond`
>                       diff          lwr          upr     p adj
> Exp2:B-Exp1:B  0.016844040  0.006273786  0.027414294 0.0016210
> Exp3:B-Exp1:B -0.001600507 -0.012900584  0.009699570 0.9964757
> Exp1:U-Exp1:B  0.007280763 -0.004019314  0.018580840 0.3277292

  #checking anova assumption validity
# 2. Homogeneity of variances
plot(anova, 1)

#Bartlett's test or Levene's test to check the homogeneity of variances.
library(car)
leveneTest(variable ~ exp*cond, data = test )

# 2. Normality
plot(anova, 2)
#confirm with shapiro
# Extract the residuals
anova_residuals <- residuals(object = anova)
# Run Shapiro-Wilk test (high P value= normalit is oK)
shapiro.test(x = anova_residuals )

Comment: You have no more than three data points for each condition, sometimes even only two. Don't visualize such a small number of data points using boxplots! As you see, [the boxplots are hiding a lot of information](https://stats.stackexchange.com/q/580985/1352). Much better to simply plot the data points themselves - then you would see at a glance that you probably have far too little data and far too much variance to draw any valid conclusions. Boxplots are *dangerous*.
Comment: what is your sample size?
Comment: Given the low sample size, I suspect this might be due to the fact that in Exp1 the difference of means is much lower. You can try to follow [this post](https://aaronschlegel.me/tukeys-test-post-hoc-analysis.html) to compute Tukey's HSD manually, and maybe that will clarify your doubts
Comment: Thank you all for you explanations and suggestions. Indeed the boxplot mislead me.
Answer: Update: Interesting discussion (don't skip the comments) about box-and-whiskers for small samples: How should we do boxplots with small samples?

Your plot is misleading rather than revealing.

The box and whiskers plot is a 5-number summary: it shows the minimum, lower quartile, median, upper quartile, and maximum. You use a box-plot to summarize as few as 2 values. It's not possible to create a meaningful 5-number summary of 2 numbers. As @StephanKolassa explains, boxplots can be dangerous.
Each panel has its own scale for the y-axis. This highlights differences within each experiment but keep in mind that "statistical differences" are measured on the scale of the residual error which is the same for all observations.

Here is a different plot of the same data. If you had made this plot, you might not have written the question.

You wrote the question, however, so let's point a couple more things.

Three pairs of condition U measurements are almost exactly the same. (I added jitter to avoid overlap.) Suggests that variance is not the same under the two conditions.
It may be easier to make comparisons with the emmeans package.

mod <- lm(variable ~ exp * cond, data = test)
pairs(emmeans(mod, ~ cond | exp))

#> exp = Exp1:
#>  contrast estimate      SE df t.ratio p.value
#>  B - U    -0.00728 0.00341 13  -2.137  0.0522
#>
#> exp = Exp2:
#>  contrast estimate      SE df t.ratio p.value
#>  B - U    -0.03086 0.00295 13 -10.458  <.0001
#>
#> exp = Exp3:
#>  contrast estimate      SE df t.ratio p.value
#>  B - U     0.00236 0.00381 13   0.620  0.5462

Comment: Hello @dipetkov, thank you for your detailed answer and your suggestions. In the beginning, what made me expect significant result  was looking at the mean ±  sd of the values :  B=0.88a ± 0.14  vs. U=1.60a ± 0.48. But actually you are right choice of plot type was not appropriate and it is clear that I have 2 data points in U that are much closer to the values in B.  Thanks again for the suggestions and explanations.
Comment: How did you compute the standard deviations in your first computation? Was it separately for each condition?
Comment: I computed the sd for each condition per experiment separately using the function std in r.
Comment: This is one more thing to clarify: In the model every observation has the same error variance $\sigma^2$; for each combination of experiment $i$ & condition $j$, the standard error of the sample mean is a function of $\sigma^2$ and the group size $n_{ij}$: $\sigma^2/n_{ij}$. Since your design is almost balanced and there are 10 observations under B and 9 observations under U, the estimated means for the two conditions have similar standard error as well. So in a way the difference between $\text{SE}_B = 0.14$ and $\text{SE}_U = 0.48$ is too big *under the equal variance assumption* of ANOVA.
Comment: Thank you for link for the discussion ! Glad to see that my unintended wrong choice of plot triggered this very interesting discussion!


Inject function in angularjs

Question: I am unit testing angularjs controller with jasmine, karma.... the test sample looks like this:
     beforeEach(inject(function(_$rootScope_, _$controller_){
    $rootScope = _$rootScope_;
    $scope = $rootScope.$new();
    $controller = _$controller_;
    $controller('AboutController', {'$rootScope' : $rootScope, '$scope': $scope});
}));

Here, I am confused how did jasmine come to know about the inject function? Is it the same function object as angular's Injector.inject()... I am surprised, the method is available outside Angular namespace... and what does the $controller variable injected into function do?
Answer: the inject function is part of the Angular Mocks package (ngMock).  You probably added this to your karma.conf.js file in order to get the jasmine tests configured.  So, this way of injecting is not available in production Angular code, it is only used for unit testing.
That package adds inject to the window object (global) as a convenience during testing.
From the docs:

NOTE: This function is also published on window for easy access.

For more information here is the documentation.
As for the second question: The $controller service allows you to initialize a named controller ('AboutController' in your example) and pass in it's dependencies.  Getting a handle on $scope is often necessary when testing controllers.

Inject function in angularjs


Find all $z\in\mathbb{C}$ such that $e^z = 1$.

Question: We write $z=a+ib$. Now,
$$1 = e^z = e^{a+ib} = e^a e^{ib} = e^a(\cos b + i\sin b) = e^a\cos b + ie^a\sin b$$
We have
$$1 = e^a \cos b \\ 0 = e^a\sin b$$
Now, I don't understand why it has to be that $$1 = e^a\cos b = \color{red}{e^a (-1)^n}$$
Comment: $e^a\neq 0$ for any real value of $a$, so $0=e^a\sin b$ implies that $\sin b = 0$ which implies...  Now, that occurs only when $\cos b = 1$ or $-1$.  Since $e^a>0$ for all real $a$, that implies that $\cos b$ is not negative.  That implies $\cos b = 1$ which then implies that $e^a=1$.  What values of $a$ and $b$ satisfy this?
Answer: Since $e^a$ never equals $0$, it follows from $0=e^a \sin b$ that $\sin b=0$, hence $\cos b$ takes as values either $1$ or $-1$, hence this implies that $1=e^a\cos b=e^a(-1)^n$.
Comment: @Elimination You're welcome! ;-)
Answer: Since $e^a \neq 0$, we can divide both sides of the second equation, $0 = e^a \sin b$ by $e^a$, giving $$\sin b = 0 .$$ This has solution $$b = n \pi, \quad n \in \Bbb Z,$$ and substituting this in the remaining equation gives
$$1 = e^a \cos (n \pi) = e^a (-1)^n$$
as claimed.
Comment: You're welcome, I'm glad you found it useful!
Comment: Oh right. I have to get some sleep! many thanks!


Handling -uNUM as a bash option

Question: I have a bash function that handles a usage option for the following situations
-u, -u NUM, -u=NUM, -uNUM

nmafr in a function that tests whether the argument is a numeric whole number.
I could change the ("-u"*) part, in a way that it handles the case of -u followed by at least one alphanumeric character, so that the case of "-u" is handled by ("-u"|"--usage").
What would be the pattern to use instead of the current ("-u"*) ?
local AFFNUM="nmafr -q -W"

while (( $# > 0 )); do
 case $1 in

  ("-u"|"--usage")
      ## Handle -u NUM, -u allows optional argument value
      if { $AFFNUM "$2"; }; then
        usg="$2" ; shift ; shift
      else
        usg=1 ; shift 1
      fi
      lampi-usage "$usg"
      return 0
      ;;

  ("-u="*|"--usage="*)
      ## Handle "-u=2", "-u=" allows optional argument value
      if { $AFFNUM "${1#*=}"; }; then
        usg="${1#*=}" ; shift 1
      else
        usg=1 ; shift 1
      fi
      lampi-usage "$usg"
      return 0
      ;;

  ("-u"*)
      ## Handle -uNUM
      if { $AFFNUM "${1#*-u}"; }; then
        usg="${1#*-u}" ; shift 1
      else
        shift 1
        lferr+=(" {-uNUM} NUM fails numeric validation")
      fi
      lampi-usage "$usg"
      return 0
      ;;

  ("--") shift 1 ; break ;;
  (*) opt_error=1 ; break ;;

 esac
done

Comment: Why are you having trouble deciding? You haven't really expressed a problem that can be solved. Is your current code broken in some way, and if so how? Provide example inputs, their wrong outputs, and your desired output.
Answer: One major issue in your script is that for all the case statement branches, you must change all instances of
( {match1}|{match2}|{match3} ) action1 ;;

to
{match1} | {match2} | {match3} ) action1 ;;

removing the open round-bracket on each one.  Otherwise, the () pair is considered a sub-shell.
Also, putting space between each pattern and the vertical bar, to ensure it is not interpreted as part of the string by being adjacent.
Comment: I don't think either of these assertions are correct. The shell case statement does allow an opening parens as part of the syntax, (sometimes they are very convenient) AND you would only put spaces before/after a `|` (OR) operator if you expect your variable input for case matching includes a space. Unfortunately [Posix Shell Definition](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html) does show spaces before/after the `|` char. (Search for *Case Conditional Construct*).  ,.,,,
Comment: But note that a quick test `arg=a ; case $arg in ( 1|b|a|5 ) echo $arg ;; *) echo no match $arg ;; esac` (returns `a`)  ,,,,doesn't required spaces.
Comment: And `arg=" c d" ; case $arg in (1|b|a|5|\ c\ d) echo $arg ;; *) echo no match $arg ;; esac` returns `c d` (with leading space), while arg=" c d" ; case $arg in (1|b|a|5|c\ d) echo $arg ;; *) echo no match $arg ;; esac` returns `no match  c d` . Good luck to all!
Comment: I go with what I consider the most portable (ash compatible), most of the time.  I only use bash when specific features available in bash dictate its use.
Comment: Did my code samples fail in `ash`? (I would be suprised). But thanks for the feedback. Also I notice that this Q is tagged only with `bash`.

Handling -uNUM as a bash option


Method Added in Python

Question: In Ruby, one can create callbacks for when methods are defined on an object:
module Chatty
  def self.method_added(method_name)
    puts "Adding #{method_name.inspect}"
  end
  def self.some_class_method() end
  def some_instance_method() end
end
# => Adding :some_instance_method

Does Python have any similar callback?
Comment: Not for methods added during class creation. Afterwards it's just `__setattr__` like any other attribute.
Comment: You can do this with a metaclass.
Comment: What is a good use case for this functionality? I think it would be cool if you provided some motivation too.
Answer: In Python, methods are just attributes that happen to be callable*. You'd have to hook in to attributes being set to see new methods being added to a class.
You'd have to use a metaclass to intercept new attributes being added to a class:
import types

class NewMethodAlerter(type):
    def __setattr__(self, name, obj):
        if isinstance(obj, types.FunctionType):
            print(f'New method {name} added!')
        super().__setattr__(name, obj)

class Demo(metaclass=NewMethodAlerter):
    def existing_method(self):
        pass

def new_method(self): pass
Demo.new_method = new_method

which then looks like this:
>>> class Demo(metaclass=NewMethodAlerter):
...     def existing_method(self):
...         pass
...
>>> def new_method(self): pass
>>> Demo.new_method = new_method
New method new_method added!

If you wanted to know about the initial set of attributes, the result of executing the class body, then you have two options: use a metaclass, or in Python 3.6 and up, the __init_subclass__ method. Either one is called to create new classes, and can be used to inspect the attributes:
class InitialMethodAlerter(type):
    def __new__(typ, name, bases, attrs):
        for name, obj in attrs.items():
            if isinstance(obj, types.FunctionType):
                print(f'Method {name} defined!')
        return super().__new__(typ, name, bases, attrs)

class Demo(metaclass=InitialMethodAlerter):
    def existing_method(self):
        pass

or the __init_subclass__ method:
class InitialMethodAlerter:
    @classmethod
    def __init_subclass__(cls, **kwargs):
        for name, obj in vars(cls).items():
            if isinstance(obj, types.FunctionType):
                print(f'Method {name} defined!')

class Demo(InitialMethodAlerter):
    def existing_method(self):
        pass

You may want to read up on metaclasses at What is a metaclass in Python?

*Well, the attributes are functions actually. Functions are descriptor objects, which causes them to be bound when accessed via an instance. That binding process produces a method object, that when called takes the original function and passes in the instance to which it was bound.
Comment: So there's no way to intercept methods defined in the class definition?
Comment: @faraz: what are you trying to achieve here? I may have misunderstood. The metaclass is *also* told about all the initial attributes for the class, as the class is created.
Comment: I'd expect `New method existing_method added!` to appear after the class is defined.
Comment: @faraz: your question was confusing me there, because of the terminology 'added'. I've updated the question, but it's more and more a duplicate of [What is a metaclass in Python?](//stackoverflow.com/q/100003) now.
Comment: @faraz One small clarification to help you understand why you are not seeing the message about the existing method: the `__setattr__` method isn't called when the class body is executed and all of the initial class members are created. There is a separate set of machinery invoked for class *creation*.
Comment: Thank you so much for this! I've just started diving into metaprogramming in Python, and this was immensely helpful.

Method Added in Python


How to hook up NSWindowDelegate in macOS game template

Question: This is a "how-to" for related question:
cocoa windowDidEnterFullScreen not being called
Using the Xcode (9.1) macOS "game" template -
I would like to create a simple NSWindowDelegate using the AppDelegate class. However I can't seem to connect the given NSWindow outlet to anything.
// AppDelegate.h
#import <Cocoa/Cocoa.h>

@interface AppDelegate : NSObject <NSApplicationDelegate, NSWindowDelegate>

@property (assign) IBOutlet NSWindow *window; // won't connect

@end

I assume I'm supposed to connect to a "Window" within the storyboard. This is what happens when I try to connect - the inspector does not show up.

What am I missing here?
Note: I'm just playing around so I don't care if AppDelegate is the right place or not, I just want something to work.
EDIT 1
Using suggestion from answer, I've tried connecting the 'TestFullscreen' window to the AppDelegate object, but it still won't connect, either from the AppDelegate inspector or the property declaration in the code.
Comment: If you are just using AppDelegate to write everything, you don't need NSWindowController.
Answer: You should have a Delegate object and that is what should hook up to your window.

It looks like you are currently attempting to connect the window to itself. Also it doesn't appear you have a view for the window either, so you'll need to add that for the window content.
Comment: Thanks, but still won't connect to my delegate. Is there a chance I've mixed up the WindowController with the Window itself?
Comment: @Justicle: I mistakenly posted what would normally be done for nibs, and xibs. Basically with storyboards you'll hook your WindowController up to a ViewController. This example should shed some light on how it's done: https://github.com/stonehouse/T-Minus
Comment: Looked at the project - Not sure how that will help? - I want to respond to NSWindow messages, not NSWindowController messages.
Comment: @Justicle: Storyboards don't work the same way as a nib or xib does, so the delegate connections don't hook directly to a window. Generally you'd have a WindowController > Window > First Responder > Then Storyboard Entry Point. Personally I don't like using storyboards on macOS because of the convoluted segue necessity and all that, however, creating a new basic storyboard app should show you how the connections are made in a typical project. BTW - I think there's a bug in Xcode, maybe you can confirm? - control-c (copy) on "window" underneath Window Controller it crashes (at least for me).
Comment: Also Did you try connecting the "TestFullScreen" window underneath the Window Controller over to the View Controller View? That should work.
Comment: cmd-c works for me, cmd-v crashes Xcode pretty hard.
Answer: A workaround is to simply create non-Workspace project.
Editing the XIB allows you to connect the Window delegate outlet to the AppDelegate, after it has NSWindowDelegate protocol specified.


How to use Rules to send an email to an email id based on a selected in a registration form?

Question: I have created a rule for sending an email after a new user registered. I would like to add a Rules Condition to send the email to the target based on the selection in the registration form.
For example: if I select the country as india I need to send to email@example.com and for other firstname.lastname@example.com.
I have tried adding a condition in To mail receipt address:
<code>$email = ($account->country == 'india'? email@example.com : 'email@example.com')
echo $email;
</code>
Can you suggest how to handle the scenario?
Answer: You should be able to get this to work by creating a single rule using the Conditional Rules module (and Rules of course). The rule should be trigger by Rules Event "after saving a new user account".
For some samples to put together such rule (in Rules export format), refer to my answer to either of these questions:

How to set the values of some fields depending on the value of a list box?
How to specify a Rules condition related to select list values?

The actual Rules Action you want to use, should be pretty similar to the Rules Action included in my answer to "How to send an email via a Rules action using a field key?".


find the $x$ : $x^2(x-1)^2+x^2=8(x-1)^2$

Question:
find the $x$ :
$$x^2(x-1)^2+x^2=8(x-1)^2$$

My Try :
$$x^2(x-1)^2+x^2=8(x-1)^2\\ x^2(x^2-2x+1)+x^2=8(x^2-2x+1)\\x^4-2x^3+x^2+x^2=8x^2-16x+8\\x^4-2x^3-6x^2+16x-8=0$$
Now What ?
Answer: Hint : Try the divisors of $8$.
Comment: Why ?Nothing changes
Answer: Notice that $x=2$ is a solution. So
$$x^4-2x^3-6x^2+16x-8 =(x-2)(x^3-6x+4)$$
$x=2$ is also a solution of $x^3-6x+4=0$. So
$$x^4-2x^3-6x^2+16x-8 =(x-2)^2(x^2+2x-2)=0$$
The roots are $x=2,1\pm\sqrt{3}$.
Comment: how did you find out that :$$x^4-2x^3-6x^2+16x-8 =(x-2)(x^3-6x+4)$$
Comment: By inspection: we know we have some cubic factor $ax^3+bx^2+cx+d$, but we know $a=1$ to get $x^4$, $d=4$ to get the constant term $-8$, and then I just noticed that $b=0$ and $c=-6$ works. You could also do it by polynomial long division (i.e. the Euclidean algorithm for polynomials)
Comment: @Almot1960 It is called the rational root test.
Comment: @Almot1960 To get your identity you just divide your degree-4 polynomial $p(x)$ by $x-2$, since you already know that $p(2)=0$ (this is called the factor theorem). Then the degree-3 polynomial is the quotient of the division.
Answer: So it can be checked that your polynomial $$x^4-2x^3-6x^2+16x-8=0$$ has a factor of $(x-2)$. We check that this is so by the factor theorem. Then (and it should be checked by you too) that by carrying out the appropriate algebraic division that
$$x^4-2x^3-6x^2+16x-8=(x-2)(x^3-6x+4).$$
Then by a similar argument, we may divide this through by $(x-2)$ again to give
$$(x^3-6x+4)=(x-2)(x^2+2x-2).$$
Then apply the quadratic formula to yield
$$x^2+2x-2=0 \Rightarrow -1\pm\sqrt{3},$$
so altogether $$x=2, -1\pm\sqrt{3}.$$


Responsive design - Media Queries - How not to load certain images

Question: Ok, So I designed a responsive layout that doesn't show images for very small screen sizes, using media queries and display: none;.
So far so good. But these images still download on these devices, causing an increase in bandwidth.
What is the proper way to make these images not download on the specified devices?
Any response would be much appreciated!
Comment: If you can't just have a different markup setup, I would have a mobile.site.com or www.site.com/mobile concentration point and do something to remove or replace (with a blank or empty file reference) all of the `IMG` src attributes (... or just remove the element altogether...). Or pass all of your image file requests through a script on your server, and set a `COOKIE` or `SESSION` flag that tells the script if it's mobile or not, and send either the file contents or an empty response. Something like that. I don't know that you can do it with pure CSS, though.
Answer: Two options I can think of:

Detect small devices on the server using browser-sniffing, and send them different HTML that doesn't reference the images.
Display the images via CSS instead of HTML (in style attributes if you like), using either background-image or :before/:after and content (not supported by IE 6 or 7), and wrap that CSS code in media queries so that it's only displayed by devices with larger screens.
Comment: #2 would usually be a good solution, sadly it won't work for me in this case
Comment: @Illes: sure, it's not always a great idea. I think you're stuck with serving different HTML to small-screen clients then — I don't believe browsers let HTML authors control when image assets get downloaded. Hopefully someone else on Stack Overflow will have some experience of this though.
Comment: 2 is a good option because < IE8 doesn't support media queries anyway.
Answer: The only accessible solution right now is to wrap the image with  tags, then pull the image out later with javascript. Cookies don't work on first page load (HTMLPreloadScanner), nor with CDNs. Browser-sniffing is useless if your images aren't always 100% of the viewport.
Slimmage.js implements context-friendly responsive images in 3KB of vanilla JS.
The markup is pretty simple as well:

Of course, you can make a server-side helper to even abstract this away.
Answer: If you don't mind a javascript dependency you could check window.innerWidth and insert image tags for sufficiently large screens.
Images would only be requested if javascript is enabled and the window big enough.
Answer: If you don't have any issues using additional JavaScript, then you may try THIS. I've stumbled upon it while searching and learning about media queries.


Oracle Database character set issue with the audit tables on Debian

Question: I've got Oracle XE installed on Debian linux and the character set is configured to AL32UTF8.
There are several client applications that connects to a database from Windows with the different locales - French etc, not English. That's ok with all the client data these applications put into database, nothing converted and text data in French represents correctly.
But texts in audit tables looks like '??????' if contains any not-english character. I suppose this is because audit records go to database in the different locale and it's not dependent on the client's globalization/locale settings.
How this globalization issue can be fixed? thanks!
Comment: What are you looking at the audit tables with? What's that tool's locale set to?
Comment: The user names (windows domain user names) are invalid in SYS.AUD$ and look like '?????'. If the user name contains only English characters it's ok, otherwise the whole name converted into '????'-alike strings.
Comment: I'm trying to login remotely to the Oracle using not-english windows user name, not using any 3rd party application, and got the same result - user is audited as '????' in SYS.AUD$
Answer: The likely option is the the audit data is saved correctly in French, but YOUR client doesn't support it, so your Oracle client translate French letters to ???? for you.

What is the NLS_LANG of your client / environment? (for example, from your environment)
In order to check if the data is stored correctly in sys.aud$ table, run:

SELECT username, ascii(username) from DBA_AUDIT_TRAIL;  --optionally with a WHERE clause to limit it to a few suspected rows
If all the ??? characters have the same ascii code, Oracle stores ???. If every ??? has a different ascii code, Oracle stores French letters and you client NLS_LANG configuration does not support French letters.
I hope that helps you troubleshooting it...


Forecasting with mixed frequency data

Question: Just a general question that I couldn't find too much on.
What would be some good approaches to one step ahead forecasting of financial time series with mixed frequencies?
Often a lot of the available data influencing the price of say a stock or commodity is published at different frequencies, some daily, some weekly, some monthly etc. which in my head makes it tricky to use normal models for anything but the longest time interval.
Edit: found this paper which goes some way to cover the topic
Comment: state space models can deal with this. you go with the highest frequency, and the algorithm deals with missing data elements naturally
Comment: take a look at MATLAB [ssm](http://www.mathworks.com/help/econ/ssm.estimate.html) function help's Algorithms section. The first bullet's about missing observations. So, if you sample at monthly, and some data is quarterly, then it should be able to proceed assuming that not provided monthly data is "missing".
Comment: Interesting! got any good resources? @Aksakal
Comment: In case you search for another software tool apart from MATLAB for estimating MIDAS types of models, I also recommend gretl: http://gretl.sourceforge.net/ Ch. 19 and 40 in the manual offer a good reading on the topic, examples and how to implement things:
https://sourceforge.net/projects/gretl/files/manual/gretl-guide-a4.pdf/download
Answer: You can use MIDAS regressions to predict low-frequency target variable with some set of high-frequency (hf) covariates. If you have a larger set of hf covariates, the simplest way is to use forecast combinations, see [1] of such an application of MIDAS regression model to nowcast GDP growth rate using large set of hf covariates. Also, see Matlab toolbox for MIDAS regressions in many different contexts and actual data examples.
Briefly about MIDAS regression:
Formally, let $t\in [T]$ be the low-frequency (lf) time period, say quarterly and $y_t$ be the lf target variable (so you observe it each quarter). Further, let $x_{t-j/m}$, $j \in \{0, \dots, m-1\}$, be hf covariate which we observe within period $(t-1, t]$, i.e. we observe $x$ $m$ times per $t$ time period, and the notation $j/m$ means that $x$ is lagged by a fraction of time period $t$. Say we have daily hf. Assuming 66 days within the quarter (reasonable assumption e.g when taking trading days but it can be generalized to any number, and it can even vary quarter...), this means that we have 66 $x$ observations for each $y$ observation. To use information efficiently, we may wish to use all 66 observations in our regression model, so we can write the model as
$ \qquad \qquad y_t  = \alpha + \sum_{j=0}^{m-1} \beta_{j} x_{t-1-j/m}  + \epsilon_t$
where we subtract additional lag in $x$ to make the regression predictive. This is what is called U-MIDAS (unrestricted MIDAS) regression model. When $m$ is large, as in the quarterly/daily example, the model suffers from parameter proliferation problem (a lot of parameters and typically small samples to estimate them). In MIDAS regression we parameterize $\sum_{j=0}^{m-1} \beta_{j}$ lag polynomial such that it depends on a few, say one or two, parameters. In this case, the model is
$ \qquad \qquad y_t  = \alpha + \beta \omega (\theta) X_{t-1}  + \epsilon_t$
where $\beta$ is the usual regression slope coefficient, $\omega (\theta)$ is some weight function typically taken to be exponential Almon or beta density function, $\theta$ is a low-dimensional parameter of $\omega(.)$ that determines the shape of the weight function and $X_{t-1} \in \mathbf{R}^m$ is a vector of hf lags. Slope coefficient in fact is needed only if you want to know the aggregate effect of $X_{t-1}$ on $y_t$, while if your goal is the prediction you actually do not need it. In the former case, $\omega$ function has to scaled to sum to one for $\beta$ to be identified.
To estimate U-MIDAS you use OLS, while for MIDAS you typically need non-linear LS estimator. There is a very elegant way to avoid NLS estimation (sometimes NLS is problematic) by profiling out $\theta$ parameter, see [2]. In this case, you only need OLS to estimate MIDAS regression.
You can also check wiki on MIDAS models: https://en.wikipedia.org/wiki/Mixed-data_sampling
Hope this helps!
Matlab toolbox:
https://nl.mathworks.com/matlabcentral/fileexchange/45150-midas-matlab-toolbox
R package: https://cran.r-project.org/web/packages/midasr/midasr.pdf
Refs:
[1] Andreou, E., Ghysels, E., & Kourtellos, A. (2013). Should macroeconomic forecasters use daily financial data and how?. Journal of Business & Economic Statistics, 31(2), 240-251.
[2] Ghysels, E., & Qian, H. (2019). Estimating MIDAS regressions via OLS with polynomial parameter profiling. Econometrics and statistics, 9, 1-16.

Forecasting with mixed frequency data


Argumento inválido fornecido para foreach

Question: Criei um foreach para percorrer um array que possui 2 elemento porem eu queria que meu foreach pega-se apenas o primeiro elemento, eu tentei utilizar o [0] porem meu retorno foi esse erro:
ERRO:
arning: Invalid argument supplied for foreach() in C:\Apache2\htdocs\teste.php on line 44

Meu código:
foreach($lista_quantidade[0] as $quantidade_unidade){
       $quantidade_unidade = intval($quantidade_unidade);
       $quantidade_unida_diferen = $quantidade - $quantidade_unidade;
       echo "Diferença de quantidade: $quantidade_unida_diferen" . "
";
      }

Answer: Se você deseja pegar o elemento [0] do seu array, pq precisa percorre-lo? Você não precisa de um foreach para ter esse valor.
Comment: tem razão nao havia me ligado


What's the difference between running Python web applications in normal way and running them under wsgi?

Question: I know that in order to run a Python web application(an application developed with frameworks such as Flask & Django) on the server, you need to deploy it using things such as uwsgi, wsgi.. gunicorn.. etc, and configure it to run with the web servers like apache2 & nginx.
But, I know that I can just run python my_app.py and the application will work on the server using the ports like: mywebsite.com:5000. And I can use a proxy on the web server to redirect mywebsite.com:5000 to something like test.example.com or any place I want.
So what's the difference between the two ways? Which one should I use?
Thanks.
Answer: This isn't the case with all frameworks but django and flask when you run in their dev http mode, which you referenced, is only single threaded.
So the server can only handle a single connection at a time. So if two connections come in together the server will handle one and make the other wait.
A wsgi server with apache/nginx in front will handle many connections at once.
Comment: Isn't there an alternative way to run the application in multi-thread using the same `python` command without using `wsgi` and others?
Comment: that really depends on the framework you are using.
Comment: Even when you use a builtin development server you are still using WSGI. WSGI is the API by which modern Python web applications talk to a web server. So all modern sync frameworks rely on WSGI. Where you are confusing things is by saying 'wsgi' is an implementation of WSGI when it isn't. You likely mean 'mod_wsgi' and if that is the case that is what you should refer to it as. It is very rare to find a sync framework which isn't setup to run on top of a WSGI server. The main Python web frameworks that don't are actually async frameworks as there is not standard API for async.


Getting rid of text labels on overlayed px.bar plots

Question: I have successfully plotted five bar charts (all with the same x-axis) vertically, one on top of the other.  Each chart separately represents the time occurrence of different variables (identified by long Key Phrases) during the same period.  I have used px.bar with barmode = 'overlay' and facet_row = "Key_phrases".  The routine insists on writing the "Key_phrases" vertically on the the right hand border in addition to the legend, but the phrases as so long that they overlap one another.  How can I turn this off and write each phrase, horizontally inside its individual plot?
Comment: Can you include the code you used to generate your bar charts, and a screenshot of the bar chart you're getting? This will help clarify your question a bit, thanks!
Answer:
plotly express creates an annotation for each row of traces in a facetted figure
have created some sample data that generates a long KeyPhrase
generate a figure in way you describe
demonstrated overriding annotation text.  Another option would be remove the annotations

<code>phrase = "The COP26 summit will bring parties together to accelerate action towards the goals of the Paris Agreement and the UN Framework Convention on Climate Change "

df = pd.DataFrame(
    {
        "Key_phrases": np.repeat(
            [" ".join(phrase.split(" ")[5 * p : 5 * (p + 1)]) for p in range(5)], 4
        ),
        "x": np.tile(range(5), 4),
        "y": np.random.uniform(1, 4, 20),
    }
)

fig = px.bar(df, x="x", y="y", facet_row="Key_phrases")
fig.show()

# override annotation text
fig.update_layout(
    annotations=[
        {**a, **{"text": f"phr.{i+1}"}}
        for i, a in enumerate(fig.to_dict()["layout"]["annotations"])
    ]
)
</code>
Comment: Rob, you answered my question completely.  Thanks! This was something that I could not find in any of the documentations.  And it begs the next question: in the example you provide above,  how can I take the label phrases and write them instead inside each graph box instead of the external legend labels.  When I use the "annotate" option, it only puts the phrase in the last (bottom) box.  I have found examples that annotate all the graphs with the same annotations, but  I can't figure out how to annotate each of the boxes individually.


Learning the cello with limited money and not much help

Question: This is for a friend of mine, but I'll speak in first person to make it less awkward to type out.
I'm 23, almost 24, and I recently acquired a cello (an electric cello to be precise to keep noise down). I know that my age isn't exactly the prime age to be learning an instrument at, and my musical background consists of playing the flute in highschool at a very amateur level.
Cello tuition is very expensive where I live, and I don't have the money to pay for more than a lesson a week (which might not be sustainable anyways). So I've been trying to research what I could do to practice the cello outside of lessons (which I've not started yet) in an attempt to make lessons more cost efficient. That is, I'd like lessons to have more content in it since I can't afford them regularly.
But there is just too much online! It's very easy to get lost and it's difficult to separate what's right from wrong. What's the best way for me to learn the cello without a teacher? I really would like to devote a lot of time and self learn this as much as possible.
Comment: I didn't start guitar until I was 19. 24 is not too late at all. The main challenge you might face being 24 is practice time, assuming you are out working a full time job and living on your own and doing your own grocery shopping and cooking and cleaning and taxes. Time spent playing is the number one ingredient for success, so if you can get up to 1 - 2 hours a day you should be able to make some nice noises and play short pieces in one to two years.
Comment: In my time as an instrument learner (I've taught myself a decent amount of violin, bass, drums, harmonica, and piano) and as a teacher, I think what makes an instrument easier or harder is pretty much **love**. If you love it, you'll learn it, and it won't seem that hard (I'm pretty sure french horn is an exception... and maybe oboe?). Cello is a bit more forgiving on the intonation than violin and a more comfortable playing position, and I didn't find learning violin to be so hard it overpowered my love of it.
Comment: @ToddWilcox Thank you very much for the encouragement! However, learning cello alone isn't as, for lack of a better word, easy as learning the guitar. (Talking as my actual self for a moment and not for my friend, I too picked up the guitar at around 19, possibly 18. There's a lot of resources and I filtered the good from the bad by trying them. I imagine that it's not as simple for the cello which is somewhat a more "classical" instrument.)
Comment: You are not starting as an absolute beginner. You can already read music and you have the experience of learning and playing an different instrument. The best plan would be to pick a teacher and have a discussion up-front about arranging a schedule of lessons and practice that will work for you. Personal tuition is by far the best way to avoid starting out with basic problems of wrong posture, a badly-adjusted instrument, etc, which will limit and discourage your progress and could even lead to physical problems like chronic neck, shoulder, or hand strains.
Answer: I would focus here as you get started:

Learn to tune it and acquire whatever tools you need to tune it effectively. A chromatic electronic tuner is great for someone self-learning and much easier to use than a tuning fork or pitch pipes.
Learn how to hold the bow and bow on open strings (just the strings with no fingering). Practice long strokes that cover the whole length of the bow and short strokes in different areas of the bow. This is really important and takes plenty of practice, as different parts of the bow require different amounts of pressure and speed for the right volume and best tone. Web search the heck out of this and get all you can on it, while also playing and experiencing the feel for yourself.
Learn the first three places to put your fingers. Back in the day teachers would put thin pieces of masking tape down at these spots so they can be easily seen. That seems to have fallen out of favor but if you're self-teaching you get to decide. This is the best image I could find for it:

Image source
The yellow, red, and teal lines are where you want to focus on first. The numbers "1st, 2nd..." indicate fingers - your first finger is your index finger, fourth finger is your pinkie. You can use the chromatic electronic tuner to find the right places to put your fingers.
Also check out this page which seems to show scales in first position overlaid on top of where the tape would be if you are using it.

Finally, I hope you've taken up the cello because you love the sound and there is some cello music that compels you. If you can find something like 100 easy pieces for cello and look for ones that seem interesting, as well as finding sheet music for pieces that you really love, then you have something to help motivate you to learn. Once you have the barest basics down you want to practice rudimentary techniques like bowing and scales and vibrato and also start working on a song or two so you can hear yourself making music. The need to work on both technique and songs pretty much never ends. If you feel a little joy when the cello "speaks", you'll be hooked and you'll learn faster than you think.
Answer: Perhaps you could see if any nearby community colleges have something. Even junior colleges and 4-year colleges sometimes have faculty that offer private lessons. Generally such lessons are expensive as you have noted, but so is instruction in golf or ballroom dance (or piano).
Answer: Pay for one lesson.  Think about where you want to be with Cello in a few months and tell your teacher.  With one lesson a great teacher can set you on the right course.  Yes, even with just one lesson.
Comment: @CarlWitthoft I think it depends on what one is trying to do. I wouldn't say it's hard to recover as much as it takes a lot of time to figure out what one has been doing wrong for the last two years. Self-teaching is much slower than being professionally taught, because you don't even know what mistakes you're making until long after you've made those mistakes into habits, in some cases. Teachers normally point them out to you right away. I agree that regular teaching is the best way to learn. I disagree that just one lesson is not valuable.
Comment: Wrong.   Just so wrong.   Without regular interaction with someone who can observe your physical positioning and motion, you'll do bad things and find it very hard to recover.


Getting a taxonomy-term-name as plain-text in computed field

Question: In an entity-type with term-reference i want to add a computed field, which grabs the term and sanitizes it for further use with the drupal_clean_css_identifier for example. My code doesn't work, because field_get_items gives back a full link to the term instead the term name as plaintext:
<code>$entity_field[0]['value'] = drupal_clean_css_identifier(array_pop(field_get_items($entity_type, $entity, 'field_myterms'))));
</code>
Can someone help me out?
Answer: calling field_get_items() on a term reference field returns an array like this

Array(
  0 => Array(
    'tid' => 10,
  ),
)

to get the term name from the term id (tid) you should load the taxonomy term:

$field_myterms = field_get_items($entity_type, $entity, 'field_myterms');
if (!empty($field_myterms)) {
  $term = taxonomy_term_load($field_myterms[0]['tid']);
}

$term is an stdClass object:

stdClass Object
(
    [tid] => 1
    [vid] => 1
    [name] => test
    [description] =>
    [format] => filtered_html
    [weight] => 0
    [vocabulary_machine_name] => tags
    [rdf_mapping] => Array
        (
            [rdftype] => Array
                (
                    [0] => skos:Concept
                )

            [name] => Array
                (
                    [predicates] => Array
                        (
                            [0] => rdfs:label
                            [1] => skos:prefLabel
                        )

                )

            [description] => Array
                (
                    [predicates] => Array
                        (
                            [0] => skos:definition
                        )

                )

            [vid] => Array
                (
                    [predicates] => Array
                        (
                            [0] => skos:inScheme
                        )

                    [type] => rel
                )

            [parent] => Array
                (
                    [predicates] => Array
                        (
                            [0] => skos:broader
                        )

                    [type] => rel
                )

        )

)

to set the computed field value:

$entity_field[0]['value'] = drupal_clean_css_identifier($term->name);
Comment: Thanks a lot! Your answer is perfect, but for now i can't give you any credit-points 'cause i've got not enough reputation …
Comment: Finally, here are your credits!


Regex para validar número de documento nacional

Question: Estou tentando criar um validador de documentos nacionais que aceite números e letras ou somente número com limite de 11 caracteres em JavaScript.
O problema está na criação do regex.
Segue o código:
var documento = 'abc123-$/';
alert(documento.replace(/^[A-Za-z0-9]{0,5}\d+[A-Za-z0-9]{0,6}$g/,"")); // resultado deveria ser: abc123

var documento = 'abcdef-$/';
alert(documento.replace(/^[A-Za-z0-9]{0,5}\d+[A-Za-z0-9]{0,6}$g/,"")); // resultado deveria ser vazio porque deve conter pelo menos 1 número

Segue um exemplo no JSFiddle: JSFiddle
Comment: No caso de documentos, acho que seria melhor fazer o [cálculo do(s) dígito(s) verificador(es)](https://pt.wikipedia.org/wiki/D%C3%ADgito_verificador), que eles geralmente possuem (descubra qual é o cálculo do documento que vc está trabalhando e implemente-o). Apesar da regex "funcionar", nem toda sequência de 11 dígitos/letras será um documento válido, caso este possua dígitos verificadores - e neste caso o cálculo destes já garante que o número do documento é válido, tornando a regex desnecessária.
Comment: Isso é meio impossivel porque estou usando um campo para todos os documentos nacionais. É um sistema de venda de passagens online, é necessário somente que o usuário preencha um documento com foto, pode ser desde carteira de trabalho a carteirinha da AOB num mesmo campo.
Answer: Utilize esta expressão regular: (?=.*\d)[A-Za-z0-9]{1,11}
Em que a demo no Regex101 pode ser vista.
Explicação

(?=.*\d) - Positive Lookahead, em que garante que pelo menos um número está presente na string.
[A-Za-z0-9]{1,11} - Corresponde de 1 a 11 caracteres de A a Z ou de a a z ou de 0 a 9. Então não são permitidos caracteres especiais.

Outro caso
Caso seja somente números ou letras de 1 a 11 caracteres, utilizar a seguinte expressão regular: [A-Za-z0-9]{1,11}
Sem a parte de verificar se há pelo menos um dígito.


installing numpy&scipy on centos 6.4

Question: I am working in a virtual environment and I am having trouble installing numpy and scipy. It is my understanding that I have to full install numpy before going to scipy, but I am having trouble installing numpy.
I usedpip install numpy and that installed numpy into my python2.7/site-packages/numpy directory, however, I am trying to run python setup.py install --user as stated here numpy build and I keep getting the error "this is the wrong file to run". I do not know where to go from here....and I still need to install scipy
Comment: The question is unclear, sounds like pip installed numpy ok on your system but you have trouble with scipy? You should include I/O from your shell commands.
Answer: numpy and scipy come pre-compiled with CentOS, just type:
sudo yum install numpy scipy

it is always harder to install from source code.

installing numpy&scipy on centos 6.4


Accessing private instances of Github and Gitlab through their respective Python APIs

Question: Can I access private instances of Github and Gitlab through API wrappers in python such as pygithub and python-gitlab. For example, if I want to access my company's private server of Github and Gitlab, is it possible? Any help on the matter would be really appreciated!
Answer: When using python-gitlab, use:
import gitlab
gl = gitlab.Gitlab('http://your_gitlab_instance_url.com', private_token='token')

Mentioning the url of the private instance does the job. The method may fail though, if there is some other secondary forms of security authenticators.
When using pygithub, use:
from github import Github
g = Github(base_url="https://{hostname}/api/v3", login_or_token="access_token")

Works fine with the Rest API for github api v3


Is there any event fires after $("#").load() is completed in Jquery?

Question: I want to change some partial-view html code after the partial-view is loaded by this function
<code>$("#myRootElement").load("MyAction?Parameter=" + value);
</code>
I saw inside the JQuery source code, there is a
<code>$("#myRootElement").innerHtml = "MyPartialViewHtmlCode"
</code>
But I didn't find any event fires after this inner html is set. I want to fires a event after this here is what I have tried.
<code>$("#myRootElement").on('load', function(){
  // My code.
})

$("#myRootElement").load('action?parameter=' + value);
</code>
It doesn't work at all. The break point never been hit.
Comment: jquery document https://api.jquery.com/load/  have callback function, try normal action like `console.log('message');` in call back function for testing.
Comment: Why not do it when the entire document is ready, a la $(document).ready?
Answer: load provides a callback you can use
<code>$("#myRootElement").load('action?parameter=' + value, function() {
  // load complete  do stuff
});
</code>
Comment: Thank you DP. And thank you everyone, I am crying about my foolish now.
Answer: You can see this page, there is a callback param.
Use like this
<code>$("#myRootElement").load("MyAction?Parameter=" + value, function() {
  alert( "Load was performed." );
});
</code>


Access inline javascript variables that are generated via Ajax call? Barba.js question specifically

Question: I'm using Barba.js on my website. When the 'Portfolio' page is loaded via Barba.js, I run a function, let's call it get_portfolio_items(). There are some inline javascript variables that get_portfolio_items() needs to access the values of. If the 'Portfolio' page is the very first page to be loaded, then get_portfolio_items() accesses these variables just fine. However, if another page is loaded first, and then clicked into the Portfolio page, I get the error:

loadMoreVars is not defined.

Even though I can see loadMoreVars is in the DOM.
How can I access these variables in get_portfolio_items()  ? Thank you!
This is the script in the actual HTML that appears on the new page:

This is the function that is called whenever a new page is loaded via Barba.js
function get_portfolio_items(){
 alert(loadMoreVars.postsPerPage);
 alert(loadMoreVars.maxNumPages);
}

This is the Barba.js code that triggers the function when a new page is loaded.
Barba.Dispatcher.on('newPageReady', function(current, prev, container) {
    history.scrollRestoration = 'manual';
    get_portfolio_items()
});

How can I get the function to see the variables and thus alert them out?
Comment: Can you provide more code? It's kinda hard to understand what is happening.
Comment: Hi there, I edited the above to provide more clarity. Please let me know if that makes sense
Comment: Is the script tag inside the head or body of the page?
Comment: The script that contains 'loadMoreVars' is loaded into the body, and the barba.js and related scripts are initially loaded in the body as well
Answer: A bit late, but i managed to make it work. It's important to set the variable to the window object.

// JS FILE
Barba.Dispatcher.on('newPageReady', function(currentStatus, oldStatus, container) {
  var inlineScript = $(container).find('script.loadInlineScript')
  inlineScript.each(function(i, elm) {
    eval(elm.innerHTML);
  })
});


MVC4 Areas, HomeControllers and Routing

Question: http://blog.falafel.com/duplicate-controller-names-aspnet-mvc-areas/
Followed this advice and am now running.  However, when hitting /area/home/index the correct controller action fires but it is using the Index.cshtml from the root site rather than the Index.cshtml from the Area folder!  Any ideas how to "fix" this?
Or is there a better way to handle routing to accomplish the same thing?
Goal:
http://example.net/  -> HomeController / Index (root)
http://example.net/area1  -> area1.HomeController.Index / area1's Index.cshtml
http://example.net/area1/NotIndex  -> area1.HomeController.NotIndex / area1's NotIndex.cshtml
http://example.net/area2  -> area2.HomeController.Index / area2's Index.cshtml
etc...
I tried attribute routing for a different area.
<code>[RouteArea("ProductReuse")]
[Route("ProductReuse")]
public partial class ProductReuseController : BaseProductReuseController
{
    [HttpGet]
    [Route("Index")]
    public ActionResult Index()
    {
        if (SessionUserLogin == null) return LoginActionResult(SessionAppName);

        var serviceResponse = _productReuseService.IndexQuery(SessionUserId);
        var response = _mapper.Map<IndexViewModel>(serviceResponse);

        return View(response);
    }
    ...
}
</code>
This is close but you still have to have an URL that looks like:
http://example.net/ProductReuse/Index
If you try to hit http://example.net/ProductReuse it bombs out.
TIA
Answer: I discovered that you can add an empty string route name to the routing attribute.
<code>[RouteArea("ProductReuse")]
[Route("ProductReuse")]
public partial class ProductReuseController : BaseProductReuseController
{
    [HttpGet]
    [Route("Index")]
    [Route("")]  // Use an empty name to set the default page...
    public ActionResult Index()
    {
        if (SessionUserLogin == null) return LoginActionResult(SessionAppName);

        var serviceResponse = _productReuseService.IndexQuery(SessionUserId);
        var response = _mapper.Map<IndexViewModel>(serviceResponse);

        return View(response);
    }
    ...
}
</code>

MVC4 Areas, HomeControllers and Routing


Prove that in separable space X $(x_n)$ is convergent to $x_0$ iff $d(x_n, a)$ converges to $d(x_0, a)$ for each $a \in A$where A is dense subset of X

Question: Let $(X,d)$ be a metric space and $A$ a dense countable subset of X.
Then
$$
x_n \rightarrow x_0 \iff \left( \forall_{a \in A} \text{  } d(x_n, a) \rightarrow d(x_0, a)  \right)
$$
My take: for arbitrary $\epsilon > 0$ and $a \in A$ we have that $\exists_N \forall_{n_0 > N} \text{ }d(x_{n_0}, x_0) < \epsilon$. Now using the triangle inequality we obtain:
$$
d(x_n,a) \le d(x_n, x_0) + d(x_0, a) < d(x_0, a) + \epsilon
$$
move $d(x_0, a)$ to left hand side of equation and since d is symmetric:
$$
|d(x_n, a) - d(x_0,a)| < \epsilon
$$
This completes the $\implies$ proof. How can I prove the $\impliedby$?
Comment: I don't see in what the separability is relevant...
Comment: Sorry for possible misleading title @Surb. Perhaps its not limited to separable spaces - it's just a lemma in the proof I am trying to understand("Every separable metric space is homeomorphic to a subset of Hilbert's cube").
Answer: Choose $a$ such that $d(x_0,a)<\epsilon/4$. There exists a natural number $N$ such that $n>N\Rightarrow |d(x_n,a)-d(x_0,a)|<\epsilon/2$, which implies $d(x_n,a)\leq d(x_0,a)+\epsilon/2$. Then
$$d(x_n,x_0)\leq d(x_n,a)+d(x_0,a)\leq d(x_0,a)+(d(x_0,a)+\epsilon/2)\leq2\epsilon/4+\epsilon/2=\epsilon$$
Hence $x_n\to x_0$
Comment: Thank you. The assumption that A is dense ensured $a \in A$ such that $d(x_0, a) < \epsilon / 4$ exists, right?
Comment: @math_beginner Yeah.
Comment: what if $ \ eps  < 0$


How to update or insert data with WITH subquery? and avoid `PG::UndefinedTable: ERROR: missing FROM-clause entry for table` error

Question: Im trying to run simple sql query:
    <<-SQL.squish
      WITH payloads as (
        INSERT into text_payloads (text, created_at, updated_at)
          SELECT text, created_at, updated_at
          FROM text_messages
        RETURNING id, text, created_at, updated_at
      )
      UPDATE text_messages
      SET
        payload_id = text_payloads.id,
        payload_type = 'TextPayload'
      WHERE
        text_messages.text = text_payloads.text AND
        text_messages.created_at = text_payloads.created_at AND
        text_messages.updated_at = text_payloads.updated_at
    SQL

but got this error:
PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "text_payloads"
LINE 1: ...d_type = 'TextPayload' WHERE text_messages.text = text_paylo...

I've already tried to add FROM payloads and even LEFT OUTER JOIN text_payloads, but nothing helped. How can I implement this update or similar insert operation with WITH subquery and its result?
Thank you very much in advance!
Answer: The error message is clear: there is no FROM clause in your UPDATE statement to perform the join between the CTE (I guess that you want to use the CTE and not
text_payloads) and text_messages.
The correct syntax is:
WITH payloads as (
  INSERT into text_payloads (text, created_at, updated_at)
    SELECT text, created_at, updated_at
    FROM text_messages
  RETURNING id, text, created_at, updated_at
)
UPDATE text_messages
SET
  payload_id = payloads.id,
  payload_type = 'TextPayload'
FROM payloads
WHERE
  text_messages.text = payloads.text AND
  text_messages.created_at = payloads.created_at AND
  text_messages.updated_at = payloads.updated_at

See the demo.
Answer: here is working code
    <<-SQL.squish
      WITH payloads as (
        INSERT into text_payloads (text, created_at, updated_at)
          SELECT text, created_at, updated_at
          FROM text_messages
        RETURNING id, text, created_at, updated_at
      )
      UPDATE text_messages
      SET
        payload_id = text_payloads.id,
        payload_type = 'TextPayload'
      FROM payloads, text_payloads
      WHERE
        text_messages.text = text_payloads.text AND
        text_messages.created_at = text_payloads.created_at AND
        text_messages.updated_at = text_payloads.updated_at
    SQL


How to split a data frame into multiple data frames based on columns

Question: I have the following data frames:
import pandas as pd
df = pd.DataFrame( {
    "Name" : ["gene1","gene2","gene3","gene4"] ,
    "T1" : [0.33,1,3,4],
    "T2" : [1.23,2.1,3.5,5.0], } )

Which looks like this:
In [30]: df
Out[30]:
    Name    T1    T2
0  gene1  0.33  1.23
1  gene2  1.00  2.10
2  gene3  3.00  3.50
3  gene4  4.00  5.00

What I want to do is group based on T1 and T2 (basically all columns from 2nd columns onward). Note that the column names follow no pattern and can be more than two.
The end result I hope to get is this:
T1
    Name    T1
0  gene1  0.33
1  gene2  1.00
2  gene3  3.00
3  gene4  4.00

T2
    Name    T2
0  gene1    1.23
1  gene2    2.10
2  gene3    3.50
3  gene4    5.00

How can I achieve that?
I tried this but doesn't give what I want:
tlist = list(df.columns[1:])
for dft in df.groupby(tlist,axis=1):
    print df

Comment: In your hoped result you are not grouping, you are just listing the columns. If that's really what you want, you just have to set "Name" as an index.
`df = df.set_index("Name")` and then print the results
`for c in df.columns:
    print(df[c])`
Answer: You can get there using pd.melt():
melted = pd.melt(df, id_vars='Name', var_name='t_col')

for t_col, sub_df in melted.groupby('t_col'):
    print(sub_df)

    Name t_col  value
0  gene1    T1   0.33
1  gene2    T1   1.00
2  gene3    T1   3.00
3  gene4    T1   4.00
    Name t_col  value
4  gene1    T2   1.23
5  gene2    T2   2.10
6  gene3    T2   3.50
7  gene4    T2   5.00


Php loop to create variables

Question: I have a list of variables i need to create like so:
$meta_2_length = get_post_meta( get_the_ID(), 'meta-2-length', true );
$meta_2_loft = get_post_meta( get_the_ID(), 'meta-2-loft', true );
$meta_2_lie = get_post_meta( get_the_ID(), 'meta-2-lie', true );
$meta_2_bounce = get_post_meta( get_the_ID(), 'meta-2-bounce', true );

I need to make these for the numbers 2 - 14 so I figured the best way would be a loop. I am new to php but want to write as clean as possible. I thought this might work:
for($i = 0; $i <= 14; $i++) {
   ${"meta_$i_length"} = "get_post_meta( get_the_ID(), 'meta-$i-length', true );";
}

but when it doesnt seem to be working when I echo $meta_3_length
Comment: Numeric variables like this are almost always wrong. This is what arrays are for.
Answer: My recommendation for you is create an array. And give the array values in the loop.
example
$foo = array();
for($i = 0; $i <= 14; $i++) {
   $foo[] = "get_post_meta( get_the_ID(), 'meta-$i-length', true );";
}

then echo data by using the array
Comment: Why did you put the call to `get_post_meta` in quotes?
Comment: If I use this (without qoutes around `get_post_meta`) and I echo it out like `` I get nothing.
Answer: You can use variable variables:
for($i = 0; $i <= 14; $i++) {
   $varname = "meta_$i_length";
   $$varname = get_post_meta( get_the_ID(), 'meta-$i-length', true );
}

Answer: Use an array of associativer arrays.
$metas = array();
$id = get_the_ID();
for ($i = 0; $i <= 14; $i++) {
    $metas[] = array(
        'length' => get_post_meta($id, "meta-$i-length", true),
        'loft' => get_post_meta($id, "meta-$i-loft", true),
        'lie' => get_post_meta($id, "meta-$i-lie", true),
        'bounce' => get_post_meta($id, "meta-$i-bounce", true)
    );
}

Now you can do echo $metas[3]['length'];.
Comment: Worked perfect and clean. Also gives me a better understanding of how to set up PHP variables like i would in JS
Answer: You can use extract with an associative array:
$arr = [];
for($i = 0; $i <= 14; $i++) {
    $arr["meta_{$i}__length"] = get_post_meta( get_the_ID(), "meta-{$i}-length", true);
}
extract($arr);

Then, you can do echo $meta_3__length and get the result of the function call get_post_meta( get_the_ID(), "meta-3-length', true);
I hope it helps

Php loop to create variables


Is it possible to know if relation R, is true about two sets of input using neural networks

Question: I have just seen an introduction video to neural networks, and I was wondering, are neural networks only useful for when you want to say that "A based on it's features matrix, belongs to category C", or can it also be used to detect relations as well.
What I mean is, is it possible to say that "if you (the computer) see these numbers for A [1 (male), 4 (blood type B+), 78 (weight), 23 (age)] and you see this type of matrix for B [1 (male), 5 (blood type B-), 82 (weight), 25 (age)], then 'learn' that they have the relationship R (1 = are brothers), else they are not related (0) and if I give you new sets in the future, decide if they are related or not based on what you have learned"? In other words, is it possible to detect relationship between two sets of input samples, in a manner that the relation X is true only about these people from group A and these people from group B; based on their matrices?
If neural networks are only for classification of only one group, what machine learning method can be used to train the computer (or make a model) to detect if relationship R is true about two streams of input or not? Because even clustering that seems a bit close, decides if one items belongs in a category or not.
I know that probably these two groups can be combined into one huge group, and be arranged randomly, to see if they are brothers or not, but other than that method, which seems pretty expensive, are there any other methods?
Comment: It sounds like "abstraction".  Are you asking if a human can abstract based on the matrix, or if another network can do that?
Comment: I am not sure of what you mean by abstraction. Just in case, I am thinking of another network doing this. But what I was thinking about, was a training a (machine learning) model, that when you give it two matrices [45,89,B+,5] and [55,39,A+,5], it outputs either 1 or 0. 1 = the relationship is true, 0 = they are not related.
Comment: This is rather broad, but ultimately an answer can be provided here. I'm voting to leave open.
Answer: The thing to recognize here is that although this looks different than a prototypical classification problem, it is ultimately the same.  Instead of having data on various individuals, you have sets of data on pairs of individuals.  The classes to which you want to assign your inputs aren't, say, spam vs. good, but brothers vs. not-brothers.  You would need think carefully about how you design the neural network if you want optimal performance, and not just use a default fully-connected feed-forward network.  For example, you might want a convolutional NN with specific receptive fields.  You might also want to do some preprocessing of your data and feed that into the network for training instead of using the raw data.  For example, you might want to determine similarities between each pair of measurements (e.g., heights) according to various measures of similarity, and use one set of similarities as your inputs instead of two sets of raw measurements.  This would certainly be a more complex project than the standard textbook examples, but the point is that it is ultimately similar.
Comment: Hamming distance is not (necessarily) Mahalanobis distance.  If I had a pair of NN's I would also want input/output pairs (which I could determine as long as I knew the bounds of the input variables) and I could then look at differences.  I'd be worried about using weights because much more extremely like Perl, with NN's there are an infinite number of ways to "skin" any particular "cat"


Sencha Touch: Displaying and editing HasMany field on formpanel

Question: My Question is: How to display and edit a hasMany field on the formpanel of sencha touch API
Sencha touch does not have a listbox or any other feature to innately do this.
My example
Candidate:

firstName: [textfield]
lastName: [textfield]
...
list of interviewers

candidate has many interviewers
I looked into tpl and xtemplates but could not get anything to work
My idea is to have a textfield that also functions as a search with ajax with an add button ( + ) beside it, if it's any but the first textfield an ( - ) button.
Even getting a textfield and a button to display on the same row seems difficult
My Models:
     Ext.require('Candidates.model.Interviewer', function() {
        Ext.define('Candidates.model.Candidate', {
            extend: 'Ext.data.Model',

            config: {
                fields: [
                    {name: 'id', type: 'string'},
                    {name: 'firstName', type: 'string'},
                    {name: 'lastName', type: 'string'},
                    {name: 'email', type: 'string'},
                    {name: 'dept', type: 'string'},
                    {name: 'room', type: 'string'},
                    {name: 'greet', type: 'string'},
                    {name: 'present', type: 'boolean'},
                    {name: 'date', type: 'date'},
                    {name: 'status', type: 'string'},
                    {name: 'completed', type: 'boolean'}
                ],
                hasMany: {
                    model: 'Candidates.model.Interviewer',
                    name: 'Interviewers'
                }
            },
      });

Interviewer
    Ext.define('Candidates.model.Interviewer', {
        extend: 'Ext.data.Model',

        config: {
            fields: [
                {name: 'id', type: 'int'},
                {name: 'firstName', type: 'string'},
                {name: 'lastName', type: 'string'},
                {name: 'username', type: 'string'},
                {name: 'password', type: 'string'},
                {name: 'email', type: 'string'},
                {name: 'dept', type: 'string'}
            ]
        }
    });

in fieldset items [
    {
        xtype: 'textfield',
        name : 'firstName',
        label: 'First Name',
    },
    {
        xtype: 'textfield',
        name : 'lastName',
        label: 'Last Name',
    },
    {
        xtype: 'textfield',
        name: 'interviewers',
        id: 'interviewerfield',
        label: 'Interviewer(s)',
        tpl: [
            '
',
                '<tpl for="interviewers">',
                    '
',
                        '{firstName}',
                    '
',
                '</tpl>',
            '
'
        ].join(''),
        store: 'Candidates'
    },

Idea's I tried to even just display a list of interviewers to the field
Anybody have any idea a way to display a many field onto the formfield?
Comment: My form displays/updates the data for the other fields so I at least know the models and store are working for candidates.
Comment: oO - the name of your store is the same as the app?!
Answer: I suffer from the same problem, i find solution by Ext.dataview.DataView instead of using Ext.List.