Content: Has taxonomy term ID depth modifier

Question: Answer to my question was found here: Show all child nodes of a taxonomy term D7.
But I'm not able to understand the use case of the second option: "Content: Has taxonomy term ID depth modifier" as in the figure.
Answer: The taxonomy term ID depth modifier option allows you to reuse the same view to query nodes according to varying depths in the taxonomy tree. For example let's say this is your taxonomy.
<code>North America (term id:7)
- Canada
- Mexico
- United States
-- California
--- San Francisco
--- Los Angeles
--- etc
</code>
With a term id of 7 and a depth modifier of 0 your query would include nodes tagged with "North America". With a depth modifier of 1 your query would include nodes tagged with "North America", "Canada", "Mexico" and "United States", and so on.
The term depth modifier is passed as the second argument (Contextual Filter in Drupal 7) to the view separated by a slash. So if the term id is 7 and the depth modifier is 2 the arguments for the view are '7/2'.


Theater Seating application in WPF -problems in databinding

Question: I am new to WPF, and I want to develop an application for Theater seating in WPF- c#.net.
I did some research but i am lost as i do not know how each seat's data (sold or not, price, in which row) should be eventually bound to field in a table in SQL Express.
Should i be using ObservableCollection to populate the contents of a Datatable in it?
Also, should i be using a grid of buttons? or rectangles? How should i proceed if i want the front left and front right buttons to be inclined a bit instead of being horizontal?
Should i be using a wrappanel if i want to have three areas for the seats? Left area, space for alter, middle area, space for alter and right area?
If somebody can give me some hints for me to start, i will be more than glad.
Thanks in advance...
Answer: You're asking a lot of questions at once, and it would be impossible for anyone to answer them all without writing your program for you, but I'll offer the high-level approach that I would take. You'll have to spend some time to dig into the details. Plenty of info on StackOverflow and otherwise to get help on these details.
Anyways-
Database, 3 tables
SeatStatus Table

ID, int, Primary Key
Name, string    (e.g. Available,
Sold, Broken)

PricePoint Table

ID, int, Primary Key
Name, string    (e.g. Default,
OnSale, Premium)
Price, float (e.g. 10.0, 8.0, 12.0)

Seat Table

ID, int, Primary Key
SeatStatusID, int, Foreign Key ->
SeatStatus Table
PricePointID, int, Foreign Key ->
PricePoint Table
Row, int
Column, int

Application Model
I would use Entity Framework 4 and generate your model from your TheaterSeating database. This will create Seat objects for you that automatically contain references to SeatStatus and PricePoint. Very slick.
Edit 1
Once you've created your model you will have an .edmx file that represents your data, and can read/write to your database easily. Assuming this file is called TheaterSeatingModel.edmx, the auto-generated classes will provide you with the means to call something along the lines of:
TheaterSeatingEntities entities = new TheaterSeatingEntities();

You now have access to your entire database, including:
entities.Seats
entities.PricePoints

etc.
You can use these classes as you would naturally expect, an example:
Seat seat = new Seat();
seat.Row = 10;
seat.Column = 5;
entities.Seats.Add(seat);
entities.SaveChanges();

Populate an ObservableCollection with these seats inside a class, and set your View's (the XAML control's) DataContext to this class.
public ObservableCollection<Seat> SeatCollection {get;set;}

public ViewModelConstructor()
{
   TheaterSeatingEntities entities = new TheaterSeatingEntities();
   SeatCollection = new ObservableCollection<Seat>(entities.Seats);
}

This will populate your collection with all the Seat objects.
A simple WPF binding to this collection would be something along the lines of:
<ListBox ItemsSource={Binding SeatCollection} />

UI
If it were me I would use a WPF ItemsControl whose ItemsSource is set to your ObservableCollection of Seats. Place this ItemsControl inside of a Canvas. The ItemsControl's ItemsControl.ItemTemplate control what each Seat will look like in your view. You can bind the ItemTemplates Canvas.Left and Canvas.Top to the Seat.Row and Seat.Column to place the seats in their appropriate positions on screen. You can make the template be a button, rectangle, image of a seat, anything. You can set up Styles and Triggers to make the Seat display differently depending on PricePoint, SeatStatus, etc.
I think WPF will be great for the project you're starting.
Good luck!
Comment: Hello there, sorry for being so general in my question. But as all notions are new to me, i got quite lost ...In trying to find out how to bind the WPF controls with the database (to reflect updates, inserts and deletes)I got lost between ADO.NET EF, MVVM, ObservableCollection...Anyway thanks a million for your guidance.
Comment: No worries, I've been there many, many times. Just try to pick one thing and keep your head above water. In your case if you've already put together your database, I would start by generating some C# classes that represent your database using Entity Framework. This is quite straightforward to do, and requires no coding on your part for basic CRUD (CReate, Update, Delete) operations. See this page for doing so: http://www.asp.net/mvc/tutorials/creating-model-classes-with-the-entity-framework-cs Start with the "Creating the ADO.NET Entity Data Model" section.
Comment: ok I got my ADO.NET Entity Data Model, thanks again for your guidance. Now how do i populate the observablecollection with the data of each entity? Any tutorial in C#.NET somewhere? it seems to be simple but i could not find an example...


RaphaelJS/Javascript update path instead of creating new one

Question: I have a textbox where the position of a co-ordinate have to be entered. Then after that by clicking on Set, the text(co-ordinates) are assigned to variable c. And clicking Draw draws a path to the defined co-ordinate.
What I want to do is update the existing path every time I click on Draw. But all it does is keep creating new paths when I click on Draw. Where am I going wrong?
Here is the FIDDLE

    Enter co-ords  >  Click Set  >  Click Draw

    <input type="text" id="b1" value="100,400">
    <button type="button" onclick="set()">Set</button>

    <button type="button" onclick="draw()">Draw</button>

Answer: Easy: You're making a new Raphael.path() object each time the user clicks "draw," when you need to be updating the existing one (if "draw" has been clicked at least once already).
//line needs to be declared outside the function, without an initial value
if (typeof line === "undefined") {
    line = paper.path(linepath);
} else {
  line.attr("path", linepath);
}

While we're here, you don't want to assume the user enters three-digit values for the coordinates if you're not establishing that condition as a restriction. Instead of getting the x/y values from the input with substrings, do this:
var posX = parseInt(c.split(",")[0], 10);
var posY = parseInt(c.split(",")[1], 10);

updated fiddle


Use UITableViewCellDeleteConfirmationControl to know what is the current cell's subview

Question: Is it OK to use UITableViewCellDeleteConfirmationControl this way:
- (void)layoutSubviews {
    [super layoutSubviews];

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:0.0f];

    for (UIView *subview in self.subviews) {
        if ([NSStringFromClass([subview class]) isEqualToString:@"UITableViewCellDeleteConfirmationControl"]) {
        CGRect newFrame = subview.frame;
        newFrame.origin.x = 200;
        subview.frame = newFrame;
        }
        else if ([NSStringFromClass([subview class]) isEqualToString:@"UITableViewCellEditControl"]) {
            CGRect newFrame = subview.frame;
            newFrame.origin.x = 100;
            subview.frame = newFrame;
        }
        else if ([NSStringFromClass([subview class]) isEqualToString:@"UITableViewCellReorderControl"]) {
        CGRect newFrame = subview.frame;
        newFrame.origin.x = 200;
        subview.frame = newFrame;
       }
   }
   [UIView commitAnimations];
}

Even though UITableViewCellDeleteConfirmationControl is not a public class?
Answer: First, a class is not a string. You should use NSStringFromClass([subview class]) to get a string representation of the class name.
Second, having the entire class name as a string literal is a big risk, and you should not have it so obvious. For instance, you could test if the name contains a portion of the name you are looking for: [className rangeOfSubstring:@"DeleteConfirmation"].location != NSNotFound.
Third, the reason this is not exposed is because it is private implementation of tableview cells. A good example why you shouldn't is on iOS7, the entire implementation of cells has been changed completely. The classes you mention in your example are no longer used.
Answer: Since you're comparing string equality you're not exposing any private API's and therefore should be eligible for AppStore submission.
I've been successfully able to use this equality check in my own app that's made it to the AppStore.


preg_match_all, espressão regular no php com variaveis

Question: Olá estou com dificuldades em monta a expressão regular, e a função me retorna 3 posições no array todas vazias;
preg_match_all('/(.*)<\a>/i', $page_content, $sku_3_a);

array(3) {
[0]=>
  array(0) {
  }
  [1]=>
  array(0) {
  }
  [2]=>
  array(0) {
  }

Comment: Qual a *string* que você está utilizando? Quais partes da *string* você quer capturar?
Comment: O valor de dentro da tag : 32cm
Comment: parece que contou pela quantidade de itens que está no site, mas não retornou o conteúdo.
Answer: Provavelmente não está funcionando pois você está escapando as aspas sem necessidade. Você só precisa escapar essas aspas, quando a função começar com elas, por exemplo
preg_match_all("necessário \" escapar", $var)

Caso contrário
preg_match_all(' "Aqui" não precisa ', $var)

Caso você esteja tentando extrair os links de uma página, basta usar a "Regex" abaixo (mais curta):
preg_match_all('/]*>(.*)<\/a>/i', $page_content, $sku_3_a);

Caso você queira pegar apenas o valor do HTML, basta usar strip_tags
strip_tags('32cm');

// Output: 32cm

Comment: Opa, obrigado pelo exemplo, estou testando


Como faço para contar a quantidade de registros, onde registros iguais são agrupados e equivale a apenas um, e impor uma ordem ao mostrar

Question: Tenho a tabela de relação com as colunas autor e time.
Preciso contar a quantidade de registros que o autor tem, sendo que os registros agrupados por autor e time conte como apenas 1, e depois exibir.
Exemplo:
Autor -------- Time
Gabriel ------- X
Gabriel ------- X
Gabriel ------- Y
João ---------- Z
João ---------- Z
João ---------- Z
No exemplo, onde o autor é Gabriel e o time é X seria contado apenas como 1 registro, o mesmo para João. Sendo assim, ao exibir na ordem decrescente ficaria:
Gabriel = 2 registros
João = 1 registro

Não consigo passar disso:
$sql = $pdo->query("SELECT *, COUNT(autor) AS total FROM aa_usuarios_treinamentos_rel WHERE time>'$timeRanking' AND status='true' GROUP BY autor, time ORDER BY total DESC");

Answer: Segundo o cenário que você apresentou, a query básica ficaria assim
SELECT autor, count(DISTINCT time) FROM tbl GROUP BY autor

Veja em funcionamento no SQLfiddle
http://sqlfiddle.com/#!9/7c5220/1
Explicação

Nesse primeiro exemplo, está os dados reais, da tabela, mauro tem dois registros, felipe um registro e jesus um registro também.

Utilizando o COUNT(DISTINCT time) recebo os valores reais da query
Comment: Desde já, muito obrigado!
No meu caso, precisaria que os registros de mauro contasse como apenas 1 por ter os times iguais e caso mauro tenha um terceiro registro com o time 2, por exemplo, contasse 2 registros.
Comment: http://sqlfiddle.com/#!9/b6baa9/1

Nesse caso eu precisaria mostrar Gabriel 2, João 1 e Pedro 1, em ordem decrescente.
Comment: Atualizei o link, dê uma olhada.
Comment: Perfeito! Não conhecia esse método que você utilizou. Muito obrigado!
Comment: Caso tenha te ajudado, marque como melhor resposta, para ajudar outras pessoas com a mesma dúvida.


Tem como fazer um map() de um array de objetos no React?

Question: Estou fazendo um projeto onde preciso de vários cards de receitas que conterão: título e ingredientes. Esses cards devem ser expansíveis (O usuário verá o título e ao clicar, os ingredientes serão mostrados) e para facilitar, estou usando o Material Ui.
Como não sei a quantidade (a aplicação será dinâmica), gostaria de usar map() e notei que precisarei de dois map(): Um para os cards e outro para a lista de ingredientes que serão renderizados dentro do card.
Abaixo estão: o exemplo de objeto de entrada que usei para testar, como pensei em fazer a manipulação desse objeto e a mensagem de erro exibida.
Exemplo de entrada:
 const teste2 =[{
   title:"Brigadeiro",
   ingredients:["margarina","achocolatado","leite condensado"]
 },{
   title: "Pão assado",
   ingredients:["pão","margarina"]
 }]

Como pensei em fazer:
 const Recipes = (props) =>{
   let recipesList = props.objects.map((object, index)=>{

     let ingrList = object.ingredients.map((ingred,index)=>(
     <CardText expandable={true}>
       {ingred}
     </CardText>
   ))

     return(
       <Card>
         <CardHeader
           title={object.title}
           actAsExpander={true}
           showExpandableButton={true}
         />
         <CardText>
           {ingrList}
         </CardText>
       </Card>
   )})
 }

Erro:
 Recipes(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.
 Evaluating index.js

Alguém teria uma dica do que fazer? Existe algum método map() para objetos?
Observação:
Tentei separar mais os objetos, criando um só para as listas de ingredientes e renderizando-o dentro dos cards de receitas, porém a propriedade expandable={true} do componente <CardText>deixa de funcionar (os ingredientes aparecem sempre expandidos). Vale salientar que, nesse teste, não usei objetos.
Comment: O teu código parece-me bem, ondes estás a usar depois esse `Recipes`? Onde está o componente principal e o `render()`?
Answer: O erro ocorre por que não há nada sendo retornado do método render(). Isso está claro do código e da mensagem de erro.
Aqui vai minha sugestão para resolver o problema: divida a interface de usuário em partes menores. O problema fica mais fácil de resolver. Cada componente ou função deve ter somente uma responsabilidade. Vamos lá:
(1) Crie um componente Recipes para todas as receitas.
(2) Crie um componente Recipe para só uma receita.
(3) Crie um componente Ingredient para cada ingrediente.
1. Recipes.js
O componente Recipes só se importa em mostrar vários componentes Recipe.
(e.g.
  props.recipes ===
    [
      {
        id: 123,
        title: "Brigadeiro",
        ingredients: ["margarina", "achocolatado", "leite condensado"]
      },
      {
        id: 124,
        title: "Pão assado",
        ingredients: ["pão", "margarina"]
      }
    ]
)

const Recipes = (props) => {
  const recipeComponents = props.recipes.map(recipe => (
    <Recipe key={recipe.id} recipe={recipe} />
  ));

  return (

Receitas

      {recipeComponents}

  );
};

2. Recipe.js
O componente Recipe mostra uma receita individual (e varios ingredientes).
(e.g. props.recipe ===
  {
    title:"Brigadeiro",
    ingredients: ["margarina", "achocolatado", "leite condensado"]
  }
)

const Recipe = (props) => {
  const ingredientComponents = props.recipe.ingredients.map(ingredient => (
    <Ingredient key={ingredient} ingredient={ingredient} />
  ));

  return (
    <Card>
      <CardHeader
        title={props.recipe.title}
        actAsExpander={true}
        showExpandableButton={true}
      />
      {ingredientComponents}
   </Card>
  );
};

3. Ingredient.js
O componente Ingredient tem o papel de renderizar um ingrediente individual.
(e.g. props.ingredient === "margarina")

const Ingredient = (props) => {
  return (
    <CardText expandable={true}>
      {props.ingredient}
    </CardText>
  );
};

Nota: todos os imports necessários foram omitidos para focar no problema em questão.
Answer: Fiz com state ao invés de props, se funcionar assim é só trocar depois:
import React, { Component } from 'react';

class Recipes extends Component {
    constructor(props) {
        super(props);
        this.state = {
            teste2: [
                {
                    title:"Brigadeiro",
                    ingredients: ["margarina","achocolatado","leite condensado"]
                },{
                    title: "Pão assado",
                    ingredients: ["pão","margarina"]
                }
            ]
        }
    }
    render() {
        return (
            <Card>
                { this.state.teste2.map((valor, x) => {
                    return (
                        <CardHeader
                            title={ valor.title }
                            actAsExpander={ true }
                            showExpandableButton={ true }
                            key={ x }
                        />
                        <CardText>
                            { valor.ingredients.map((ingred) => {
                                return { ingred }
                            }) }
                            { ingrList }
                        </CardText>
                    )
                }) }
            </Card>
        );
    }
}

Answer: const teste2 = [
    {
        title: "Brigadeiro",
        ingredients: ["margarina", "achocolatado", "leite condensado"]
    },
    {
        title: "Pão assado",
        ingredients: ["pão", "margarina"]
    }
]

const Recipes = (props) => {
    const { objects } = props

    const CardContent = objects.map(
        (elem) => {
            <CardHeader
                title={elem.title}
                actAsExpander={true}
                showExpandableButton={true}
            />
            for (ingred of elem.ingredients) {
                <CardText expandable={true}>
                    ingred
                </CardText>
            }
        })
    return (
        <Card>
            <CardContent/>
        </Card>
    )
}


Radius of convergence for unusual power series

Question: Consider the following infinite series:
$$\sum^\infty_{n=0}\frac{2^n}{2^n+1}x^{n^2}$$
I need to determine the radius of convergence. So, what troubles me is the $x^{n^2}$ as for a normal $x^n$ I already determined the radius to be $1$. Now, I interpreted the higher exponent as just considering the standard power series, which skips some exponents by coefficients of $0$. This should most certainly not affect the convergence of the series and also not the limit of the coefficients.
Comment: Compare https://math.stackexchange.com/questions/2172637/what-is-the-radius-of-convergence-of-displaystyle-sum-n-0-inftyzn2 or https://math.stackexchange.com/questions/1839670/whats-the-series-and-whats-the-radius-of-convergence-of-this-power-series – the same arguments can be used here.
Answer: If $|x|\geqslant1$, then it is not true that $\lim_{n\to\infty}\frac{2^n}{2^n+1}x^{n^2}=0$ and therefore the series diverges.
If $|x|<1$, then$$\left|\frac{2^n}{2^n+1}x^{n^2}\right|<\frac{2^n}{2^n+1}|x|^n$$and you already know that the series $\sum_{n=0}^\infty\frac{2^n}{2^n+1}|x|^n$ converges. Therefore, the original series converges too.
So, the radius of convergence is $1$.
Answer: Adding on the answer of José: you can write
$$\sum_{n=0}^\infty\frac{2^n}{2^n+1}x^{n^2}=\sum_{n=0}^\infty c_nx^n\;,\;\;\text{with}$$
$$c_n=\left\{\frac12,\,\frac23,\,0,0,\frac45,\,0,0,0,0,\,\frac89,0,\ldots\right\}= \begin{cases}\cfrac{2^{\sqrt n}}{2^{\sqrt n}+1},&n\;\text{is a perfect square}\\{}\\0,&\text{otherwise}\end{cases}$$
Thus, to find its convergence radius you can now apply Cauchy-Hadamard:
$$\limsup_{n\to\infty}\sqrt[n]{|c_n|}=\lim_{x\to\infty}\frac{2^{\sqrt n}}{2^{\sqrt n}+1}=1$$


Graphql is showing error while running with nodejs?

Question: I have newly installed graphql through nodejs, while setting up the built schema i got the following error
TypeError: builtScheme is not a function.
the code is given below
const express = require('express');
const bodyParser = require('body-parser');
const graphqlHttp = require('express-graphql');
const { builtScheme } = require('graphql');

const app = express();
app.use(bodyParser.json());

app.use('/api',graphqlHttp({
    schema: builtScheme(`
    type RootQuery {
        events:[String!]!

    }
    type RootMutation{
        createEvent(name:String):String

    }
    scheme{
        query: RootQuery
        mutation: Rootmutation
    }
    `),
    rootvalue:{
        events:()=>{
            return ["Romatic comedy","missing u","dont u dare"]
        },
        createEvent:(args)=>{
            const eventname =args.name;
            return  eventname
        }

    },
    graphiql:true

}))

app.listen(3000,(err,result)=>{
    if(err){
        console.log('node is unable to start');
    }
    else{
        console.log('node is running at 3000');
    }
});

if anybody know the solution,please revert back to me?
Answer: Looks like your looking for buildSchema, However you are const { builtScheme } = require('graphql');.
Try:
const { buildSchema } = require('graphql');
Comment: Thank you...sorry it was my mistake


mysql error 150 Foreign keys

Question: whenever I do insert into table xxx:
alter table xxx
add index FK68C3166C7B556202 (my_yyy_id),
add constraint FK68C3166C7B556202 foreign key (my_yyy_id) references yyy (yyy_id)

...I get:
19:27:44,355 ERROR SchemaUpdate:212 - Unsuccessful: alter table xxx add index FK68C3166C7B556202 (my_yyy_id), add constraint FK68C3166C7B556202 foreign key (my_yyy_id) references yyy (yyy_id)
19:27:44,356 ERROR SchemaUpdate:213 - Can't create table 'mydb.#sql-2f1b_657' (errno: 150)

why?  how do I resolve this issue?
Answer: Documentation:

If MySQL reports an error number 1005 from a CREATE TABLE statement, and the error message refers to error 150, table creation failed because a foreign key constraint was not correctly formed. Similarly, if an ALTER TABLE fails and it refers to error 150, that means a foreign key definition would be incorrectly formed for the altered table.

You need to provide more info about the foreign key constraint you're trying to make.
Answer: It's hard to guess what is wrong without details, but there are some common mistakes you might make :
1. yyy.yyy_id is not a unique/primary key
2. yyy.yyy_id and xxx.my_yyy_id have different types (e.g. yyy_id unsigned int, xxx.my_yyy_id int)
Comment: i think it's the latter, I have one bigint, one int
Answer: What version of MySQL are you using? Could it be older than 4.1 or so?
Can try create an index without adding the foreign key? If that works, try adding the foreign key.

mysql error 150 Foreign keys


Given $X\sim\mathcal{N}(0,\sigma^{2})$, obtain the Fischer information of $\sigma$ and $\sigma^{2}$

Question: Suppose the random variable $X\sim\mathcal{N}(0,\sigma^{2})$, where we do not know the value of the standard deviation $\sigma$. Then obtain the Fisher information $I_{F}(\sigma)$ through $X$. Suppose now the variance is the target parameter and obtain its Fisher information through $X$.
MY ATTEMPT
The answer to the first question can be obtained from what it follows
\begin{align*}
& f(x|\sigma) = \frac{1}{\sigma\sqrt{2\pi}}\exp\left(-\frac{x^{2}}{2\sigma^{2}}\right) \Rightarrow \ln f(x|\sigma) = -\ln(\sigma) - \ln(\sqrt{2\pi}) - \frac{x^{2}}{2\sigma^{2}} \Rightarrow\\\\
& \frac{\partial\ln f(x|\sigma)}{\partial\sigma} = -\frac{1}{\sigma} + \frac{x^{2}}{\sigma^{3}} \Rightarrow \frac{\partial^{2}\ln f(x|\sigma)}{\partial\sigma^{2}} = \frac{1}{\sigma^{2}} - \frac{3x^{2}}{\sigma^{4}} \Rightarrow\\\\
& -\textbf{E}\left(\frac{\partial^{2}\ln f(x|\sigma)}{\partial\sigma^{2}}\right) = \frac{2}{\sigma^{2}}
\end{align*}
Once $\textbf{E}(X^{2}) = \textbf{Var}(X)$, since $\textbf{E}(X) = 0$. Therefore, $I_{F}(\sigma) = 2n/\sigma^{2}$.
What concerns me is that I am not understanding the second question. Can someone help me get the right result? Thanks in advance!
Comment: Instead of the Fisher information for the standard deviation, find the Fisher information for the variance.  (Hint: to make taking the derivatives etc. a little easier notationally, define a parameter $\tau = \sigma^2$ and find the Fisher information for $\tau$.)
Comment: Oh, now I see. Thanks for the contribution. Is the answer given by $n/2\sigma^{4}$?
Answer: Your calculations for the first question seems correct. Second question asks you to set your measurement variable as the variance, i.e. $\theta=\sigma^2$, instead of $\theta=\sigma$. Then, we apply the same steps. Let $\tau=\sigma^2$ as @jbowman suggests.
$$\begin{align*} &\ln f(x|\tau)=-\frac{1}{2}\ln\tau-\ln\sqrt{2\pi}-\frac{x^2}{2\tau}\rightarrow \frac{\partial^2 f(x|\tau)}{\partial^2\tau}=\frac{1}{2\tau^2}-\frac{x^2}{\tau^3}\\ &\Rightarrow\mathcal{I}_F(\sigma^2)=\frac{n}{2\tau^2}=\frac{n}{2\sigma^4}\end{align*}$$


Probability of an event occuring

Question:
Possible Duplicate:
How to find percentiles of a Normal distribution?

The weight of a given Africander breed is said to follow a normal distribution with mean 200 kg and standard deviation of 10. Calculate
a) The probability that the weight of the Africander is less than 215 kg.
b) The probability that the weight lies between 190 kg and 210 kg.
c) Find the weight M kg such that the probability of X > M = 5%
d) Given that there are 10 Africander whose weights are greater than M kg, Calculate the probability that there are exactly 2 Africanders whose weights are greater than M kg.
Comment: Probably should label as homework.
Comment: maxwell, please [research our site](http://stats.stackexchange.com/questions/tagged/normal-distribution+homework) first and then come back if you have *specific* difficulties solving these problems.
Answer: All these answers can be found by using a table of the N(0,1) (standard normal) distribution.  When you are given the weight say X then you calculate Z=(X-200)/10.
So for example in a) you want P(X>215)= P(Z>(215-200)/10=1.5).  So you look up P(Z>1.5 in the standard normal table.
For b) you want P(210 > X > 190)=P(1 > Z > -1).
For c) you want P(Z > u)=1-P(Z < u)=0.05 so you look up u and then since u=(M-200)/10
M=10u+200.

Probability of an event occuring


How to obtain an Intersection of a List of complex custom Objects and a List of its String attributes and in Java using Stream API

Question: Here's my domain classes Location and Address:
public class Location {
    GPS gps;
    Address address;
    // etc.
}

public class Address {
    String street;
    String number;
    // etc.
}

Let's say I have a List of String's
List<String> houseNumbers

and a List of Locations
List<Location> locations

Now, I want to have only those Locations where the Location.address.number matches with any of the Strings in the houseNumbers list.
I've the following, which produces a compilation error: "expecting a
Predicate <? super java.lang.String> instead of a String".
My attempt:
List<Location> filteredLocations = locations.stream()
    .anyMatch(location ->
        housenumbers.stream().anyMatch(location.address.number)
    );

But how do I make sure to compare to every item in the houseNumbers List?
The following snippet did the trick:
List<Location> filteredLocations =
 locations.stream().filter(
   location -> housenumbers.contains(location.address.number)
).collect(Collectors.toList());

Comment: ***But how do I make sure to compare to every item in the List houseNumbers?*** - Use `filter` instead of `anyMatch` .
Comment: With filter it is still complaining about the Predicate. locations.stream().filter(
location ->
 housenumbers.stream().anyMatch(location.address.number)
)
Comment: When posting questions, please put in minimal code to demonstrate the issue.  That includes all classes and data structures required with input and expected output.  It should be in the form of a [mre].  And you should also take the [tour].
Answer: Dump the data from the houseNumbers into a HashSet a then in the stream check the house number of each Location against the Set.
For that, you would need to apply:

filter() operation to discard the locations, which has a house number that is not present in the list;
toList() as a terminal operation to collect the result into a list (or collect() with Collectors.toList() specified as an argument if you're using JDK 15 or earlier).

List<String> houseNumbers = // initializing the list
Set<String> numbers = new HashSet<>(houseNumbers);

List<Location> locations = // initializing the list

List<Location> filteredLocations = locations.stream()
    .filter(location -> numbers.contains(location.getAddress().getNumber()))
    .toList(); // for Java 16+ or collect(Collectors.toList())

*Sidenote: in Java, we use access modifiers to encapsulate the data properly withing the class. And getter methods serve a mean of accessing the data. Don't keep the fields public (or package-private). If you're doing a lot of JavaScript you might be accustomed to this location.address.number, but in Java it's not appropriate.
Comment: contains did the trick


Setting language of iOS keyboard extension

Question: I am developing a Keyboard extension for iOS. In Settings -> Keyboard -> Keyboards, the language is shown as English. Where to change this language?
Answer: In keyboard extension's Info.plist, change "NSExtension" -> "NSExtensionAttributes" -> "PrimaryLanguage" to the desired language.
Comment: And if you want it to say "Multiple languages" set it to "mul"


Como faço para somar um array?

Question: Boa tarde é assim a minha duvida é imaginando que tenhos estas variaveis :
var powerRangers = ['Red', 'Black', 'Yellow', 'Pink', 'Blue'];

e quando eu uso o for ( por exemplo )
for (var i = 0; i < powerRangers.length; i++) {
     console.log([i]+":"+powerRangers);
}

O objetivo e sair :
0: Red'
1:black'
2:Yellow'
... E sempre assim ... Help
E o que sai na real é :
0:Red,Black,Yellow,Pink,Blue
1:Red,Black,Yellow,Pink,Blue
2:Red,Black,Yellow,Pink,Blue
3:Red,Black,Yellow,Pink,Blue
4:Red,Black,Yellow,Pink,Blue
Comment: Isso não é somar um `array`, você quer concatenar um iterador numérico com elemento de um `array` em uma `string`.
Comment: Ahhh Obrigado !
Answer: Basta você acessar o índice do seu array, dessa forma:
 console.log([i]+":"+powerRangers[i]);

Comment: Meu deus muito obrigado ! :D
Comment: Neste caso o codigo correto seria :

for (var i = 0; i < powerRangers.length; i++) {
     console.log(i+":"+powerRangers[i]);
}

Como faço para somar um array?


type 'Bool' has no subscript members

Question: i'm new to Swift and following Appcoda book to study IOS programming, here is my code:
-In restaurantDetailViewController class:
class RestaurantDetailViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
@IBOutlet var restaurantImageView:UIImageView!
@IBOutlet var restaurantNameLabel:UILabel!
@IBOutlet var restaurantTypeLabel:UILabel!
@IBOutlet var restaurantLocationLabel:UILabel!

var restaurantImage = ""
var restaurantName = ""
var restaurantType = ""
var restaurantLocation = ""
var isVisited:Bool?

 func tableView(tableView:UITableView,numberOfRowsInSection section:Int)->Int{
    return 4
}
func tableView(tableView:UITableView,cellForRowAtIndexPath indexPath:NSIndexPath) -> UITableViewCell{
    let cellIndentifier = "Cell"
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as!RestaurantDetailViewCell
    switch indexPath.row{
    case 0:
        cell.filedLabel.text = "Name"
        cell.valueLabel.text = restaurantName
    case 1:
        cell.filedLabel.text = "Type"
        cell.valueLabel.text = restaurantType
    case 2:
        cell.filedLabel.text = "Location"
        cell.valueLabel.text = restaurantLocation
    case 3:
        cell.filedLabel.text = "Been here?"
        cell.valueLabel.text = isVisited[indexPath.row] ? "Yes, I have been here" : "No"//I got the error right here

    default:
        cell.filedLabel = nil
        cell.valueLabel = nil

    }
    return cell
}
override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    restaurantImageView.image = UIImage(named: restaurantImage)
    //restaurantNameLabel.text = restaurantName
    //restaurantTypeLabel.text = restaurantType
    //restaurantLocationLabel.text = restaurantLocation
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
}
*/

}
I have searched on many topic about my problem however i haven't got any clue, i would very appreciate if you guys could help me. This is the first time i post my question to stackoverflow so if there is anything wrong with my topic and the way i ask the question i hope you guys can remind me gently.
Thanks you very much.
Comment: PS: Declaring `isVisited` as optional is nonsensical. Is there anything else as `yes` or `no`?
Comment: Just delete `[indexPath.row]` -> `isVisited ? "Yes, I have been here" : "No"`
Comment: I think something seriously wrong with you _model_, because seemingly you just don't have a _model_ at all.
Comment: If i don't declare isVisited as optional Xcode will inform me that i got :"class RestaurantDetailViewController has no initializer".
Answer: iSVisited is declared as an optional boolean
var isVisited:Bool?

Updated your case3 as follows:-
cell.valueLabel.text = isVisited ? "Yes, I have been here" : "No"

Comment: I did as your instruction but i got the error of : "Optional type '()' cannot be used as boolean, test for '!=nil' instead" .
How can i solve this?
Comment: Oh, i have found the solution by setting false as default value to isVisited and the apps works correctly.

type 'Bool' has no subscript members


Python - Unicode file IO

Question: I have a one line txt file with a bunch of unicode characters with no spaces
example

Ⓜ

And I want to output a txt file with one character on each line
When I try to do this I think end up splitting the unicode charachters, how can I go about this?
Comment: Can you include the code you've tried so far?
Answer: There is no such thing as a text file with a bunch of unicode characters, it only makes sense to speak about a "unicode object" once the file has been read and decoded into Python objects.  The data in the text file is encoded, one way or another.
So, the problem is about reading the file in the correct way in order to decode the characters to unicode objects correctly.
import io
enc_source = enc_target = 'utf-8'
with io.open('my_file.txt', encoding=enc_source) as f:
    the_line = f.read().strip()
with io.open('output.txt', mode='w', encoding=enc_target) as f:
    f.writelines([c + '\n' for c in the_line])

Above I am assuming the target and source file encodings are both utf-8.  This is not necessarily the case, and you should know what the source file is encoded with.  You get to choose enc_target, but somebody has to tell you enc_source (the file itself can't tell you).
Comment: I will just add that `io.open` is the better way for cross-compat, and `codecs` is legacy.  There are some technical differences, you can google it if interested.
Comment: just out of curiosity, is there any advantage/difference to your approach over `codecs.open()`? Or is `codecs` a Python 2 thing?
Answer: This works in Python 3.5
line = ""
with open("file.txt", "w", encoding="utf8") as f:
    f.write("\n".join(line))

Python - Unicode file IO


Trouble playing C# on A string with 4th finger

Question: I'm trying to teach my 11 year old son a bit of bass guitar. My main instrument is double bass and my efforts on bass guitar are entirely self-taught.
We've hit a roadblock: he cannot get a clear tone from C# played with his fourth finger on the A string in first position. (We've not tried G# on the E string yet.) It's a short-scale bass and it seems fine when I play it. He has average sized hands for an 11 year old.
I've been telling him to press with the hard tips of his fingers, not the fleshy bit, with his first finger just behind the second fret, the third finger just behind the third fret, and the third and forth fingers together just behind the fourth fret. I've told him to keep his knuckles slightly bent and he has great difficulty with this - his fourth finger knuckle in particularly wants to bend the wrong way. He also keeps scrunching his four fingers up together rather than keeping them spread out behind their respective frets. He's also tending to push the string sideways rather than straight down onto the fingerboard.
It's got to the stage where he seems to have decided it is too difficult and is giving up.
Firstly, am I giving him good advice? I realise I've adapted my technique from the double bass. Secondly, what can I do to help him not give up?
I'm sure the effort to crack this problem will be well worth it, but I need to convince him of that. I don't want him to end up with a terrible technique that will soon start holding him back. (I did consider suggesting he shift position to play the C# with his second finger, but dismissed that because he'll have no dexterity with a technique like that.)
Answer: I have zero experience at teaching, also at being a father, but are you sure it's the fact he's not quite got it yet that's making him want to give up… or that you're standing over him making him do it your way, rather than just letting him get on with it & finagling his technique when he's stronger?
I didn't start playing bass until I was 13 [this is 50 years ago;) & was 6ft tall & strong for my age. I'm still pretty sure I didn't have a great technique at that point. I'd been playing piano 5 or 6 years so already had some finger strength & dexterity.
The band I was in at the time had a 'rock n' roll/blues' medley we did that was about 7 minutes long. That's how I learned to better hold the 4th fret… eventually. Seven minutes of E, G♯, B, C♯, D & back, then transpose up a 4th & 5th as appropriate gave me lots of practise.
I had no-one teaching me - in fact my father wanted to buy me a pair of running shoes rather than a bass & amp, as he said I'd be interested in it for longer;)
Maybe a lighter string gauge & just leave him to it for a while.
Comment: You're completely right about a light touch and letting him get on with it, but I've been doing that and he's not really got anywhere on his own. I want to motivate him by helping him learn a very simple song that he can then play in a band. My question was really to confirm whether or not the technique I'm trying to help him achieve is correct for bass guitar, or whether there is a better way.
Comment: Even being a career bassist, after having taught a lot of beginners and kids in particular I tend to agree with your basic (I'm paraphrasing)  "just get it done however you can for now" approach. People who can already do the things that the OP talks about like curving and spreading the fingers  don't understand how difficult that can be to someone just starting out. You probably will be getting a visit from the enharmonic police for: "E, A♭, B, D♭, D" pretty soon though.
Comment: @JohnBelzaguy - that probably serves me right for trying to outguess myself. All sharps? I'll fix it ;))
Comment: I wish I could accept two answers. I'm going to fret less (pun intended) about technique, and just try to get him playing stuff and enjoying it.
Answer: The first question I would ask is: Is the bass set up well? You must take into account someone with not a lot of hand strength who is just starting and not yourself who has years of experience holding down strings on an upright with higher action. The nut height, action and neck relief can all impact whether an instrument is easy to play or not, especially for a beginner. Too much neck relief will cause an instrument to be hard to play starting around the 4th or 5th frets and get progressively worse as you go higher.
Moving on from there, there's nothing wrong with using basic 3 finger upright technique on electric. I would even say it's necessary in some cases because most people can't comfortably spread 4 fingers across 4 frets on a bass, especially in the low register.
That being said, you understand the importance of good technique and hand position. An 11 year old does not, at least not on the same level. He also is not able to do things with his hands and fingers that are second nature and seemingly very easy to you. If while teaching him you spend a lot of time trying to get him to curve his pinky and spread and put all his fingers on a string he will get bored and discouraged. If you get him playing bass lines, even if it is with less than perfect fingering and technique he will enjoy it more. Focus more on playing music than technique. As his motor memory improves and his hands and fingers get stronger he should be more able and receptive to improving his technique and fingering.
Answer: Why on Earth should anyone keep the other fingers over the lower frets when playing with the pinky? It's a pointless exercise. Slide the whole hand up, and if he can't play a clean note on fret 4 with pinky, then use pinky and ring. I often find myself (small hands, standard 5 string bass) using mainly index and pinky, and sliding along as necessary.
That apart, why does the C♯ if the C♯ has to be played there, one plays the A on bottom string, 5th fret, middle finger, and that C♯ with index, leaving a smaller stretch for perhaps the E on A string, 7th fret.
Comment: @IanGoldby - also consider encouraging him to hold the bass with the head high - so the attitude is more string bass-like. It alleviates a lot of the difficult angles involved when having the bass horizontal.
Comment: "That apart, why does the C♯ have to be played there, when there's a substitute a fret lower on the next string?" This doesn't make sense to me, the only places to play that C# on a four string bass are the A String 4th fret or the E string 9th fret.
Comment: Well, I personally find the other fingers help take some of the pressure off my 4th finger, as well as being already in position for playing B and C. But as I said my technique comes from double bass where this is standard technique. The reason for playing C# at the 4th fret on the A string is so he doesn't have to move his whole hand. Is that wrong on bass guitar?
Comment: I mostly agree with this answer, but "why does the C♯ have to be played there"- because it sounds great, it's conveniently placed, and the inability to play that note is a major handicap to a bass player.  Also, there isn't a C# a fret lower on the next string.  Is the substitute a different note?
Comment: @JohnBelzaguy - my fault. I was thinking of A on the bottom string! Will edit accordingly.
Comment: I did wonder about teaching him to play in in third or forth position (double bass terminology, sorry) with the C# on the E string, rather than 1st position, to make the wrist position easier. But he's not so much struggling with that, and you lose the benefit of open strings to fill in the gaps between notes reachable 'in position' and there's no choice but to shift position every few notes. Perhaps my notion that shifts are really difficult for a beginner is another thing that comes from double bass though and doesn't apply so much to bass guitar...!


Modificar o Paginate no Laravel 5.8

Question: Boa noite pessoal!
Eu estou desenvolvendo uma ferramenta utilizando o Laravel. Talvez eu ainda tenha que estudar mais para poder alcançar um nível de conhecimento para poder discutir melhor sobre isso, pois eu não sou desenvolvedor, mas graças a Deus eu tenho aprendido tudo o que estou precisando para conseguir fazer o que eu preciso.
A minha dúvida é:
- Como eu consigo alterar a quantidade de páginas exibidas em uma tabela? Atualmente minhas páginas exibem tabelas com o padrão de 10 itens. Eu gostaria de alterar esse padrão, mudar de 10 itens para 30 para facilitar a experiência do usuário.
Para ajudar a esclarecer minha dúvida, segue a imagem abaixo

Sei que o tempo de cada um é precioso, se puderem talvez me indicarem alguns links ou dar uma dica de como poderei seguir... Eu agradeço imensamente! Obrigado!
Comment: seja bem vindo! tenta seguir esses passos para sua pergunta ser mais clara para todos aqui. leia com atenção https://pt.meta.stackoverflow.com/questions/5483/manual-de-como-n%c3%83o-fazer-perguntas?cb=1 espero que a resposta que coloquei abaixo ajude.
Answer: Para alterar a quantidade a ser exibida crie uma variável em seu controller
protected $totalPaginas = 30;

então um exemplo poderia ser sua pagina index, que eu suponho que poderia trazer todas os resultados do retorno consultado.
public function index()
    {
        $varParaEnviarParaView = $this->minhaModelFiltrada->paginate($this->totalPaginas);
        return view('caminho.para.minha.view', compact("varParaEnviarParaView"));
    }

o método paginate retorna a quantidade de páginas.
por último em sua view acrescente ao final da página, fora do foreach
{{$varParaEnviarParaView->links()}}

acredito que resolva a questão.
Comment: André! Não sei como te agradecer... Obrigado pela orientação em me enviar o link de boas práticas com as perguntas, sou novo aqui e peço desculpas se cometi algum erro. Mas você entendeu a minha dúvida, inclusive me passou tudo de "mão beijada" e deu certo por aqui. Poxa, obrigado mesmo! Sucesso, que Deus abençoe.
Comment: que bom que deu certo! ;)

Modificar o Paginate no Laravel 5.8


Called Function's Return Value Undefined in Calling Function

Question: I did quite a bit of searching and got the feeling my question is answered, but I had trouble integrating available answers with my particular situation. This is my first-ever Javascript, and I apologize for almost certainly repeating a beginner-question that's probably been adequately answered for very similar contexts. Basically, I don't get why fishDirector's var queryDir is always holding an undefined value after fishTitle is called.
function fishDirector() {

var dir = "";
var req = new XMLHttpRequest();

var URL = "https://netflixroulette.net/api/api.php?";
var queryTypeDir "director=";
var queryDir = fishTitle();
console.log(queryDir);
console.log(dir);

req.open('GET', URL + queryTypeDir + queryDir, true);
req.addEventListener("load", function() {
    var response = JSON.parse(req.responseText);

req.send(null);
});
}

Above I naively tried to define var dir in the calling function to be updated by the called function, fishTitle:
function fishTitle() {

var req = new XMLHttpRequest();

var URL = "https://netflixroulette.net/api/api.php?";
var queryType = "title=";
var query = document.getElementById('form_search').value;

req.open('GET', URL + queryType + query, true);
req.addEventListener("load", function() {
    var response = JSON.parse(req.responseText);

    dir = dir + response.director;
    console.log(dir);
    return dir;
});
req.send(null);
return dir;
}

The dumbly-located return statements were an unguided effort to have the anonymous function let it's calling function know what dir is, and have that returned to fishDirector, which called fishTitle. I get the impression the value of dir is lost once the anonymous function terminates, but if so, how do I get it out of there?
Dumbdumbdumb. Sue me.
Comment: `XMLHttpRequest` is set to `true` for asynchronous flag. `dir` is returned at `return dir` before `load` event. Also missing `=` at `var queryTypeDir "director=";`
Answer: It's because it's an asynchronous ajax request. Tḧat means that you request is put in a different thread and your main thread continues to execute.
So you do var queryDir = fishTitle(); and it runs all the way to the end, starting another thread of execution and returning undefined.
LATER, when this other thread gets processed, it may set the dir value, but the main flux of execution has already finished.
Read guest271314 answer to see one of the ways of dealing with it. Educate yourself about ajax and asynchronous programming to improve this understanding.
Comment: Thanks to you both! I tried to race into javascript and blew right past all requisite knowledge of asynchronous requests - and didn't even know enough to know that's what I didn't know.
Comment: NP. If you find any answer usefull please accept/upvote. Thanks.


Group KFold for regression problems: When is it helpful?

Question: I am working in manufacturing related industry. I am tasked with building some models to predict some physical quantities (for example, size of a hole in the structure) from spectra. The data usually comes in groups, for example my customer would 10 of their products and let us collect data on these products. Since the manufacturing conditions varies from products to products, there's a natural grouping in my data.
Now my question is, when I do cross validation, should I do the train-validation split by groups or not? From sklearn documentation (http://scikit-learn.org/stable/modules/cross_validation.html#cross-validation-iterators-for-grouped-data), at first glance it seems to suggest I should since model made from a particular set of products should generalize to other products:

The i.i.d. assumption is broken if the underlying generative process yield groups of dependent samples.
Such a grouping of data is domain specific. An example would be when there is medical data collected from multiple patients, with multiple samples taken from each patient. And such data is likely to be dependent on the individual group. In our example, the patient id for each sample will be its group identifier.
In this case we would like to know if a model trained on a particular set of groups generalizes well to the unseen groups. To measure this, we need to ensure that all the samples in the validation fold come from groups that are not represented at all in the paired training fold.

However, when I think about it, splitting by group seems unnecessary. There is no hidden variable per se that would affect the spectra collected from different groups. In principle, the spectra are only determined by the structure on a product-this seems to be different from the example in the documentation, where supposedly the hidden variable is the patient itself (different individual can be more prone to some disease, or benefits more to some treatments). In fact, blind test on additional data seems to suggest that splitting by groups overestimate the cross validated MSE against splitting without groups.
Answer: The domain specific qualification is everything here. On the one hand, you suggest that manufacturing conditions varies from products to products, but on the other hand the spectra are only determined by the structure on a product. Only you (or another domain expert) will know which one wins out here.
I've used group kfold when I don't want observations from the same group to be in train and test sets, because the algorithm might overfit. Not sure if this applies for you.
Answer:
the spectra are only determined by the structure on a product

Can you guarantee that production settings do have no whatsoever influence on structure? If so, you can neglect the groups. If production settings can possibly influence structure, you need to split by groups.

In fact, blind test on additional data seems to suggest that splitting by groups overestimate the cross validated MSE against splitting without groups.

In other words, if you split by groups, you see higher MSE?
=> this is clear indication that you should split by groups. In other words, not splitting by groups will get you an overoptimistic error estimate.
Comment: I have 30+ groups and I left about 10 as blind test, not sure if this is what you meant by splitting groupwise. The blind test data does not contain any data from the groups that are in the training set.
Comment: In my case, splitting by group give me an overpessimistic error estimate. I reserved a subset of data for blind test (i.e. not seen at all by the training process). I ran the CV process with Group-KFold and KFold to obtain 2 different models. The Group-KFold model underfit (MSE on blind test is larger than the KFold model), while both models have no overfitting issue (Training MSE is about the same as blind test MSE).
Comment: @lizardfireman: was that blind test set set aside *splitting groupwise*?


How to call a block inside a view page?

Question: I am working with Drupal 8. I have a view page and added a twig for that.
I want to call a block inside my view page. How can I do that?
Answer: Here is some possible ways to do it:
1. using no extra modules
Click ADD next to header or footer area and look for GLOBAL: Rendered entity - Block.  The configuration asks for view mode and block id

2.  using  Views block area module
You can use Views block area module that will allow you to insert a block as a field or in header or footer area.
3.  using preprocess / twig
if you want to add the block using your twig template in your THEMENAME.theme file using a preprocess function
function THEMENAME_preprocess_XXX (&$variables) {
    $block = \Drupal\block\Entity\Block::load('id_block');
    $variables['myBlock'] = \Drupal::entityTypeManager()
        ->getViewBuilder('block')
        ->view($block);
}

and then inside your twig file use this
{{ myBlock }}

To find appropriate preprocess function look in your twig file comments.
For example if you want to use views-view--unformatted.html.twig you can see in the comments
* @see template_preprocess_views_view_unformatted()

which means include in your .theme file THEMENAME_preprocess_views_view_unformatted() function
Answer: You can use module Twig Tweak this module you can render view,block ...
You can see document here
Render views
{{ drupal_view('who_s_new', 'block_1') }}

Render blocks
{{ drupal_block(plugin_id) }}

How to call a block inside a view page?


Hadoop Load and Store

Question: When I am trying to run a Pig script which has two "store" to the same file this way
store Alert_Message_Count into 'out';
store Warning_Message_Count into 'out';

It hangs, I mean it does not proceed after showing 50% done.
Is this wrong? Cant we store both the results in the same file(folder)?
Answer: HDFS does not have append mode. So in most cases where you are running map-reduce programs, the output file is opened once, data is written and then closed. Assuming this approach you can not write data simultaneously onto the same file.
Try writing to separate files and check if the map-red programs do not hang. If they still do, then there are some other issues.
You can obtain the result and map-reduce logs to analyze what went wrong.
[Edit:]
You can not write to the same file or append to an existing file. The HDFS Append feature is a work in progress.
To work on this you can do two things:
1) If you have the same schema content in both Alert_Message_Count and Warning_Message_Count, you could use union as suggested by Chris.
2) Do post processing when the schema is not the same. That is write a map reduce program to merge the two separate outputs into one.
Comment: When I write to different files, it does it without any problem.
What can be done so as to append/write multiple results to a single file?
Comment: @Nikhil Desai: See edited answer and also Chris's answer. You can not use append but there are solutions based on existing constraint.
Comment: Thanks. For now, Union should help me. Anyway I will look into the second option too.
Answer: Normally Hadoop MapReduce won't allow you to save job output to a folder that already exists, so i would guess that this isn't possible either (seeing as Pig translates the commands into a series of M/R steps) - but i would expect some form of error message rather than it just to hang.
If you open the cluster job tracker, and look at the logs for the task, does the log yield anything of note which can help diagnose this further?
Might also be worth checking with the pig mailing lists (if you haven't already)
If you want to append one dataset to another, use the union keyword:
grunt> All_Count = UNION Alert_Message_Count, Warning_Message_Count;
grunt> store All_Count into 'out';

Comment: Yes it now throws an exception, but after a long time.As you said it does not allow writing to a output file which already exists. When I use two separate files, it works fine.
In that case what is the way to append/write the results to a single file?
Comment: Do the two outputs have the same 'schema'? If so look at the union keyword - http://ofps.oreilly.com/titles/9781449302641/advanced_pig_latin.html
Comment: Thanks Chris. Yes they have the same schema.UNION can be worked out for these.
Comment: Would it be a good practice to use load the output files so generated and then extract information from that?
I mean I am using something like this
A = load 'Number_By_Time/part-r-00000' using PigStorage(' ');
B = group A by $2;
C = foreach B generate group, COUNT($1);
I was just thinking whether Number_By_Time/part-r-00000 would cause any issues later on? Right now I have no issues, but would it be advisable to use something like this?
Comment: Not sure i understand your question
Comment: I am writing a pig script and in that I store some result into a file. Then I load once again the same output file and do the further processing, like this
Alert_Message_Day_Order = foreach Alert_Message_Day generate group,COUNT($1);
store Alert_Message_Time_Order into 'Number_By_Time';
store Alert_Message_Day_Order into 'Number_By_Day';
A = load 'Number_By_Time/part-r-00000' using PigStorage(' ');

I have continued in the next comment...
Comment: I wanted to know if this is fine? I mean using the output file so generated, i.e. here when I do  "store Alert_Message_Time_Order into 'Number_By_Time';" I get an output folder with a file in it named "Number_By_Time/part-r-00000". Then I LOAD this file and do the further processing.
i.e. "A = load 'Number_By_Time/part-r-00000' using PigStorage(' ');"
So, I wanted to know if this can be done? It works fine, but just wanted to know if this can be done.
Comment: Sure, if you want to store off intermediate results then this is perfectly acceptable, also means you are able to continue processing from a 'checkpoint'
Comment: Yes, its not just storing but also immediately using the stored results for further LOADING.

Hadoop Load and Store


Como obter valor dos checkbox selecionados

Question: Estou desenvolvendo um site que tem um filtro de busca por bairros, onde a pessoa seleciona em checkbox os bairros. Aí preciso pegar o valores que estão checados e jogar em um texto (ex: Bairros selecionados: Brooklin, Campo Belo)
Os checkbox estão assim (é uma lista com dezenas de bairros):

<input type="checkbox" value="43" name="bairro[]" id="bairro0">  Aclimação

<input type="checkbox" value="2" name="bairro[]" id="bairro1">  Alto da Boa Vista

<input type="checkbox" value="48" name="bairro[]" id="bairro2">  Alto da Lapa

Se possível pegar já o nome do bairro, caso não dê posso pegar só o valor do checkbox e fazer uma consulta usando mysql e php para trazer o nome.
Quando a pessoa aplica o filtro e dá OK, a página já carrega com os campos selecionados.
Obrigado!
Answer: Troque o name do seus inputs para:
name="bairro"

E tente isso:
$(function () {
    $('.span3').click(function () {
        var checkValues = $('input[name=bairro]:checked').map(function() {
            return $(this).parent().text();
        }).get();
        //do something with your checkValues array
    });
});

Answer:

var els = document.querySelectorAll("input[type='checkbox'");
var selecionados = '';
for (var i = 0; i < els.length; i++) {
  if (els[i].checked) {
    selecionados += els[i].nextSibling.nodeValue + ',';
    document.getElementById("sel").innerHTML = selecionados.substring(0, selecionados.length - 1);;
  }

  els[i].addEventListener("click", function() {
    if (this.checked)
      selecionados += this.nextSibling.nodeValue + ',';
    document.getElementById("sel").innerHTML = selecionados.substring(0, selecionados.length - 1);
  });
}

  <input type="checkbox" value="43" name="bairro[]" id="bairro0">  Aclimação</input>

  <input type="checkbox" value="2" name="bairro[]" id="bairro1">  Alto da Boa Vista</input>

  <input type="checkbox" value="48" name="bairro[]" id="bairro2" checked>  Alto da Lapa</input>

Selecionados:

Comment: PERFEITO!!! Obrigado
Comment: Quase isso, a única modificação, como faço para ele logo no começo já trazer só quem está selecionado? por exemplo alto da lapa já estar checked e ele trazer o valor Alto da lapa
Answer: Veja desta forma, gerando um link para pesquisa com $_GET

$(document).ready(function(){
  $("#test").click(function(){
  var testval = [];
     $('.span3:checked').each(function() {
       testval.push($(this).val());
     });
    document.getElementById("bairro").text = "http://teste.com/?bairro="+testval;
 });

});

<input class="span3" type="checkbox" value="43" name="bairro[]" id="bairro0">  Aclimação

<input class="span3" type="checkbox" value="2" name="bairro[]" id="bairro1">  Alto da Boa Vista

<input class="span3" type="checkbox" value="48" name="bairro[]" id="bairro2">  Alto da Lapa

Test

Desta forma irá listar todos os itens selecionados e colocar como uma parâmetro na URL.


Sortear letras de forma aleatória

Question: Sei gerar números, mas letras como faço para gerar tipo AB BC AEEE, por exemplo.
import random

import string

for j in range(40,100):

print(random.choice(string.ascii_uppercase))

Neste código gero uma letra minúscula. Preciso 4 letras por turma número de turmas esta entre 40 a 100
Comment: Já pensou em chamar a função `random.choice` 4 vezes?
Comment: deu certo porem elas nao estao em linha reta como faco para colocalos em linha reta posso usar print end mas como ?
Answer: O que você precisa fazer é basicamente chamar a função random.choice o número de vezes que você quer sortear uma letra. Como você precisa 4 letras: 4 vezes.
import random
import string

letras = string.ascii_uppercase

for turma in range(40, 100):
    codigo = ''.join(random.choice(letras) for _ in range(4))
    print('Turma', turma, 'possui o código', codigo)

Porém, isso não garante que os códigos serão únicos, podendo duas ou mais turmas possuírem o mesmo código.
Comment: deu certo obrigado
Comment: Complementando o que o Anderson disse, para que os números não se repitam é preciso armazenar as letras em alguma estrutura, como uma lista, para que seu for cheque se existe a ocorrência da determinada letra dentro da lista. Dessa forma elimina-se a duplicidade de letras sorteadas.

Sortear letras de forma aleatória


how to catch up exception when user click links in textview?

Question: use a TextView to show email, and set

TextView tvEmail = (TextView)this.findViewById(R.id.tvEmail);
Linkify.addLinks(tvEmail, Linkify.EMAIL_ADDRESSES);

click on above mail address will raise an exception, because mail client didn't found. how to catch up this exception?
Comment: which exception is there on textview click?
Comment: @PareshMayani ActivityNotFound, No Activity found to handle Intent {act=android.intent.action.View dat=mailto:xxx }
Answer: I have already had the same issue, and I solved it by creating a new class that checks for null before actually launching the Intent.
All you have to do is to replace all URLSpan spans, before setting the TextView's text (which means you cannot use setAutoLinkMask()).
This has to be done, because URLSpan's onClick() method does not perform any kind of null checks.
How to preceed:
TextView txt = ...
txt.setLinksClickable(true);
txt.setText(SafeURLSpan.parseSafeHtml(<<YOUR STRING GOES HERE>>));
txt.setMovementMethod(LinkMovementMethod.getInstance());

Kinds of strings that could be used in <<YOUR STRING GOES HERE>>:
"Click here: My links"
"Mail me: My email"
... and so on...

Here is the source for SafeURLSPan class (I use it in my app FPlay, and it has been tested on Android 10+):
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.provider.Browser;
import android.text.Html;
import android.text.Spannable;
import android.text.style.URLSpan;
import android.view.View;

public final class SafeURLSpan extends URLSpan {
    public SafeURLSpan(String url) {
        super(url);
    }

    @Override
    public void onClick(View widget) {
        try {
            final Uri uri = Uri.parse(getURL());
            final Context context = widget.getContext();
            final Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            if (context != null && intent != null) {
                intent.putExtra(Browser.EXTRA_APPLICATION_ID, context.getPackageName());
                context.startActivity(intent);
            }
        } catch (Throwable ex) {
        }
    }

    public static CharSequence parseSafeHtml(CharSequence html) {
        return replaceURLSpans(Html.fromHtml(html.toString()));
    }

    public static CharSequence replaceURLSpans(CharSequence text) {
        if (text instanceof Spannable) {
            final Spannable s = (Spannable)text;
            final URLSpan[] spans = s.getSpans(0, s.length(), URLSpan.class);
            if (spans != null && spans.length > 0) {
                for (int i = spans.length - 1; i >= 0; i--) {
                    final URLSpan span = spans[i];
                    final int start = s.getSpanStart(span);
                    final int end = s.getSpanEnd(span);
                    final int flags = s.getSpanFlags(span);
                    s.removeSpan(span);
                    s.setSpan(new SafeURLSpan(span.getURL()), start, end, flags);
                }
            }
        }
        return text;
    }
}


XGBoost - Removing Important Parameter, Improved score?

Question: This is a generic question about xgboost. I ran the following code to see the important features of my data
imp <- xgb.importance(names(train),model = gbdt)
xgb.ggplot.importance(imp)

Weirdly, when I remove one of the most important features, my model improves (aka my ability to predict test data on Kaggle improves). Why would this be? How can you determine which features to leave in the data, and which to remove? Thanks
Comment: How are you measuring performance? Have you accounted for the standard error of the performance estimates? Is this related to the nature of your trian/test partition? Is there a non-deterministic component to your estimation procedure (such as row- or column-subsampling)?
Answer: This will happen if the most important feature is highly correlated with some other features.   It seems violate the tree based model features selection rules-it should immune to collinearity, but the colsample_bytree (colsample_bytree is a parameter in xgboost) is random select features, so it will select them both, but if you remove the redundant one, the result's changes is insignificant.
colsample_bytree: subsample ratio of columns when constructing each tree. Default: 1


Flutter: Transferring items from one list into a different list

Question: i have one List (growable) with an item (actually item 0:
items is of class Team

items[_id = 1, _team = "Team01", _note = "blabla"]

and I want to transfer it into another list with a different structure:
participants is of class User
participants[id = 1, name = "participant1"]

skipping the note and translating _id into id and so on.So at last the result would give me
participants[id = 1, name = "team01"]

(sorry for the writing, I describe it out of the debugger)
i tried something like this, but doesnt work with value:
List<TestTeam> participants;
for (var value in items) {
  participants.add(new TestTeam(value.id, value.team));
}

my class Team is defined like this:
class Team {
  int _id;
  String _team;
  String _note;

  Team(this._team, this._note);

  Team.map(dynamic obj) {
    this._id = obj['id'];
    this._team = obj['team'];
    this._note = obj['note'];
  }

  int get id => _id;
  String get team => _team;
  String get note => _note;

  Map<String, dynamic> toMap() {
    var map = new Map<String, dynamic>();
    if (_id != null) {
      map['id'] = _id;
    }
    map['team'] = _team;
    map['note'] = _note;

    return map;
  }

  Team.fromMap(Map<String, dynamic> map) {
    this._id = map['id'];
    this._team = map['team'];
    this._note = map['note'];
  }
}

Comment: Can you explain me what you want by Drawing or other way
Comment: i want to transfer from one list to another, while both are type of different classes
Answer: You should implement below way
void main() {
  List<Team> teams=[];
    List<User> participants=[];

  for (var i = 0; i < 4; i++) {
    teams.add(Team(i,'Team_$i','Note_$i'));
  }
  for (var value in teams){
    participants.add(User(value.id,value.team));
  }

    for (var value in teams){
    print(value.toString());
  }
     for (var value in participants){
    print(value.toString());
  }

}

 class Team{
   int id;
   String team;
   String note;

   Team(this.id,this.team,this.note);

   toString()=> 'Team Map :{id:$id,team:$team,note:$note}';
 }

class User{
   int id;
   String team;

   User(this.id,this.team);
   toString()=> 'User Map :{id:$id,team:$team}';
 }

Output
Team Map :{id:0,team:Team_0,note:Note_0}
Team Map :{id:1,team:Team_1,note:Note_1}
Team Map :{id:2,team:Team_2,note:Note_2}
Team Map :{id:3,team:Team_3,note:Note_3}
User Map :{id:0,team:Team_0}
User Map :{id:1,team:Team_1}
User Map :{id:2,team:Team_2}
User Map :{id:3,team:Team_3}

Comment: When i do this, then i got a fault on this line `participants.add(TestTeam(value.id, value.team));` Too many positional arguments, 0 expected
Comment: Where class of `TestTeam`


File reading using main thread and process data using multithreading and ExecutorService

Question: I have a requirement to read bulk data file and process the data (like data validation, tracking validation failures and insert into data base etc..) using multithreading.  I wanted to use main thread to reading data from file and process the data using an ExecutorService.

Is this the correact approach? if yes, how can I do this?
Also, I need to tract every record output once validation and insetion done against to database.  How can I do track output of every record?  Can put it one common variable and increasing the count of failure record data?
Also I need to track how many records are failed sequentially?

Thanks.
Comment: Your bottleneck is likely to be the database so I would batch the data first as this is more likely to improve performance (and be relatively simple) For multi-threading examples, I would do a quick search on google. ;)
Answer: I would suggest to split the file into virtual segment and allow your executors to pick and process these segments. Reading the file in the main thread would end up creating bottleneck. Allow each thread to read its segment separately and parallelly. Refer to the following post How to implement Concurrent read to a file mapped to memory in Java?
Answer: Yes it is correct, but you will have an improvement if processing takes significant time (comparing to reading file), processing of pieces are independent and you have multiple cores.
Read your data to any container (if it fits in RAM) and use any ExecService tutorials like this: http://tutorials.jenkov.com/java-util-concurrent/executorservice.html
Answer: Your idea is correct IMO, i would do something like:
while ((line = filereader.readLine()) != null) {
    Mycallable mycallable = new Mycallable(line);
    executor.submit(mycallable);
            }


Why Drupal won't remember "use search" permission settings for roles?

Question: I want to make search available to everyone who uses the site, including anonymous users.
Now, if i go to /admin/people/permissions and and try to enable "use search" for anonymous and authenticated users, the systems seems to act okay, but when I look at it again, nothing's changed. The settings seemingly won't remember my settings.
Any ideas? I hope that there's something totally simple I forgot
EDIT: in fact, it does not keep any changes in the permission system.
EDIT 2: I made it work by editing permissions through /admin/people/permissions/roles. Does anyone has any ideas why it was possible in one way but not the other?
Comment: Sounds like a bug; did you try on a clean install?
Comment: no, I've done a fair number of them, and that's the first time I have this problem. That's exactly what makes me wonder.
Answer: PHP has a default setting of 1000 for max_input_vars, and once you have a significant number of modules and/or roles defined, you end up with an excess number of permissions boxes on the page.
In your php.ini file add max_input_vars = 1500 and keep incrementally increasing it until it saves.
Comment: ...and, re: edit 2, with only one role shown, you are under this limit.


Codeigniter row() on a non-object

Question: I have problem with ION Auth library. I want to edit existing group and when i try to dedit i have this error:
Where is mistake, i explore all and CI doc but all looks fine.

Fatal error: Call to a member function row() on a non-object in
  /var/www/ci_balcanrent/beta/modules/user/controllers/user.php on line
  603

Here is controller for edit function:
   //edit a group
    function edit_group($id) {
        // bail if no group id given
        if (!$id || empty($id)) {
            redirect('user', 'refresh');
        }

        $this->data['title'] = $this->lang->line('edit_group_title');

        if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin()) {
            redirect('user', 'refresh');
        }

        $group = $this->ion_auth->group($id)->row();

        //validate form input
        $this->form_validation->set_rules('group_name', $this->lang->line('edit_group_validation_name_label'), 'required|alpha_dash|xss_clean');
        $this->form_validation->set_rules('group_description', $this->lang->line('edit_group_validation_desc_label'), 'xss_clean');

        if (isset($_POST) && !empty($_POST)) {
            if ($this->form_validation->run() === TRUE) {
                $group_update = $this->ion_auth->update_group($id, $_POST['group_name'], $_POST['group_description']);

                if ($group_update) {
                    $this->session->set_flashdata('success', $this->lang->line('edit_group_saved'));
                } else {
                    $this->session->set_flashdata('error', $this->ion_auth->errors());
                }
                redirect("user", 'refresh');
            }
        }

        //set the flash data error message if there is one
        $this->data['message'] = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('error')));

        //pass the user to the view
        $this->data['group'] = $group;

        $this->data['group_name'] = array(
            'name' => 'group_name',
            'id' => 'group_name',
            'type' => 'text',
            'value' => $this->form_validation->set_value('group_name', $group->name),
        );
        $this->data['group_description'] = array(
            'name' => 'group_description',
            'id' => 'group_description',
            'type' => 'text',
            'value' => $this->form_validation->set_value('group_description', $group->description),
        );

        $this->template->build('auth/edit_group', $this->data);
    }

603 Line $group = $this->ion_auth->group($id)->row();
Model :
/**
     * group
     *
     * @return object
     * @author Ben Edmunds
     **/
    public function group($id = NULL)
    {
        $this->trigger_events('group');

        if (isset($id))
        {
            $this->db->where($this->tables['groups'].'.id', $id);
        }

        $this->limit(1);

        return $this->groups();
    }

View:
<?php echo form_open(current_url());?>

            <?php echo lang('create_group_name_label', 'group_name');?>

            <?php echo form_input($group_name);?>

            <?php echo lang('edit_group_desc_label', 'description');?>

            <?php echo form_input($group_description);?>

<?php echo form_submit('submit', lang('edit_group_submit_btn'));?>

<?php echo form_close();?>

Comment: `$this->ion_auth->group($id)->row();` Here which class method is `row()`?
Comment: http://ellislab.com/codeigniter/user-guide/database/results.html
Answer: $group = $this->ion_auth->group($id)->row();

Problem :
$this->ion_auth->group($id) returns group class object. So you can not call Datbase row() method from group class.
Comment: I know that i post this answere how can i fix that.
Comment: @Jony You post "Where is mistake, i explore all and CI doc but all looks fine". That is why I marked that.
Comment: Okay how all other people dont have problem with this error only me. I dont edit nothing i just download that lib

Codeigniter row() on a non-object


CSS: Stopping div pushing content

Question: I'm trying to implement a CSS menu and am having a problem with the menu pushing the other content/divs down when the menu expands.
http://www.confetti.ie/index2.aspx
Can anyone tell me what CSS I need to stop the main body content being pushed when the menu expands?
Comment: I don't know what you mean. Can you describe in more detail?
Answer: The keyword is the CSS property position: absolute. It makes elements "float" over the other content. Absolutely positioned menu elements won't push the page content.
Comment: Hi thanks for the reply, I still seem to be having a few problems. I've added position:absolute; to the submenu container, it still seems to push the main body and then teh body pops back up? Also how would I get the sub-menu container to appeatr over any other images on the page?

View problem here
http://bit.ly/bAcS56

Regards
Melt
Comment: @Melt the first I don't know, there must be some other element that gets resized by your script - can't really say which one.  The keyword for the second is the `z-index` property. http://www.w3schools.com/Css/pr_pos_z-index.asp
Answer: Use position: absolute for the one you want to be over and position : relative for the one don't want to move
Answer: Use position: absolute; to throw the element (sub menu container) out of the document flow.

CSS: Stopping div pushing content


how to get all lat and lng point by zip code?

Question: my problem is that

as I image see I want all location of by zip code, not just center.
I check many ways just give me response like google reponse
but that give northeast and southwest point
but my project wants all the point of that zip code.
how do I get all the points?
Answer: This is not currently possible.
There is a very popular feature request that seems like a good fit though:
Automatic polygon generation to specified geographic boundary


Python 2.7 Etree/lxml minimizing

Question: Im using lxml/Etree to parse and write to XSD documents.
I have the basic structure
tree = ET.parse('file.xsd')
# do stuff
tree.write('output.xsd')

But tags get minimized in some instances, for example:
<Cars>
    <Car type="Chevy"></Car>
</Cars>

Get shortened to
<Cars>
    <Car type="Chevy"/>
</Cars>

Is there a way to make lxml/ETree NOT do this? I've searched around and apparently this is something good - But in my case, I want the ending tags to be left as they are.
I'm parsing the whole tree, making adjustments and saving it to another file
Answer: Use method parameter of write method. Value on parameter if html or xml
E.g.
tree.write("output.xsd", method="html")

Also have pretty print parameter which have value True or False
e.g.
tree.write("output.xsd", method="html", pretty_print=True)

Have may parameters:
write(self, file, encoding=None, method="xml",
          pretty_print=False, xml_declaration=None, with_tail=True,
          standalone=None, compression=0,
          exclusive=False, with_comments=True, inclusive_ns_prefixes=None)

Comment: So method='html' doesn't truncate empty tags? Regards
Comment: @enrm: Yes, Correct.
Comment: Very nice! Thank you for your answer

Python 2.7 Etree/lxml minimizing


Hypothesis testing with p-values from similar tests as prior

Question: I hope to work on a hypothesis testing problem to test $\beta$ against the null hypothesis ($H_{null}$) $\beta=0$, and we can consider Wald test with the test statistics
$$
W = \dfrac{\beta^2}{var(\beta)}
$$
Then, with $W$, I can get p-values, which is essentially "getting a value of the test statistic as extreme as or even more extreme than what is observed by chance alone", so
$p(t > W | H_{null})$.
However, the sample size I have to calculate $\beta$ and $var(\beta)$ is fairly small. The results, although p-values for some covariates are small, are not very convincing.
On the other hand, I have some p-values calculated for the same set of covariates, from a larger body of samples. Basically, I have a prior $p_0(t>W_0|H_{null})$. In addition, sometimes I also have $\beta_0$.
I wonder whether/how I can calibrate $p(t > W | H_{null})$ with $p_0(t>W_0|H_{null})$.
Some of my current efforts

I learned a way to do this is to simulate a large amount of data that leads to $p_0$ if we conduct the test, and then combine the simulated data and my real ones to do the hypothesis testing, but I hope there are more efficient ways to do it.
Bayesian hypothesis testing sounds relevant, but it assumes $p_0(H_{null})$ instead of $p_0(t>W_0|H_{null})$, and it leads to a MAP result. I hope we can still have a p-value at the end.
Answer: It sounds like what you are after is a meta-analysis.  This is the frequentist analog to a Bayesian analysis using an informative prior.
A meta-analysis can come in many forms.  One option is to combine the subject-level observations into a single data set and run a single model to produce p-values and confidence intervals.  This is the ideal approach.
Another option is to combine summary-level statistics or estimators into a single value and estimate its standard error.  One can then perform a hypothesis test to produce a p-value and invert a hypothesis test to construct a confidence interval.  Another option is in line with what you proposed, which is to use simulated data that mimics the observed results from a historical study and use option one.
Here is a related paper on meta-analysis and transfer learning.
Comment: Thanks. Looks like what I hoped to learn is the second option. I will read the paper and follow up.


Why is there a natural symbol on the second note?

Question: Just begining to learn to read musical scores. I don't understand why there is a natural on the second note of the 9th measure, since there is no previous sharp or flat?
I assume the natural in the 7th measure cancel the flat of the previous measure even though they are cancelled by being in a different measure etc.
Answer: It is a courtesy accidental.  This is an extra, unneeded accidental that the composer or publisher has added because they think that a mistake is likely.  Here, with many of the Es flattened, including in the immediately preceding measure, the E natural may be a surprise.  Many of the Bs are also flattened so the player might be tempted to switch into a B flat gear.
As you say, it is not needed but it is not forbidden either and it may help.  Somewhat like adding (sic) in a document where you think that the reader may otherwise assume that you have made a mistake.
Addendum
I read your question a little too quickly and concentrated on the natural in the 7th measure.  As guidot says, the one the in 9th measure is a little unusual.  Accidentals (unlike key signatures) apply only to the octave in which they are used.  This particular B has not been flattened so it is in even less in need of a courtesy natural.  I am not quite sure but I think that I have seen the occasional courtesy accidental in another octave.  If B is frequently flattened (as here), the performer might be tempted to think that the key has changed and all Bs will be flattened.  They might, like Tim, recognize the blues style but, if they don't then they may suspect that the piece has modulated to B flat.
Wikipedia
Comment: @guidot A good point.  I was actually looking at the wrong measure and I commented on one of the earlier Es.  I'll amend my answer.  I still guess that since there are some many B and E flats, there was a fear that the player may think that the piece has modulated to B flat.
Comment: While I agree with the explanation, the courtesy accidental is strange here, since on-the-fly accidentals are octave-dependent and the whole excerpt has no b on this position.
Comment: Yes, it could be mistaken for being in Bb. However, thankfully, a lot of musos use their ears well, so it would only be a mistake first time round. Although, playing it on bass, a pattern should emerge - it's the same for each bar, just starting on a different note - C, F or G! And, that natural in bar 9 is so unnecessary!
Comment: As I commented to your answer, I failed to mentally (or really) play it.  If I had then I would have recognized it.  I very much doubt that I would have needed that courtesy natural but maybe someone living in a cave has not heard it before.
Answer: One of the most used bass lines in a 12 bar blues! Since it's written in C, but uses the notes from C blues, with the b7th on all the riffs, on the C bars, it's B♭, on the F bars it's E♭, neither in the key sig. Thus accidentals needed. However, there's always a possibility that a reader will forget which notes have been changed, or when they change back (as if!!) so the publisher has printed natural signs which courteously remind that reader that the written notes are naturals, not like the changed notes in the previous bar, which actually get cancelled by the following bar line anyway. It is better to print them thus: (♮), as a way of saying 'you probably know anyway, but here's a reminder!'.
Comment: I concentrated on the question without (mentally) playing it.  I am not much of a bass guitarist but even I have played that.  I don't think that I have ever played it in the key of C and I don't think that I have seen it written down.


R: extracting information from verbose output in nlme fit

Question: library(nlme)
fm2 <- nlme(height ~ SSasymp(age, Asym, R0, lrc),
            data = Loblolly,
            fixed = Asym + R0 + lrc ~ 1,
            random = Asym ~ 1,
            start = c(Asym = 103, R0 = -10, lrc = -8), verbose = TRUE)

**Iteration 1
LME step: Loglik: -115.9653, nlminb iterations: 1
reStruct  parameters:
     Seed
-6.000592
Error in nlme.formula(height ~ SSasymp(age, Asym, R0, lrc), data = Loblolly,  :
  step halving factor reduced below minimum in PNLS step

In this example, I fussed with the starting values a bit so the algorithm did not converge. However, I am interested in extracting the log-likelihood value, -115.9653 from the verbose output. Is there a way to do this?
Comment: you can grab a string by using `out <- capture.output(try(fm2 <- nlme(height ... ` and then try to parse...
Answer: I only have a manual solution for you:
set browsing on error:
options(error = recover)

Run your code and select the deepest frame. You should end up in the environment of the function that throws the error. You can access the likelihood with:
nlmeFit$logLik

and assign it to the global environment with:
LL <<- nlmeFit$logLik

Comment: Thanks. Is there an automatic way to store the verbose output in some way? Or would I have to do this manually?
Comment: you can include the commands to the browser (e.g."2" and "Q") in your script. This is very quick and dirty obviously, but for debugging that should do.
Comment: How exactly would I include those into my script? My goal is to automate fitting a bunch of different `nlme` functions. For those that have an error, I would like to automatically store the verbose output into, say, a list object.
Comment: In that case I would use `try()`, as user20650 suggested. You might want to edit your question or start a new one with a minimum example for what you are asking.
Comment: That stored the error message but not the verbose output (i.e. **Iteration 1 ... etc). Thanks. I have started a new question.
Comment: @Adrian ; [the above comment](https://stackoverflow.com/questions/44770125/r-extracting-information-from-verbose-output-in-nlme-fit#comment76521605_44770125) saves the verbose output (in variable out)


Discord.js DM User kicked

Question: Okay so I am having trouble trying to DM a user who was kicked from the server right now it DM's the person who kicked the member. I don't know what I did wrong but I want the bot to DM the user who was kicked so they know why they were kicked frokm the server
const { RichEmbed } = require("discord.js")
const { red_dark } = require("../../colors.json");

module.exports = {
        name: "kick",
        description: "Kick a user from the guild!",
        usage: "!kick",
        category: "moderation",
        accessableby: "Moderator",
        aliases: ["k"],

    run: async (bot, message, args, user) => {
      try{
  if (message.member.hasPermission("KICK_MEMBERS")) {
      if (message.mentions.users.size != 0) {
        if (message.mentions.members.first().kickable) {
            let reason = args.slice(1).join(" ")
            if(!reason) return message.channel.send("No reason was provided!")

            else {
          message.member.send("This is a test message")
          message.mentions.members.first().kick().then(m => {

            message.channel.send(`**${m.user.username}** has been kicked from **${message.guild.name}**. Bye bye!`)
          });
          }

            } else {
          message.channel.send(`:x: **${message.mentions.user.first().username}** is too priveledged for me to kick.`);
        }
      } else {
        message.channel.send(':x: Please tag the user you would like to kick.')
      }
    } else {
      message.channel.send(`:x: **${message.author.username}**, You do not have permission to kick. You must have the \`Kick Members\` permission.`);
    }
  } catch (err) {
    message.channel.send(`:x: Either I am unable to kick **${message.mentions.users.first().username},** or I do not have permission to kick members.`);
  }

}
}

Answer: You currently send a the DM to message.member. What you would need to do it to send it to the same person you actually kick, which you currently do with message.mentions.members.first().kick().
So with that clarified, you need to do message.mentions.members.first().send("This is a test message")

Discord.js DM User kicked


Strange Behavior of Random Forest in Binary Classification

Question: I'm testing the randomForest package in R and observing something really strange. Let's first look at the R code below:
<code>n <- 1000
set.seed(12345)
X <- matrix(rbinom(n, 1, 0.5), n, 1)
X <- 2 * X - 1
e <- 1 / (1 + exp(X))
W <- rbinom(n, 1, e)

dat <- cbind(W, X)
dat <- data.frame(dat)
dat$W <- factor(dat$W)

rf.classif <- randomForest(W ~ ., data = dat, ntree = 1000)
e.prob <- predict(rf.classif, newdata = dat, type = "prob")[, 2]
e.prob <- as.numeric(e.prob)
e.prob[1:10]
</code>
I use one single binary covariate/feature $X$ to predict $W$. As we can see, $W$ is Bernoulli distributed with probability $e$, which has value of either $0.2689414$ or $0.7310586$. I use randomForest function in R with $1000$ trees (well, since we have only one binary covariate $1$ tree should give the same result).
Anyway, the predicted probability for $W = 1$ ($e.prob$) returned by randomForest is very strange: it is either $0$ or $1$ instead of some value in between. The first $10$ values of $e.prob$ look like:
<code>[1] 0 0 0 0 1 1 1 0 0 0
</code>
I'm trying multiple ways to resolve this problem but still getting the same result. As a side note, running a simple logistic regression would give a very good predicted probability for $W = 1$.
If Random Forest can overfit, then why cannot it give good predicted probability in this simple setting?
Any ideas/suggestions/insights would be very much appreciated.
Answer: There are two problems here. The main problem is that you are only using one predictor variable.  Even though RF will use different points to construct the trees,  with 1000 training points,  you have a pretty dense sampling and each of the trees constructed will be almost the same. In general,  RF is not for problems with a single predictor.
There is another lesser problem as well.  You are testing on the training data. Since you built the trees on the data that you test, it is not surprising that they give very consistent results.
If you are just trying to test out how the probabilities work, try a problem with more predictors and generate new data from the same distribution to use for testing.
I hope that this helps.
Comment: Actually, I've just thought about forcing trees in the RF to output probability (values in (0, 1)) instead of decisions (values = 0 or 1). I'm not sure if this is the way RF works, but if we can do this RF would certainly outperform tree method. This seems to make more sense to me. What do you think? I check the RandomForest package in R but find no evidence of how this can be done.
Comment: Thanks for the reply!

So if I have 100,000 training points, would the result be different?
Comment: Also, it still doesn't make sense to  me why RF is not for problem with a single predictor. If it counts the values belonging to each branch in each tree, then the fraction of points with $W = 1$ should approximate the true probability. Is it correct?

Last, testing on the training data is on purpose. As mentioned at the beginning, RF fails to overfit this simple problem, i.e. failing to approximate the probability in the training data well (even though it can classify well).
Comment: My point is that RF should work well with a single predictor theoretically, and I'm still struggling to understand why it doesn't work here. We cannot simply claim that RF doesn't work for a few predictors but it will work for many.
Comment: I am not saying that RF will fail.  However, when it generates many trees,  they will all be the same - thus, the probabilities are zero or one.  With many predictors it will use different selections for different trees and so generate some variability.
Comment: When I use 1 tree, it still gives 0-1 probabilities. Why do you think that happens that way?
Comment: Because of the way that probabilities are computed in RF.  For each point, RF counts the number of trees that went to each class and divides by the total number of trees.  If there is one tree,  that is guaranteed to be either 0/1 or 1/1.  But when there is only one variable and all the trees are essentially the same, it will be 0/n or n/n.
Comment: Yes, that makes sense. I think using decision tree in this simple setting would work much better. Testing it with rpart package in R gives me really good results. Thanks a lot !!