Listbox for MVC 6 EF 7 Property not Populating

Question: I've been trying for a while now to get a list box to populate and I can't seem to figure it out. I've studied entity framework 7 documentation pretty extensively but I'm still new to it. There aren't a lot of tutorials out there for MVC6/EF7 yet so its been hard to know what the best practice is for associating one entity class with an instance of another. Please excuse the length of the question, I'm just trying to be thorough.
I'm using entity framework 7, asp.net 5 and MVC 6.
Steps To Reproduce Issue

Create a new ASP.Net Web Application → Name of project: ListBox.Web → Name of solution ListBox
Choose APS.NET 5 Templates → Web Application
Create two classes in the Models folder
Parent.cs
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace ListBox.Web.Models
{
    public class Parent
    {
        public int ParentId { get; set; }
        [Required]
        public string Name { get; set; }
        public ICollection<Child> Children { get; set; }
    }
}

Child.cs
using System.ComponentModel.DataAnnotations;

namespace ListBox.Web.Models
{
    public class Child
    {
        public int ChildId { get; set; }
        [Required]
        public string Name { get; set; }
        public int ParentId { get; set; }
        public Parent Parent { get; set; }
    }
}

Create controllers and views for each of the data classes using scaffolding

Add links to the controllers in _Layout.cshtml

Home

Parents

Children

About

Contact

Create the database
ListBox\src\ListBox.Web>dns ef migrations add Initial
ListBox\src\ListBox.Web>dnx ef database update

Run the web application
Add a couple parents.

Attempt to add a child.

A drop box is shown for parents but there are no items in the drop box to select

The HTML for the list box is: <select class="form-control" data-val="true" data-val-required="The ParentId field is required." id="ParentId" name="ParentId"></select>

Controller Source Code
using System.Linq;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.Data.Entity;
using ListBox.Web.Models;

namespace ListBox.Web.Controllers
{
    public class ChildrenController : Controller
    {
        private ApplicationDbContext _context;

        public ChildrenController(ApplicationDbContext context)
        {
            _context = context;
        }

        // GET: Children
        public IActionResult Index()
        {
            var applicationDbContext = _context.Child.Include(c => c.Parent);
            return View(applicationDbContext.ToList());
        }

        // GET: Children/Details/5
        public IActionResult Details(int? id)
        {
            if (id == null)
            {
                return HttpNotFound();
            }

            Child child = _context.Child.Single(m => m.ChildId == id);
            if (child == null)
            {
                return HttpNotFound();
            }

            return View(child);
        }

        // GET: Children/Create
        public IActionResult Create()
        {
            ViewData["ParentId"] = new SelectList(_context.Set<Parent>(), "ParentId", "Parent");
            return View();
        }

        // POST: Children/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Create(Child child)
        {
            if (ModelState.IsValid)
            {
                _context.Child.Add(child);
                _context.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewData["ParentId"] = new SelectList(_context.Set<Parent>(), "ParentId", "Parent", child.ParentId);
            return View(child);
        }

        // GET: Children/Edit/5
        public IActionResult Edit(int? id)
        {
            if (id == null)
            {
                return HttpNotFound();
            }

            Child child = _context.Child.Single(m => m.ChildId == id);
            if (child == null)
            {
                return HttpNotFound();
            }
            ViewData["ParentId"] = new SelectList(_context.Set<Parent>(), "ParentId", "Parent", child.ParentId);
            return View(child);
        }

        // POST: Children/Edit/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Edit(Child child)
        {
            if (ModelState.IsValid)
            {
                _context.Update(child);
                _context.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewData["ParentId"] = new SelectList(_context.Set<Parent>(), "ParentId", "Parent", child.ParentId);
            return View(child);
        }

        // GET: Children/Delete/5
        [ActionName("Delete")]
        public IActionResult Delete(int? id)
        {
            if (id == null)
            {
                return HttpNotFound();
            }

            Child child = _context.Child.Single(m => m.ChildId == id);
            if (child == null)
            {
                return HttpNotFound();
            }

            return View(child);
        }

        // POST: Children/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public IActionResult DeleteConfirmed(int id)
        {
            Child child = _context.Child.Single(m => m.ChildId == id);
            _context.Child.Remove(child);
            _context.SaveChanges();
            return RedirectToAction("Index");
        }
    }
}

Child Create.cshtml
@model ListBox.Web.Models.Child

@{
    ViewData["Title"] = "Create";
}

Create

<form asp-action="Create">

Child

                <input asp-for="Name" class="form-control" />

                <select asp-for="ParentId" class ="form-control"></select>

                <input type="submit" value="Create" class="btn btn-default" />

</form>

    Back to List

@section Scripts {

}

Answer: Change Create() method in ChildrenController, change
    public IActionResult Create()
    {
        ViewData["ParentId"] = new SelectList(_context.Set<Parent>(), "ParentId", "Parent");
        return View();
    }

to
    public IActionResult Create()
    {
        ViewData["ParentId"] = new SelectList(_context.Set<Parent>(), "ParentId", "Name");
        return View();
    }

In Create.cshtml, change
<select asp-for="ParentId" class="form-control"></select>

to
@Html.DropDownList("ParentId", null, htmlAttributes: new { @class = "form-control" })

Answer: The generated code is incorrect, it is a bug https://github.com/aspnet/Scaffolding/issues/149
One solution using "tag helpers" is:
Controller
...
ViewData["Parents"] = new SelectList(_context.Set<Parent>(), "ParentId", "Name", child.ParentId);
...

View
@{
    var parents = (IEnumerable<SelectListItem>)ViewData["Parents"];
}
...
<select asp-for="ParentId" asp-items="parents" class ="form-control">
     <option disabled selected>--- SELECT ---</option>
</select>
...

Answer: Here's how to do it when there is only one type of object which is nested within another object of the same type.
Object:
public class Fleet
{

    public int Id { get; set; }
    public Fleet ParentFleet { get; set; }
    public int? ParentFleetId { get; set; }

    public string Name { get; set; }

    [InverseProperty("ParentFleet")]
    public virtual List<Fleet> Children { get; set; }

    public List<UserFleet> UserFleets { get; set; }
}

Controller:

ViewData["ParentFleetId"] = new SelectList(_context.Set<Fleet>(), "Id", "Name");
return View();

View:
<form asp-action="Create">

Fleet

                <input asp-for="Name" class="form-control" />

                <select asp-for="ParentFleetId" asp-items="ViewBag.ParentFleetId" class="form-control">
                    <option value=""></option>
                </select>

                <input type="submit" value="Create" class="btn btn-default" />

</form>


Question about the equation $\int_\Omega \left(\Delta f(x)\right)\overline{g(x)} \ dx \ +\ f(x_0) = 0$

Question: $\newcommand{\R}{\mathbb{R}}$HYPOTHESIS
Let $\Omega $ be an open, connected subset of $\R^n$, denote by $C^\infty_0(\Omega)$ the functions with compact support in $\Omega$.
Let $x_0 \in \mathrm{int} (\Omega)$ and suppose that    $g\in L^2(\Omega)$ satisfies
$$(*)\quad \quad \int_\Omega \left(\Delta f(x)\right) \overline{g(x)} \ dx \ +\ f(x_0)  = 0 $$
for all $f\in C_0^\infty(\Omega)$ and
$$(**) \quad \quad g|_U \equiv 0 $$
where $U\subset \Omega$ is an open ball.
DEDUCTION
(*) implies that for all $f\in C_0^\infty(\Omega \setminus \{x_0\})$, $\int_\Omega   \left(\Delta f(x)\right) \overline{g(x)} \ dx = 0$, which tells us that $\Delta g = 0$ weakly on $\Omega\setminus\{x_0\}$, and therefore by elliptic regularity ($g\in L^2(\Omega))$ , $g|_{\Omega\setminus \{x_0\}}$  is a classical solution, hence is in $C^\infty(\Omega\setminus\{x_0\})$.
Now (**) implies by unique continuation that $g|_{\Omega\setminus \{x_0\}}\equiv 0$ and thus $g|_{\Omega}\equiv 0$.  But this is in contraddiction with $(*)$.

Is there some hidden mistake in my argument or really  $(*)$ and $(**)$ are incompatible conditions?

I abstracted this from my original problem where instead of the operator $\Delta$ we have a Dirac operator  and instead of $\Omega$ we have a closed manifold.
Comment: Can some function always satisfy (*)? Perhaps I'm missing something, but if it does it for $f$ then it may be hard to satisfy for $f+c$ for all constants $c$ as they only affect the free term, not the laplacian one
Comment: @Ilya Thank you for your comment. $f+c$ is not compactly supported in $\Omega$ though.

The idea is still interesting in the manifold setting (the one I am referring to in the last paragraph). In this case  constants correspond to covariantly constant spinor fields, which however do not always exist (the spin structure must be trivial).
Answer: You are correct that these are incompatible conditions.  The first hypothesis is the statement that $\Delta g = \delta_{x_0}$ in the sense of distributions.  Therefore $g$ must be a fundamental solution of the Laplacian on the domain $\Omega$, which does not vanish on any open set (in fact, it must be positive everywhere).
I am wrong about the fundamental solution being positive -- this is only true on some manifolds (for example it is positive on $\mathbb{R}^3$ but not on $\mathbb{R}^2$).  However the unique continuation principle you use is valid and, as $g$ is harmonic outside of $x_0$, you are correct that it cannot vanish on an open set.
Comment: Can you provide some references about your last statement? (Not vanishing, positivity?)
Comment: Before accepting the question, let me ask one last thing.
If we are working on a closed manifold, so the equality is $f(x_0) = -\int_M (\Delta f) g$ for all $f\in C^\infty(M)$, then the if we add a constant $c\in \mathbb R$ to $f$, the left hand-side varies while the right hand-side stays the same; does this imply that there are no fundamental solutions on a closed manifold? Seems wrong to me.


Galera alguém sabe de uma função que considere caracteres especiais como "://" no php sem ser strpos()?

Question: Galera alguém sabe de uma função que considere caracteres especiais como "://" no php sem ser strpos()?
Ele não procura nas string um caractere comum junto de caractere especial.
Ex:
    <?php
    function onhttp($param) {
    $busca = strpos($param, "http");
    return $busca;
    }
    $testurl = "iuuiuhttps://www.youtube.com/watch?v=HL9kaJZw8iw";
    echo onhttp($testurl); //Saída: está após 5 caracteres

    <?php
    function onhttp($param) {
    $busca = strpos($param, "http://");
    return $busca;
    }
    $testurl = "iuuiuhttps://www.youtube.com/watch?v=HL9kaJZw8iw";
    echo onhttp($testurl); //Saída: Nada é retornado.

Quero criar uma função que verifique se o começo da url conte a string "http://".
Comment: Isso não é verdade: _"Ele não procura nas string um caractere comum junto de caractere especial."_ - e pra saber se o começo é `https://` basta ver se o `strpos( $param, 'https://' ) === 0` (notar os tres `=` )
Comment: E se quiser achar em qualquer posição: `strpos( $param, 'https://' ) !== false`
Comment: Nossa é verdade, grande falta de atenção minha. E essa não é a primeira vez que não consigo fazer algo por não prestar atenção entre o http e https muito obrigado.
Answer: O strpos e stripos consideram sim os "caracteres especiais", o problema é que :

Aqui strpos($param, "http"); você apenas verificou o http e na string iuuiuhttps://www.youtube.com/watch?v=HL9kaJZw8iw existe HTTP, veja:

iuuiuhttps://

Já aqui strpos($param, "http://"); você quer verificar se tem http:// mas a url passada é https, ele nunca vai achar iuuiuhttps://www.youtube.com/watch?v=HL9kaJZw8iw.
Outro detalhe citado pelo @Bacco é que strpos pode retornar números (iniciando do 0) que se referem a posição ou FALSE acaso não encontre nada, ou seja no PHP se usar == pode ter problemas em diferenciar 0 de false, portanto use === ou !== nesta função especifica, deve tomar cuidado e de preferencia ler a documentação http://php.net/manual/pt_BR/function.strpos.php e ver os exemplos.

Não entendi o objetivo, parece tudo bem confuso e também não entendi porque não deve usar strpos, não tem sentido o iuuiu na frente das urls, ou você quer verificar ou você quer extrair. se for extrair então simplesmente use explode, assim:
<?php
function onhttp($param) {
    $busca = explode($param, 'http://', 2);
    return $busca[0];
}

$testurl = "iuuiuhttp://www.youtube.com/watch?v=HL9kaJZw8iw";
echo onhttp($testurl); //retorna www.youtube.com/watch?v=HL9kaJZw8iw

Se quer apenas extrair a urls HTTP e HTTPS então use preg_match, assim:
<?php
function onhttp($param) {
    $busca = preg_match('#(http|https)[:]\/\/(.*?)$#', $param, $matches);
    return $matches[2];
}

$testurl = "iuuiuhttps://www.youtube.com/watch?v=HL9kaJZw8iw";
echo onhttp($testurl); //retorna www.youtube.com/watch?v=HL9kaJZw8iw

Se quer apenas verificar se é uma URL "http valida":
<?php
function onhttp($param) {
    return preg_match('#(http|https)[:]\/\/#', $param, $matches) > 0;
}

$testurl = "iuuiuhttps://www.youtube.com/watch?v=HL9kaJZw8iw";
var_dump(onhttp($testurl)); //retorna um valor booleano, no caso true

Agora acho que o melhor seja extrair apenas o ID do video, veja esta resposta:

Iframe do youtube com o link inteiro

Embarcar videos
Conforme sugestão do @EduardoAlmeida, se você pretende embarcar os videos em seu site você pode verificar se a sua página esta usando HTTP ou HTTPS, para evitar inserir iframes HTTP em uma página HTTPS, assim:
<?php
function youtubeEmbedURI($url)
{
    $protcol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
    return $protocol . '://www.youtube.com/embed/' . youtube_id_from_url($url);
}
?>

Ou simplesmente omitir o http ou https deixando apenas o // da url assim:

Desta maneira o navegador vai usar o protocolo que a página estiver usando no momento.
Comment: Linda resposta! Hey, Guilherme! Dá pra você comentar na sua resposta o uso do `$_SERVER['HTTPS']` para verificar se um servidor, por exemplo, o do YouTube está usando SSL? Obrigado!
Comment: Perfeito, bro!!! Ta aí a resposta pra pergunta do OP. Obrigado!!!
Comment: a parte que vc cortou não deixa de estar correta, está bem confuso mesmo. O problema é que do jeito que ele fez, o retorno vai ser false ou zero se a string estiver no começo, pq faltou o `=== 0` pra saber se existe e está no começo, ou `!== false` pra saber se está em qq lugar.
Comment: Muito obrigado Guilherme, e obrigado pela prevenção no uso de (!== e ===) ao em vez de (== e !=) nessa situação.
Answer: fácil
$url = 'http://site.com';

if(substr($url, 0, 7) == 'http://')
    echo "A url comessa com 'http://'";
else
    echo "A url nao comessa com 'http://'";


Handling of JOptionPane cancel button, which takes string as input

Question: I want to take input as string from user through a Input dialog box, and also handle the situation if user presses cancel button.
Any suggestions?
Comment: see `JOptionPane.showInputDialog` . https://docs.oracle.com/javase/7/docs/api/javax/swing/JOptionPane.html#showInputDialog(java.awt.Component,%20java.lang.Object) . `null` is returned if the user chooses "Cancel" .
Comment: @Berger How about upgrading that comment to an answer?
Comment: Why even SO community try to answer questions like that. Those type of question asked millions of times and still getting answers.. Just google your question.
Answer: You may use the showInputDialog method of class JOptionPane .
If the user hits Cancel, the returned value is null.
Also note, as @mKorbel said in the comments, that you will also get null if the windows has been closed directly.
String result = JOptionPane.showInputDialog("Please enter something");

if(result == null){

    System.out.println("User pressed CANCEL, or window has been closed");
}
else{

    // do something with the String
}

Comment: disagree, because `result != null`, `JOptionPane` has all `windows events` implemented in API (closing, event from escape key, .....)
Comment: @mKorbel : That's right, but  will you agree that getting `null` at least means that the `Ok` button wasn't chosen ?
Comment: [there is something that I ....e.g. :-)](http://stackoverflow.com/a/8582851/714968)
Answer: Try this:
if(result == null){
    System.out.println("User pressed CANCEL, or window has been closed");
    System.exit(0);
}


Random variables and sigma field

Question: Given $Z_1,Z_2,\cdots$ i.i.d with $E|Z_i|<\infty$. $\theta$ is an independent r.v. with finite mean and $Y_i=Z_i+\theta$.
If we define $F_n=\sigma(Y_1,\cdots,Y_n), F_\infty=\sigma(\cup_n F_n).$ Do we have $\theta\in F_\infty$?
Answer: How about: If $E[Z_i] = m$, then
$$
\lim_{n \to \infty} \frac{1}{n}\sum_{k=1}^n (Z_i+\theta) = m + \theta
$$
a.e. so $m+\theta$ is $F_\infty$-measurable.  So is the constant $m$.
Comment: Yes you're right. Thank you.
Comment: And what if you don't assume $Z_i$ is integrable?  Must $\theta$ still be $F_\infty$-measurable?
Answer: Concerning GEdgar's followup question; the moments are not necessary.
We replace the sample average and true mean $m$ by the empirical distribution function
and the  true distribution function $F$.
Without loss
of generality assume that the probability space is $\Omega\times \Omega^\prime$,
a product space equipped with a product measure $\mathbb{P}\times\mathbb{Q}$.
For any fixed $c\in\mathbb{R}$ we have (almost surely)
$${1\over n}\sum_{i=1}^n1_{(-\infty,\, c]}(Z_i(\omega)+\theta(\omega^\prime))
= {1\over n}\sum_{i=1}^n1_{(-\infty,\,c-\theta(\omega^\prime)]}(Z_i(\omega))
\to F(c-\theta(\omega^\prime)),\tag1$$ where $F$ is the cumulative distribution function
 of $Z$.
For each fixed $\omega^\prime$, the convergence in (1) holds for $\mathbb{P}$-almost every $\omega$ by the law of large numbers
 and hence, by Fubini,  holds for $(\mathbb{P}\times\mathbb{Q})$-almost every $(\omega,\omega^\prime)$ on the product space. For $0<u<1$ define $q(u)=\inf(x: F(x)\geq u)$, the quantile function of $F$. It is easy to show that $F(c-\theta(\omega^\prime))\geq u$ if and only if $c-\theta(\omega^\prime)\geq q(u)$.
In particular, this shows that
$$\{(\omega,\omega^\prime) : c-q(1/2)\geq \theta(\omega^\prime)\}\in {F}_\infty\vee{\cal N}$$
where ${\cal N}$ is the $\sigma$-field of $(\mathbb{P}\times\mathbb{Q})$-trivial sets.
Since $c$ is arbitrary, we conclude that $\theta\in {F}_\infty\vee{\cal N}.$

Random variables and sigma field


Why naive (prediction) forecasting is called random walk?

Question: Why naive (prediction) forecasting is called a random walk?
Naive prediction is to use the last value as a forecast.
(It's clear that the best prediction for a random walk is a naive one.)
Answer: One of the simplest and yet most important models in time series forecasting is the random walk model. This model assumes that in each period the variable takes a random step away from its previous value, and the steps are independently and identically distributed in size ("i.i.d."). This is equivalent to saying that the first difference of the variable is a series to which the mean model should be applied.
In other words, it predicts that all future values will equal the last observed value. This doesn't really mean you expect them to all be the same, but just that you think they are equally likely to be higher or lower, and you are staying on the fence as far as point predictions are concerned.
Because of this, this method is usually known as naive method.
https://people.duke.edu/~rnau/Notes_on_the_random_walk_model--Robert_Nau.pdf


Accessing AWS APIs from within a lambda function?

Question: I'm writing my first lambda function (in Python), and I'm a little confused about how credentials are supposed to work in the lambda environment.  I'm trying to retrieve a secret (for Aurora database access) from the aws secrets api, using their example code which looks something like this (I've stripped out all the error handling for brevity):
def get_secret():
    secret_name = 'dbtest-postgres-secret'
    region_name = 'us-east-2'

    session = boto3.session.Session()
    client = session.client(
        service_name='secretsmanager',
        region_name=region_name
    )

    get_secret_value_response = client.get_secret_value(
        SecretId=secret_name
    )

    secret = get_secret_value_response['SecretString']

    return secret

This works fine locally in an environment in which I have my normal AWS credentials, but returns None without raising any errors when running as part of a lambda function.  I'm using it like this:
def handler(event, context):
    secret = get_secret()
    assert secret is not None

And it's failing at that assert statement:
{
  "errorType": "AssertionError",
  "stackTrace": [
    "  File \"/var/task/dbtest.py\", line nn, in handler\n    assert secret is not None\n"
  ]
}

I assumed that by assigning a role to the lambda function with appropriate permissions (AmazonRDSDataFullAccess, which includes permissions to access the secrets manager) that everything would be set. Do I need to provide explicit credentials (e.g., an access key and secret) to the lambda function?
Comment: i'am wondering why you didn't see an AccessDeniedError.
Answer: You do not need to give explicit credentials, the lambda will get the credentials from the role you assigned to it. What is the secret you are asking for, because the AmazonRDSDataFullAccess only has access to secrets at rds-db-credentials/*.
Comment: The secret is called "dbtest-postgres-secret".  Are you saying it needs to have a name prefixed with `rds-db-credentials/`?
Comment: That's correct. In order for that particular policy to work you would need to do that. If you need a different set of secrets you should specify the name(s) (or pattern) in a policy that you create.
Comment: Thanks, that was it!


how to create Trigger in postgresql for checking function exit or not

Question: I m new to postgresql and database part. I want to check function exit or not in postgresql using trigger before insert statement. any body know how to create trigger this?
Answer: Create a special trigger function:
CREATE OR REPLACE FUNCTION some_function()
RETURNS trigger AS $$
    BEGIN
        IF some_condition THEN
            RAISE EXCEPTION 'Some message for id %', NEW.id;
        END IF;
        RETURN NEW;
    END;
$$ LANGUAGE plpgsql;

Then define a trigger to fire it
CREATE TRIGGER some_trigger
BEFORE INSERT OR UPDATE ON some_table
FOR EACH ROW EXECUTE PROCEDURE some_function();

When the exception is raised, the update will fail.
The SQL executed may be or arbitrary complexity, involving any query or function you like. It may also change the NEW values via SET NEW.some_column = some_value, or even update other tables.
Note the NEW.id is an example column only. Use whatever column you like from the NEW row (or none) in the message.
If the check is localized to the row, consider using a column constraint, eg:
CREATE TABLE my_table (
    some_column int CHECK (some_column between 0 and 10),
    other_column int CHECK (other_column < some_column)
)


HTML Parser no Xamarin

Question: Estou desenvolvendo um aplicativo com o Xamarin com o intuito de efetuar login em uma conta web usando HTTPWebRequest e filtrar as informações relevantes do site para um aplicativo.
Já desenvolvi a parte de fazer login, agora preciso filtrar o HTML que tenho de retorno.
Eu preciso extrair do HTML a informação contida na decima segunda tag
 do HTML, alguém saberia como fazer isso?
A grande dificuldade que tenho é que as tags não tem ID então não consigo usar isso.
o codigo html da pagina eu coloquei aqui para quem quiser copiar e me ajudar.
este html e retornado na string do response.
http://notepad.cc/share/hvptGOlmZQ

preciso das informacoes YYYY e XXXX contidas nas tables do html..
Comment: Você pode usar o [Html Agility Pack](http://htmlagilitypack.codeplex.com/). Segundo [esse artigo do blog do Xamarin](http://blog.xamarin.com/data-extraction-in-mobile-apps/), ele dá conta de fazer isto. Sobre as *tags* não terem *IDs*, é possível extrair a informação da *tag* através da classe ou nome, vai depender da estrutura do HTML.
Comment: estou tentando usar ele mais nao parece ser facil como todos dizem , na verdade nao acho um tutorial util ate agora...
Comment: [Edite](http://pt.stackoverflow.com/posts/60353/edit) a pergunta e coloque o HTML que você tem. Não esqueça de postar qual informação você quer extrair.
Comment: esta e a parte importante do html que preciso retirar.. preciso ler os valores dos XXXXX e dos YYYY
Answer: Segundo o artigo Data Extraction in Mobile Apps, o Html Agility Pack pode ser utilizado para fazer isto.

HtmlAgilityPack lhe permite analisar os documentos HTML. Ao contrário
  de analisadores XML tradicionais, ele é capaz de se recuperar de
  conteúdo mal escrito, muito parecido com o seu navegador web. Além
  disso, a biblioteca é principalmente multi-plataforma, por isso é
  fácil de criar seus projetos de móveis com Xamarin [...]

Supondo que o arquivo foo.html contenha 20 tabelas e você queira selecionar somente a décima segunda, faça a consulta usando //table[12]/tbody/tr/td//text(). Segue um exemplo:
// using HtmlAgilityPack;

HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.Load("arquivoHTML.html");
foreach (HtmlAgilityPack.HtmlNode nodo in
   doc.DocumentNode.SelectNodes("//table[2]/tbody/tr/td//text()")) {
       MessageBox.Show(nodo.InnerText);
}

Comment: Estranho, aqui no VS2012 funciona sem problemas, você referenciou o Html Agility Pack? veja se consegue compilar esse código (http://www.filedropper.com/windowsformsapplication6).
Comment: O erro que tava dando era que eu estava errando o caminho no selectNodes ... agora so falta acertar o caminho porem e muita informacao na pagina... mas vlw
Comment: supondo que haja 20 tables no html inteiro como eu pego a table exata que eu quero?
Comment: esse e o problema nao ha nada unico nela. Eu fazia isso com o beautifulSoup em python trazendo todas as tables para um vetor e lendo todos os nos dentro da table de posiçao 12
Comment: ta dando erro no foeach .. diz "Referência de objeto não definida para uma instância de um objeto."
Comment: mesmo erro no mesmo lugar
Comment: Funcionou, acredito que o erro deve ser que eu estou fazendo o doc.load(string) e nesta string contem um html ...
Comment: Na verdade nao, troquei para um arquivo html e continua com o mesmo erro, mas isso eu resolvo aqui, ja vi que funciona. obrigado
Comment: editei a pergunta , coloquei o html inteiro. se puder me ver e me ajudar.. estou meio preso nisso, e esta maneira que vc colocou acima na resposta apesar de funcionar no c# nao funciona no xamarin... :/
Comment: Vamos [continuar esta discussão no bate-papo](http://chat.stackexchange.com/rooms/23267/discussion-between-user3896400-and-qmechanik).
Comment: coloquei o html inteiro da pagina pra ver se te ajuda , usei isso que vc colocou ai no xamarin mas aparentemente o xamarain trabalha de uma forma diferente o html agility Pack
Comment: @user3896400 Aqui o caminho `//table/tr/td//text()` funcionou, sem `tbody`, ([exemplo](http://www.filedropper.com/windowsformsapplication6_1)). Não tenho como testar no *Xamarin*, mas pelo que pesquisei, é necessário fazer alguns ajustes, dependerá do problema que você está tendo. [Aqui](https://github.com/Clancey/HtmlAgilityPack) parece haver uma versão do *HtmlAgilityPack* compatível com o *Xamarin*, olhe também [essa *thread*](https://forums.xamarin.com/discussion/680/get-html-code-and-text-inside-tags) para ver se te ajuda em algo. Não tenho como ajudar muito nessa situação.
Comment: @user3896400 Conseguiu resolver o problema? se sim, poste a solução para ajudar futuros visitantes com o mesmo problema. =)
Comment: nao consegui.... Acabei tendo que esquecer um pouco deste projeto .

HTML Parser no Xamarin


Seeking error in OSMF

Question: I have a HTTP video player built using Adobe's OSMF and I am experiencing a strange behavior when trying to seek within a subclip.
The player requests data from the server using URL like "http://videoserver.com/video.flv" to get the full video, and appends "?begin=123456" to request a subclip starting at 123456 bytes offset.
Whenever I try to seek within a loaded subclip, the playhead just drops to the start of the subclip and the video plays from there. Although both mediaPlayer.canSeek() and mediaPlayer.canSeekTo(newtime) return true.
Any feedback is more than appreciated!
Answer: OSMF automatically seeks to nearest keyframe. Try encoding your video keyframe/sec.
read more here: http://www.adobe.com/devnet/flash/articles/osmf-media-player.html
Comment: I have little control over how the media is encoded. I'll try this, thanks for the tip!
Comment: Also, check that provided parameter ?begin expects time as offset value. It might also be that it expects bytes as offset value.
Comment: The offset is bytes, not seconds, I know this for sure =)

Seeking error in OSMF


Drupal Migration and 404 Errors

Question: I've set up a Drupal 7 site locally and have ftp'd the site over to my ISP's server which is a linux box running PHP and MySQL.
I've never successfully logged into the remote site before and I have locked myself out as I got the admin password wrong.  When I go http://www.example.com/?q=user and click on request New Password then I get this error:
<code>Not Found

The requested URL /user/password was not found on this server.

Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.
</code>
One thing I've been confused about and that is the .htaccess file.  I never had one locally on my Mac and I did not need it (I know it is hidden) - so I downloaded one and deployed it to the web site but then I got 500 errors, it made it worse.
I've since deleted that file and at least I get some content - but not very much - just the front page.  I overrode the themes name in settings.php as I have user access errors when using a new template, if I get passed this bit I can probably fix that.  I changed it back to one of the default themes and that allowed me to get some content and not the 'white screen of death'
Advice welcome!
Answer: To get site working properly:  It seems like .htaccess issue. You do need the .htaccess file. It should be in the document root folder and secured so that any host account can read it. Out of the box Drupal has this file.
To recover Drupal User=1 password: If you are lucky, your ISP may have drush installed globally on this server. SSH to the server and try "drush uli" command. If not, you can try installing drush on your local machine - the pain will be well worth it if you plan to continue working on Drupal. You can use "drush uli" command on your local machine, login with the on-time login link given and change the admin password. They upload the database back to your ISP.
Comment: Ok thanks, I will learn more about .htaccess and how I can configure it. I was running Drupal on MAMP locally on my Mac and I did not have the file.  Thanks, will also check out drush - thanks for the pointers.
Comment: You can also reset the administrators password if you can get direct MySQL access on the host, see https://www.drupal.org/node/1023428

Drupal Migration and 404 Errors


Get column and row index pairs of Pandas DataFrame matching some criteria

Question: Suppose I have a Pandas DataFrame like following. These values are based on a distance matrix.
A = pd.DataFrame([(1.0,0.8,0.6708203932499369,0.6761234037828132,0.7302967433402214),
                  (0.8,1.0,0.6708203932499369,0.8451542547285166,0.9128709291752769),
        (0.6708203932499369,0.6708203932499369,1.0,0.5669467095138409,0.6123724356957946),
        (0.6761234037828132,0.8451542547285166,0.5669467095138409,1.0,0.9258200997725514),
        (0.7302967433402214,0.9128709291752769,0.6123724356957946,0.9258200997725514,1.0)
                  ])

output :
Out[65]:
          0         1         2         3         4
0  1.000000  0.800000  0.670820  0.676123  0.730297
1  0.800000  1.000000  0.670820  0.845154  0.912871
2  0.670820  0.670820  1.000000  0.566947  0.612372
3  0.676123  0.845154  0.566947  1.000000  0.925820
4  0.730297  0.912871  0.612372  0.925820  1.000000

I want only the upper triangle.
c2 = A.copy()
c2.values[np.tril_indices_from(c2)] = np.nan

output :
Out[67]:

        0    1        2         3         4
    0 NaN  0.8  0.67082  0.676123  0.730297
    1 NaN  NaN  0.67082  0.845154  0.912871
    2 NaN  NaN      NaN  0.566947  0.612372
    3 NaN  NaN      NaN       NaN  0.925820
    4 NaN  NaN      NaN       NaN       NaN

Now I want to get column and row index pairs based on some criteria.
Eg : Get column and row indexes where value is greater than 0.8. For this the out put should be [1,3],[1,4],[3,4]. Any help on this?
Answer: You can use numpy's argwhere:
In [11]: np.argwhere(c2 > 0.8)
Out[11]:
array([[1, 3],
       [1, 4],
       [3, 4]])

To get the index/columns (rather than their integer locations), you could use a list comprehension:
[(c2.index[i], c2.columns[j]) for i, j in np.argwhere(c2 > 0.8)]

Comment: Seems I have asked the question with a wrong example. What happens if My row and column indexes are [1,2,3,5,8]
Comment: Excellent! :) Thanks very much. Please edit this in the answer, so I can accept it.


How to use angular-sortable-view in my Angular code?

Question: I'm want to make some images sortable by dragging them around in my Angular website for which I'm trying to use angular-sortable-view. The demos look really good, but I just can't get it to work in my own code and I get no error whatsoever.
I've got a simple list defined in my controller:
$scope.prop = {};
$scope.prop.images = [
    {id: 'http://www.adiumxtras.com/images/thumbs/dango_status_icon_set_7_19047_6248_thumb.png'},
    {id: 'https://upload.wikimedia.org/wikipedia/commons/thumb/1/1f/Red_information_icon_with_gradient_background.svg/48px-Red_information_icon_with_gradient_background.svg.png'},
    {id: 'https://www.haiku-os.org/docs/userguide/images/apps-images/icon-o-matic-icon_64.png'},
];

and my html looks as follows:

I made a plunker here.
Does anybody know what I'm doing wrong? All tips are welcome!
Answer: You've got a couple problems here.  The first being that angular-sortable-view is a separate module which you need to add to your app:
angular.module('sort', ['angular-sortable-view'])

In addition to that, since images are draggable in the browser, you must disable that:

Check the forked plunkr here: http://plnkr.co/edit/i8Z8jJGnJoGFgTMFej4Q?p=preview
Answer: According to https://github.com/kamilkp/angular-sortable-view to sort images you need to add draggable="false" atribute to your image:


Web Log analysis in Java

Question: How to read a web server log file in Java. This file is getting updated all the time.  If I open a new FileInputStream, will it read the log real time?
Regards
Answer: Here is a solution based on RandomAccessFile:
http://www.informit.com/guides/content.aspx?g=java&seqNum=226

Web Log analysis in Java


Intuitive understanding of hypothesis testing with Z-scores

Question: I wanted to dig a bit deeper into hypothesis testing and fresh up my conceptual understanding from undergraduate courses. The typical way of how hypothesis testing is teached is to calculate the Z-score and then compare the associated P-value with a pre-determined cut-off level of alpha.

Let's create a hypothetical example. I've found a new drug for which I claim it raises the level of blood value X. We know that the average blood level of X in the control group is X = 10 with a standard deviation of 1.
I've ingest the drug to my friend now and measure his blood level afterwards. E voila, his blood level is 12. Given the formula above, I would arrive at a Z-Score of 2 which is far below the normally used cut-off level of 0.05
Coming to my question
How can I conclude validity from this result? E.g it could have been that I have given the drug to a group of 100 people and observed that the average result was the same as in the control group. Similarly, I could have found my friend in the group of 100 people with his extreme value of 12. I could repeat the hypothesis test only with im and arrive at a statistically meaningful result. Ta Da!
Could someone verify if my understanding is flawed here? Thank you very much!
Answer: I think your understanding is basically sound here. If you conduct the study as you describe, with only one patient taking the drug, and measure $x = 12$, that would constitute a significant result, so the conclusion would be that the drug does work.
While this is formally correct, I suppose most of us would be suspicious about this result, in particular in view of the extremely small sample size. And indeed, the conclusion may still be wrong, not only because of the obvious fact that $\alpha = 0.05$ is still more than zero, but also because the entire statistical argument here rests on some very strong assumptions, e.g.

The blood level measurements are normally distributed under the null hypothesis (with mean $\mu$ and standard deviation $\sigma$).
Your friend is randomly sampled from the population of all people who might take the drug.
You know the exact value of $\mu$.
You know the exact value of $\sigma$.

Especially assumptions 3 and 4 are so unrealistic that they are usually not made in practice. So you usually have to estimate $\mu$ and $\sigma$ too, and the simple Z-test is no longer applicable.
Regarding your penultimate paragraph, if you have done a study with 100 people, then you should of course include all of them in the calculations (except for certain pre-specified exclusion criteria). Basing the test on only one (or several) person(s) with high $x$ would be statistical malpractice ("cherry-picking"), because assumption 2 would no longer hold.


how to get the region (the menu is rendered in) or block name/ID in hook_preprocess_menu

Question: I have a menu that want to behave differently based on the region its displayed in.
By default there is no file suggestion that differentiates which twig file to be used for a menu based on the region.  Even if there was I think for the purpose of adding/removing a class it is more convinient to modify a variable in a preprocess function than keeping to versions of a twig template.
here is what I have
function THEMENAME_preprocess_menu(&$vars) {
    $test = "";
    if ($vars['menu_name'] == 'main') {
        if (!isset($vars['attributes']['class'])) {
            $vars['attributes']['class'] = [];
        }
        //test region or block name before merging
        $vars['attributes']['class'] = array_merge($vars['attributes']['class'], ['main-menu-regionA']);
    }
}

I need a way to test the region or the block name to add a specific class to the parent UL element
my 2nd choice would be to explore the hook_theme_suggestions_alter
Answer: hook_preprocess_menu is missing a lot of variables that other preprocessors have so I finally solved my problem using hook_preprocess_block (which I think would not have been possible in earlier versions of drupal)
New solution since people have been reporting that $vars['configuration']['region'] is empty
function THEMENAME_preprocess_block(&$vars){
    if($vars['base_plugin_id'] == "system_menu_block"){
        if($vars['derivative_plugin_id'] == "main"){
            $block = \Drupal\block\Entity\Block::load($vars["elements"]["#id"]);
            if( $block->getRegion() == "navbar")
                $vars['content']['#attributes']['class'][] = 'in-navbar';
                $vars['content']['#attributes']['class'][] = 'nav';
            }
            elseif($vars['configuration']['region'] == "footer"){
                $vars['content']['#attributes']['class'][] = 'in-footer';
            }
        }
    }
}

NOTE if using in a recursive function/twig MACRO (which probably you are) you should  removeClass all the classes you don't want in inner UL tags in a way similar to this
{{ menus.menu_links(item.below, attributes.removeClass('nav','in-navbar'), menu_level + 1) }}

old solution
function THEMENAME_preprocess_block(&$vars){
    if($vars['base_plugin_id'] == "system_menu_block"){
        if($vars['derivative_plugin_id'] == "main"){
            if($vars['configuration']['region'] == "navbar"){
                $vars['content']['#attributes']['class'][] = 'in-navbar';
                $vars['content']['#attributes']['class'][] = 'nav';
            }
            elseif($vars['configuration']['region'] == "footer"){
                $vars['content']['#attributes']['class'][] = 'in-footer';
            }
        }
    }
}

Comment: This didnt actually work for me because `['region']` was missing from the `$vars['configuration']` but https://drupal.stackexchange.com/a/218926/3167 worked.
Comment: just checked and I am not doing anything special to get region in configuration ... strange


Stored procedure stopped working

Question: I have a problem concerning a stored procedure. The stored procedure i programmed permits a third party provider to insert data into my database. It always worked fin up to 5 days ago when no data gets anymore inserted. I am really a complete rooky with respect to SQL so i do not know where to start investigating what could be the error. Any help, insights and advices are highly appreciated. Thanks in advance. Attached is the code.
create or replace PROCEDURE               "GET_DROP_COPY"
(
  P_BEGINSTRING IN VARCHAR2
, P_BODYLENGTH IN VARCHAR2
, P_MSGTYPE IN VARCHAR2
, P_MSGSEQNUM IN VARCHAR2
, P_SENDERCOMPID IN VARCHAR2
, P_SENDINGTIME IN VARCHAR2
, P_TARGETCOMPID IN VARCHAR2
, P_TARGETSUBID IN VARCHAR2
, P_AVGPX IN VARCHAR2
, P_CLORDID IN VARCHAR2
, P_CUMQTY IN VARCHAR2
, P_CURRENCY IN CHAR
, P_EXECID IN VARCHAR2
, P_SECURITYIDSOURCE IN NUMBER
, P_LASTPX IN NUMBER
, P_LASTQTY IN NUMBER
, P_ORDERID IN VARCHAR2
, P_ORDERQTY IN NUMBER
, P_ORDSTATUS IN VARCHAR2
, P_PRICE IN NUMBER
, P_ORDTYPE IN VARCHAR2
, P_SECURITYID IN VARCHAR2
, P_SIDE IN VARCHAR2
, P_FIELD55 IN VARCHAR2
, P_TIMEINFORCE IN VARCHAR2
, P_TRANSACTTIME IN VARCHAR2
, P_SETTLTYPE IN VARCHAR2
, P_TRADEDATE IN VARCHAR2
, P_EXDESTINATION IN VARCHAR2
, P_EXECTYPE IN VARCHAR2
, P_LEAVESQTY IN VARCHAR2
, P_SECURITYTYPE IN VARCHAR2
, P_SECONDARYORDERID IN VARCHAR2
, P_SECURITYEXCHANGE IN VARCHAR2
, P_ROUNDLOTBOOK IN NUMBER
, P_COPYMSGINDICATOR IN VARCHAR2
, P_REPEATING_GROUP IN NUMBER
, P_PARTY_ID IN VARCHAR2
, P_PARTYIDSOURCE IN VARCHAR2
, P_PARTYROLE IN NUMBER
, P_PARTYID2 IN VARCHAR2
, P_PARTYIDSOURCE2 IN VARCHAR2
, P_PARTYROLE2 IN NUMBER
, P_PARTYID3 IN VARCHAR2
, P_PARTYIDSOURCE3 IN VARCHAR2
, P_PARTYROLE3 IN NUMBER
, P_CHECKSUM IN NUMBER
) AS
l_count     NUMBER;
l_modpor    NUMBER(1,0);
l_logid     NUMBER;
err_num     NUMBER;
err_msg     VARCHAR2(100);

BEGIN

SELECT NVL(MAX(ID),0) INTO l_logid
FROM LOG_PROCEDURE;

IF l_logid = 0 THEN
  l_logid := 1;
ELSE
  l_logid := l_logid + 1;
END IF;

INSERT INTO LOG_PROCEDURE (ID, ETL, INICIO, TRAZA, TABLA)
VALUES(l_logid, 'GET_DROP_COPY', SYSDATE, 'INSERT RECORD. ',
'DROP_COPY');
COMMIT;

  INSERT INTO DROP_COPY (BEGINSTRING, BODYLENGTH, MSGTYPE, MSGSEQNUM,
SENDERCOMPID, SENDINGTIME, TARGETCOMPID, TARGETSUBID, AVGPX, CLORDID,
CUMQTY, CURRENCY, EXECID, SECURITYIDSOURCE, LASTPX, LASTQTY, ORDERID,
ORDERQTY, ORDSTATUS, PRICE, ORDTYPE, SECURITYID, SIDE, FIELD55,
TIMEINFORCE, TRANSACTTIME, SETTLTYPE, TRADEDATE, EXDESTINATION,
EXECTYPE, LEAVESQTY, SECURITYTYPE, SECONDARYORDERID, SECURITYEXCHANGE,
ROUNDLOTBOOK, COPYMSGINDICATOR, REPEATING_GROUP, PARTY_ID,
PARTYIDSOURCE, PARTYROLE, PARTYID2, PARTYIDSOURCE2, PARTYROLE2,
PARTYID3, PARTYIDSOURCE3, PARTYROLE3, CHECKSUM)
    VALUES(P_BEGINSTRING, P_BODYLENGTH, P_MSGTYPE, P_MSGSEQNUM,
P_SENDERCOMPID, P_SENDINGTIME, P_TARGETCOMPID, P_TARGETSUBID, P_AVGPX,
P_CLORDID, P_CUMQTY, P_CURRENCY, P_EXECID, P_SECURITYIDSOURCE, P_LASTPX,
P_LASTQTY, P_ORDERID, P_ORDERQTY, P_ORDSTATUS, P_PRICE, P_ORDTYPE,
P_SECURITYID, P_SIDE, P_FIELD55, P_TIMEINFORCE, P_TRANSACTTIME,
P_SETTLTYPE, P_TRADEDATE, P_EXDESTINATION, P_EXECTYPE, P_LEAVESQTY,
P_SECURITYTYPE, P_SECONDARYORDERID, P_SECURITYEXCHANGE, P_ROUNDLOTBOOK,
P_COPYMSGINDICATOR, P_REPEATING_GROUP, P_PARTY_ID, P_PARTYIDSOURCE,
P_PARTYROLE, P_PARTYID2, P_PARTYIDSOURCE2, P_PARTYROLE2, P_PARTYID3,
P_PARTYIDSOURCE3, P_PARTYROLE3, P_CHECKSUM);

  l_count := TO_CHAR(SQL%ROWCOUNT);

UPDATE LOG_PROCEDURE
SET FIN = SYSDATE,
        ESTADO = 'OK',
        TRAZA = TRAZA || l_count || ' REGISTRO(s) INSERTADO(s).'
WHERE ID = l_logid;

COMMIT;

IF (P_PARTY_ID IN ('009', '036', '016', '003') OR P_PARTYID2 IN ('009', '036', '016', '003') OR P_PARTYID3 IN ('009', '036', '016', '003')) AND (P_ORDERID NOT LIKE'%SER%') THEN

  IF ( P_EXECTYPE NOT IN ('0', '4') AND ((P_PARTYROLE = 7 AND P_PARTY_ID = '058') OR  (P_PARTYROLE2 = 7 AND P_PARTYID2 = '058') OR (P_PARTYROLE3 = 7 AND P_PARTYID3 = '058'))) THEN
    l_modpor := 1;
  ELSE
    l_modpor := 0;
  END IF;

    INSERT INTO EQUITY_PORTFOLIO_DCMOV
       ( BEGINSTRING, BODYLENGTH, MSGTYPE, MSGSEQNUM, SENDERCOMPID, SENDINGTIME, TARGETCOMPID, TARGETSUBID, AVGPX, CLORDID,
         CUMQTY, CURRENCY, EXECID, SECURITYIDSOURCE, LASTPX, LASTQTY, ORDERID,  ORDERQTY, ORDSTATUS, PRICE, ORDTYPE, SECURITYID, SIDE, FIELD55,
         TIMEINFORCE, TRANSACTTIME, SETTLTYPE, TRADEDATE, EXDESTINATION, EXECTYPE, LEAVESQTY, SECURITYTYPE, SECONDARYORDERID, SECURITYEXCHANGE,
         ROUNDLOTBOOK, COPYMSGINDICATOR, REPEATING_GROUP, PARTY_ID, PARTYIDSOURCE, PARTYROLE, PARTYID2, PARTYIDSOURCE2, PARTYROLE2,
         PARTYID3, PARTYIDSOURCE3, PARTYROLE3, CHECKSUM, ORIGEN, MODPOR
       )
     VALUES( P_BEGINSTRING, P_BODYLENGTH, P_MSGTYPE, P_MSGSEQNUM, P_SENDERCOMPID, TO_TIMESTAMP(P_SENDINGTIME, 'YYYYMMDD-HH24:MI:SS.FF3'), P_TARGETCOMPID, P_TARGETSUBID, P_AVGPX,
             P_CLORDID, P_CUMQTY, TRIM(P_CURRENCY), P_EXECID, P_SECURITYIDSOURCE, P_LASTPX, P_LASTQTY, P_ORDERID, P_ORDERQTY, P_ORDSTATUS, P_PRICE, P_ORDTYPE,
             P_SECURITYID, P_SIDE, P_FIELD55, P_TIMEINFORCE, TO_TIMESTAMP(P_TRANSACTTIME, 'YYYYMMDD-HH24:MI:SS.FF3'), P_SETTLTYPE, P_TRADEDATE, P_EXDESTINATION, P_EXECTYPE, P_LEAVESQTY,
             P_SECURITYTYPE, P_SECONDARYORDERID, TRIM(P_SECURITYEXCHANGE), P_ROUNDLOTBOOK, TRIM(P_COPYMSGINDICATOR), P_REPEATING_GROUP, P_PARTY_ID, P_PARTYIDSOURCE,
             P_PARTYROLE, P_PARTYID2, P_PARTYIDSOURCE2, P_PARTYROLE2, P_PARTYID3, P_PARTYIDSOURCE3, P_PARTYROLE3, P_CHECKSUM, 'LOCAL', l_modpor
           );

     SELECT COUNT(*) INTO l_count
       FROM EQUITY_PORTFOLIO
         WHERE SECURITYID = P_SECURITYID;

     IF l_count >= 1 AND l_modpor = 1 THEN
       ACTUALIZA_EQUITY_PORTFOLIO (P_ORDERID, P_SECURITYID, P_PRICE, P_ORDERQTY, P_EXECTYPE, P_ORDSTATUS, P_SIDE, TO_TIMESTAMP(P_SENDINGTIME, 'YYYYMMDD-HH24:MI:SS.FF3'), TO_TIMESTAMP(P_TRANSACTTIME, 'YYYYMMDD-HH24:MI:SS.FF3'), P_TRADEDATE, P_LASTPX, P_LASTQTY, l_modpor);
     ELSE
       IF l_count = 0 THEN

         INSERT INTO EQUITY_PORTFOLIO(SECURITYID, SECURITY_ID, ID_ISIN, POSITION, POSITION_INI, AAAAMMDD, CURRENCY)
           SELECT P_SECURITYID, EQDES.BLOOMBERG_TICKER, EQDES.ID_ISIN, 0, 0, P_TRADEDATE, CURRENCY
              FROM EQUITY_DESCRIPTOR EQDES
               WHERE ID_EXCH_SYMBOL = P_SECURITYID;
         COMMIT;

        ACTUALIZA_EQUITY_PORTFOLIO (P_ORDERID, P_SECURITYID, P_PRICE, P_ORDERQTY, P_EXECTYPE, P_ORDSTATUS, P_SIDE, TO_TIMESTAMP(P_SENDINGTIME, 'YYYYMMDD-HH24:MI:SS.FF3'), TO_TIMESTAMP(P_TRANSACTTIME, 'YYYYMMDD-HH24:MI:SS.FF3'), P_TRADEDATE, P_LASTPX, P_LASTQTY, l_modpor);

       END IF;
    END IF;
  END IF;

EXCEPTION
WHEN OTHERS THEN

err_num := SQLCODE;
err_msg := SUBSTR(SQLERRM, 1, 100);

INSERT INTO DROP_COPY_ERROR (BEGINSTRING, BODYLENGTH, MSGTYPE, MSGSEQNUM,
SENDERCOMPID, SENDINGTIME, TARGETCOMPID, TARGETSUBID, AVGPX, CLORDID,
CUMQTY, CURRENCY, EXECID, SECURITYIDSOURCE, LASTPX, LASTQTY, ORDERID,
ORDERQTY, ORDSTATUS, PRICE, ORDTYPE, SECURITYID, SIDE, FIELD55,
TIMEINFORCE, TRANSACTTIME, SETTLTYPE, TRADEDATE, EXDESTINATION,
EXECTYPE, LEAVESQTY, SECURITYTYPE, SECONDARYORDERID, SECURITYEXCHANGE,
ROUNDLOTBOOK, COPYMSGINDICATOR, REPEATING_GROUP, PARTY_ID,
PARTYIDSOURCE, PARTYROLE, PARTYID2, PARTYIDSOURCE2, PARTYROLE2,
PARTYID3, PARTYIDSOURCE3, PARTYROLE3, CHECKSUM, LOGID)
    VALUES(P_BEGINSTRING, P_BODYLENGTH, P_MSGTYPE, P_MSGSEQNUM,
P_SENDERCOMPID, P_SENDINGTIME, P_TARGETCOMPID, P_TARGETSUBID, P_AVGPX,
P_CLORDID, P_CUMQTY, P_CURRENCY, P_EXECID, P_SECURITYIDSOURCE, P_LASTPX,
P_LASTQTY, P_ORDERID, P_ORDERQTY, P_ORDSTATUS, P_PRICE, P_ORDTYPE,
P_SECURITYID, P_SIDE, P_FIELD55, P_TIMEINFORCE, P_TRANSACTTIME,
P_SETTLTYPE, P_TRADEDATE, P_EXDESTINATION, P_EXECTYPE, P_LEAVESQTY,
P_SECURITYTYPE, P_SECONDARYORDERID, P_SECURITYEXCHANGE, P_ROUNDLOTBOOK,
P_COPYMSGINDICATOR, P_REPEATING_GROUP, P_PARTY_ID, P_PARTYIDSOURCE,
P_PARTYROLE, P_PARTYID2, P_PARTYIDSOURCE2, P_PARTYROLE2, P_PARTYID3,
P_PARTYIDSOURCE3, P_PARTYROLE3, P_CHECKSUM, l_logid);

UPDATE LOG_PROCEDURE
SET FIN = SYSDATE,
            ESTADO = 'ERROR',
            CODERR = err_num,
            MSGERR = err_msg
WHERE ID = l_logid;

COMMIT;

END GET_DROP_COPY;

This is the output when i run the procedure:
Connecting to the database CLBCB_TRADER.
ORA-01400: cannot insert NULL into ("CLBCBTRADER"."DROP_COPY_ERROR"."SENDINGTIME")
ORA-06512: at "CLBCBTRADER.GET_DROP_COPY", line 155
ORA-01400: cannot insert NULL into ("CLBCBTRADER"."DROP_COPY"."SENDINGTIME")
ORA-06512: at line 98
Process exited.
Disconnecting from the database CLBCB_TRADER.
Additionally, I should mention that the "SENDINGTIME" variable always looks like this so i dont see a problem: "20141110-13:30:03.394"
Comment: There is no code? - How exactly does your client execute the procedure?
Comment: somehow i am not able to post the code. stackoverflow gives me an error message concerning the code eventhough it runs perfectly well.
Comment: Try copy paste into notepad and then copy paste from there
Comment: ok using the brackets worked
Comment: Are you using Oracle? Also, why all the VARCHAR2 parameter are declared without size? define a size for them.
Comment: yes its Oracle, I did not have to define size. As i mentioned The Stored procedure instered data with the exact code perfectly well the last two month until now.
Answer: The error is telling you that you are trying to insert a NULL value into the SENDINGTIME field of GET_DROP_COPY. The field does not allow NULL values.
Either:

Insert an actual value
Allow nulls in your column.

You should probably look to the first option as there is probably a reason for the column not allowing nulls.
Answer: Looking at the error message, it seems that parameter P_SENDINGTIME is passed as a NULL value, and this is not a value allowed in your schema definition.
It seems that your third party provider changed something in the last days.
If that parameter was just a timestamp, you could set a default value to it running your script to alter the procedure by setting a default value:
create or replace PROCEDURE "GET_DROP_COPY" (
   //...first part definition of script here

   , P_SENDINGTIME IN VARCHAR2 := ''

   //...rest definition of script here
)
   //... body of script here
END GET_DROP_COPY;

Please note that:

you should first of all ask the provider whether they changed
anything
it may be a risky approach if you aren't sure of what that value should be
you may use sysdate to get a proper timestamp value - eg:

   ...
    , P_SENDINGTIME IN VARCHAR2 := TO_CHAR(SYSDATE, 'MM.DD.YYYY HH24:MI:SS')
   ...

Comment: thanks for the insight. So , P_SENDINGTIME IN VARCHAR2 := '' will allow me to adapt to changes in for that specific field?
Comment: i will follow your steps and keep it posted here
Comment: That would be a default value: in case that parameter is passed as NULL (as it seems), it would get the value you define between quotes.

Stored procedure stopped working


Which strings should be used for smoother guitar chord formation?

Question: I am playing guitar for a year and half and till now I am not able to play barre chords smoothly as i can not form it with proper pressure and my hand starts to pain in 2 mins. What kind of acoustic strings should I use?

Is this a problem with my chord formation or the neck of guitar is bent or something else or I should use some other strings. I am using D'Addario (medium light gauge).
Answer: Your guitar may need to be "set up" properly. This means getting it into its best playing condition, and in particular, it includes adjusting the height of the strings above the fretboard (called the "action"). If the action is too high, the strings will be difficult to press down, just as you are experiencing. If the action is too low, the strings will buzz against the fretboard when you play—you don't want that, either.
You can learn how to adjust the action of your guitar yourself, but I highly recommend taking it to a professional repair shop for best results. A set up will cost around $30, and it will make a world of difference to how comfortable your guitar is to play.
Elaboration
Your guitar is like a bow (as in bow-and-arrow). The neck is a long, straight piece of wood with a very tight string attached at both ends, bending it into an arc. Obviously it's not as dramatic an arc as with a bow, but it's real nevertheless. Imagine for a moment that the arc really was as big as with a bow (meaning it would have extremely high action), and imagine trying to press the bowstring down to the bow itself as if you were playing it—that would be really, really difficult.
To help support the neck of the guitar, the neck has a steel rod inside it, called a "truss rod". This truss rod counteracts the string tension and keeps the neck from bowing too much. Because different kinds of strings exert different amounts of tension, the truss rod is adjustable, and it can be adjusted so that your guitar's neck has just the right amount of bow for your particular strings.
When you take your guitar to a professional repair person, one of the things s/he will do is adjust the truss rod until your action is just right. Different people prefer different amounts of action, so tell your repair person that you find playing chords to be uncomfortable, and s/he will make sure your action is low enough for playing chords without being too low.
Comment: @kashminder While I agree with Wheat that you should go to a professional repair person, you can also search YouTube for videos demonstrating how to set up a guitar. Here's a link to one: https://www.youtube.com/watch?v=00AnN5NMJZ4
Comment: how to screw the truss rod?
Comment: If you do not know how to adjust the truss rod already, you need to take the guitar to a professional repair person to do the job for you. Truss rod adjustments are tricky. But moreover, your guitar probably also requires modification to the nut and the bridge. The truss rod is only part of the equation.
Answer: The truss rod is only part of the story behind the action. Often all that is needed is the height adjustment of the saddles on the bridge.On electrics this is straightforward, but on acoustics (as I believe the OP has) it's more complex.It could entail shaving some off the base of the saddle, a job for the pro., or just screwing a screw either side, to take the height down.


Compras no app através da operadora

Question: Hoje em dia em meu aplicativo utilizo o sistema in-app-billing, porém gostaria de saber se há possibilidade de realizar vendas e efetuar cobranças pelo crédito da operadora do dispositivo do usuário.
Será possível? Em uma época já consegui efetuar compras pela operada.
Comment: Você teve algum progresso no assunto?
Answer: Não. Atualmente não é possivel usar compras pela operadora e partilhar do sistema in-app-billing disponivel pela google.
O que podes usar é um sistema de SMS billing onde as transações monetárias são efetuadas por SMS.
Alguns sítios pode onde pode começar:
http://en.wikipedia.org/wiki/Mobile_payment
http://www.junglepay.com/
https://secure.zaypay.com/overview

Compras no app através da operadora


Como resolver erro de syntax

Question: Um formulario com anexo que erra no envio, na linha 14. alguem ajuda
<?php
$nome = $_POST['nome'];
$arquivo = $_FILES["arquivo"];
// Para quem vai ser enviado o email
$para = "eadamaral[@]gmail.com";
$boundary = "XYZ-".date("dmYis")."-ZYX";
$fp = fopen($arquivo["tmp_name"], "rb"); // abre o arquivo enviado
$anexo = fread($fp, filesize($arquivo["tmp_name"])); // calcula o tamanho
$anexo = base64_encode($anexo); // codifica o anexo em base 64
fclose($fp); // fecha o arquivo
// cabeçalho do email
$headers  = "MIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/mixed; ";
$headers .= "boundary="$boundary"\r\n";
$headers .= "$boundary\n";
// email
$mensagem  = "--$boundary\n";
$mensagem .= "Content-Type: text/html; charset='utf-8'\n";
$mensagem .= "Nome:  $nome \r\n";
$mensagem .= "--$boundary \n";
// anexo
$mensagem .= "Content-Type: ".$arquivo["type"]."; name="".$arquivo['name']."" \n";
$mensagem .= "Content-Transfer-Encoding: base64 \n";
$mensagem .= "Content-Disposition: attachment; filename="".$arquivo['name']."" \r\n";
$mensagem .= "$anexo \n";
$mensagem .= "--$boundary \n";
// enviar o email
mail($para, $assunto, $mensagem, $headers);
?>

Comment: Não poste seu código em forma de imagem. O [pt.so] tem suporte para códigos, basta você colar seu código no editor da pergunta, selecioná-lo e pressionar o atalho `Ctrl+K`. Você pode, também, utilizar o botão `{}` do editor. Por favor, entre em [edit] e faça a alteração.
Comment: Desculpe Anderson, mas não conseguir, mesmo assim vou tentar novamente.
Comment: Então recomendo que faça antes de qualquer coisa o [tour] pelo site para aprender pelo menos o básico de como o site funciona. Nele você encontrará guias de como formatar corretamente suas perguntas e respostas.
Answer: A forma que o PHP trabalha com concatenação de strings, é a seguinte:
$var2 = "concatenado";
$var = "texto" . $var2 . "mais texto";

Perceba que há um ponto onde há o fechamento das aspas duplas e a variável. Você pode encontrar mais exemplos na documentação oficial: http://php.net/manual/pt_BR/language.operators.string.php
Uma alternativa ao uso o '.', que é relativamente criticado por programadores de outras linguagens, é concatenar dessa forma:
$var2 = "concatenado";
$var = "texto {$var2}";

Lembrando que o exemplo anterior só funcionará em strings entre aspas duplas ('"'). Aspas simples (''') não vai concatenar o valor da variável $var2, simplesmente vai aparecer "{$var2}" no fim da string.
Comment: Mesmo assim não consegui corrigir Amadeus, me ajuda nessa cara, preciso urgente dessas correções.!
Comment: @Dias na linha 14, a concatenação está feita de forma errada. Você corrigiu isso?
Comment: nao... desculpe. como faço?
Comment: @Dias, dê uma olhada na minha resposta. A sua solução está no primeiro exemplo que dei
Comment: Sou iniciante, e estou estudando PHP agora, para mim é muito recente ainda... mas entendo seu enpenho para que eu possa aprender, mas não conseguir identificar o ponto.
Answer: Na linha 14 falta "escapar" as aspas dentro "das aspas":
$headers .= "boundary="$boundary"\r\n";

Faça isto:
$headers .= "boundary=\"$boundary\"\r\n";

Também é necessário escapar as aspas na linha 22:
$mensagem .= "Content-Type: ".$arquivo["type"]."; name="".$arquivo['name']."" \n";

Deve ficar assim:
$mensagem .= "Content-Type: ".$arquivo["type"]."; name=\"".$arquivo['name']."\" \n";

Também é necessário escapar as aspas na linha 24:
$mensagem .= "Content-Disposition: attachment; filename="".$arquivo['name']."" \r\n";

Deve ficar assim:
$mensagem .= "Content-Disposition: attachment; filename=\"".$arquivo['name']."\" \r\n";

O código corrigido deve ficar assim:
<?php
$nome = $_POST['nome'];
$arquivo = $_FILES["arquivo"];
// Para quem vai ser enviado o email
$para = "eadamaral[@]gmail.com";
$boundary = "XYZ-".date("dmYis")."-ZYX";
$fp = fopen($arquivo["tmp_name"], "rb"); // abre o arquivo enviado
$anexo = fread($fp, filesize($arquivo["tmp_name"])); // calcula o tamanho
$anexo = base64_encode($anexo); // codifica o anexo em base 64
fclose($fp); // fecha o arquivo
// cabeçalho do email
$headers  = "MIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/mixed; ";
$headers .= "boundary=\"$boundary\"\r\n";
$headers .= "$boundary\n";
// email
$mensagem  = "--$boundary\n";
$mensagem .= "Content-Type: text/html; charset='utf-8'\n";
$mensagem .= "Nome:  $nome \r\n";
$mensagem .= "--$boundary \n";
// anexo
$mensagem .= "Content-Type: ".$arquivo["type"]."; name=\"".$arquivo['name']."\" \n";
$mensagem .= "Content-Transfer-Encoding: base64 \n";
$mensagem .= "Content-Disposition: attachment; filename=\"".$arquivo['name']."\" \r\n";
$mensagem .= "$anexo \n";
$mensagem .= "--$boundary \n";
// enviar o email
mail($para, $assunto, $mensagem, $headers);

Como resolver erro de syntax


Laplace smoothing and naive bayes

Question: If I want to use naive bayes with laplace smoothing and therefore add 1 to probabilities with the value of 0, what does this mean for probabilities which have the actual value of 1?
Comment: It is not clear what you are asking.
Comment: When using laplace smoothing with naive bayes, do I have to add the value 1 to all my probabilities, or just probabilities with the value of 0?
Comment: Yes I read your question but it doesn't make sense as written.
Comment: link ; perhaps the value is added to zero cells of counts (or all cells?) which are then used to estimate the probabilities, rather than adding a value to the probabilities themselves
Comment: perhaps of interest http://stats.stackexchange.com/questions/108797/in-naive-bayes-why-bother-with-laplacian-smoothing-when-we-have-unknown-words-i
Answer: A value 1 is added to each feature count (not just to the feature having a count/frequency of 0 ). To be more specific, consider the case of text classification. Let us suppose that $Y_k, k=1,2,\cdots K$ denote the labels of the $K$ classes, $X_j$ denote the $j^{th}$ word and $V$ denote the total number of distinct words(vocabulary size) in all of the $n=\sum_{k=1}^{K}n_{k}$ documents, where $n_{k}$ denote the number of documents labelled as $Y_{k}$. Then, the Laplace estimate of the probability for the word $X_{j}$ in the class $Y_{k}$ is given by
$$P(X_{j}|Y_{k})\dfrac{Count(X_{j},Y_{k})+1}{\sum_{j}^{V}(Count(X_{j},Y_{k})+1)}.$$

Laplace smoothing and naive bayes


To tell a button to parse strings of text from an uploaded .txt file in visualC#

Question: BTW, I'm new at Visual C#.
I've already got the .txt file to upload, but after I get more familiar with Visual C#, my ultimate goal is to upload a .txt file into memory, read it, parse certain parts of data strings on it, and print the data onto the webpage.
I've been looking up and down the web (maybe I should learn more before I say I can't find anything I can't understand), but I've noticed on StackOverflow, the more specific you are, the more of a detailed answer you're going to get.
I also noticed this question could be filed under a "show me teh codez". As I am learning all this, instead of "show me teh codez", I would perfer pointers in which direction I should go and how I should approach this.
Content in the .txt file
<code>_______________________________
.RES B7=121
.RES C12=554
.RES VMAX=4.7μV
_______________________________
</code>
It goes on like this for about another 50 or .RES's. I want to parse these under a while loop, but if there is a more efficient way to do so let me know.
What I want to do is parse the value before the "=" into a label, minus the ".RES " (Don't forget the space after it); and the value after the "=" into a textbox, all from a clk_btn event (in VS2010 Express, click on the button you wish to put it under in the design view and up pops the handler in the C# for it).
Remember, this is all from an uploaded text file. The file is uploaded directly into VS2010 Express' default "WebApplication1" Folder on my desktop. Again, prefer not to "show me teh codez", but give me pointers. Thanks folks.
Comment: @JohnnyDoe - I would start by writting a simple console application that reads the file in question.  Once you do that write code that uploads a file to the "website".  After you do that combine the two projects, but instead of reading a file off your computer, read the file the user within the current session uploaded that is on the "website".
Comment: You will have a lot of label and textbox or need to create them on the fly?
Comment: Lots of Labels and Text boxes is preferred.. That's why I wanted to set this up on a while loop
Comment: Why is this question tagged C# if your using VB2010?  You seem confused...If this is going to be a website then the location of the file won't be WebApplication1 as thats only used when you "launch" the website within Visual Studio.  Your question is not clear your mixing terms, go back, and make it clear what language and/or tools you want to use.
Comment: Because I'm using a C#page to make the "btn_clk" event for the .aspx page of it
Comment: @JohnnyDoe - You cannot be using VB2010 if your using C# within your .aspx page.  If you are using VB2010 Express then use VB.NET instead of C#.
Answer: If all lines start with ".RES " you can use Substring to remove those. After that you could split the string on the "=" to get two tokens. One for the label and one for the text box. Create a label and set the appropriate value to the first of the two tokens. Create a textbox and set the appropriate property with the value of the second token. Add them both to the control collection of the parent control.
(Code omitted due to the explicit wish of not being shown the code)


PXE boot windows PE from Linux

Question: I'm attempting to get a Windows Preinstallation Environment to boot over PXE from a Linux server. The end goal will be to install Windows but that's pretty easy once I can get WinPE to start up (I've got the samba share with the windows OS disk etc.). I'm using ESXi and attempting to get a VM to PXE boot the winPE but also have access to a physical machine for testing. I followed the steps on a few tutorials (http://www.tecmint.com/configure-pxe-server-to-install-windows-on-centos/ mainly) and I've reached an interesting place:
If I attempt to PXE boot the winPE on either the VM or a physical machine I get the error:
CDBOOT: Cannot boot from CD - Code 5

However, if I mount the winpe iso on the VM's disk drive it works fine (I reach the winpe and can install windows). From what I've read of the "Cannot boot from CD - Code 5" error it is most commonly associated with BIOS firmware/hardware incompatibilities, but were that true the iso shouldn't work when mounted either.
In my ./pxelinux.cfg/default I have:
MENU LABEL Windows 7
 LINUX memdisk
 INITRD windows/winpe_amd64.iso
 APPEND iso raw

I've tried both with and without appending raw with the same result. I have already copied the memdisk binary to the tftproot. The iso seems to be found when PXE booting because the iso is being read in some capacity, the ISO is placed inside the tftproot at windows/winpe_amd64.iso.
Anyone have any insight on why the PXE boot would behave differently from mounting the ISO on the drive, and any ideas on how to resolve the problem with booting the iso?
Answer: When you "mount" winpe_amd64.iso on a VM and boot from it the ISO sees itself booting from a CD/DVD drive (either real or virtual).
When you boot winpe_amd64.iso from memdisk the ISO sees an "emulated" (created by memdisk) disk environment.
APPEND iso raw

Some Windows ISO's need the 'raw' option on some PCs.
It is possible to map and boot from some CD/DVD images using MEMDISK. No-emulation, floppy emulation and hard disk emulation ISO's are supported.
The "map" process is implemented using INT 13h - any disk emulation will remain accessible from an OS that uses compatible mode disk access, e.g. DOS and Windows 9x. The emulation via INT 13h can't however, be accessed from an OS which uses protected mode drivers (Windows NT/2000/XP/2003/Vista/2008/7, Linux, FreeBSD) once the protected mode kernel drivers take control. If the OS contains drivers for accessing this mapped ISO, or knows how to find the ISO on the disk, there is no booting problem of course.
INT 13h access: Not all images will complete the boot process!
Windows NT/2000/XP/2003/Vista/2008/7 (NT based)
These Windows versions use INT 13h access only in the start of the booting process (loading only the necessary drivers). Once the protected mode drivers are functional to access the disks, Windows can't see the memory mapped drives created by MEMDISK (CD/DVD, hard disk and floppy disk images) and it will fail to complete the boot process.
Source:
http://www.syslinux.org/wiki/index.php/MEMDISK
Bottom line: memdisk is a last resource alternative. pretty unreliable. avoid it.
In your case I'd try PXE booting into pxeboot.n12 (NBP) wich later calls bootmgr.exe, bcd, boot.sdi, and finally your Boot.wim file. This is pretty much the WDS way to PXE a Windows PE envirnment.
Edit:
pxeboot.n12 can be found within Boot.wim on any Windows DVD/ISO.
Specifically from the error you get you can also be facing this kind problem.
https://superuser.com/questions/28123/when-installing-windows-7-cdboot-error-5-appears-cannot-boot-from-cd-why
Comment: but the winpe comes even before windows installation, I would think it to be able to boot if MEMDISK could even get to the start of windows installation. The way to install linux after loading winpe is to mount a network drive in the winpe that contains the windows install media and launch setup.exe. There are also many tutorials that suggest that MEMDISK can boot winpe isos, not sure that they would be so common if it was simply impossible, that said..

Can a linux PXE server launch pxeboot.12? And also where would I find this file? I do not have a WDS.
Comment: Windoes PE is "itself" a small "Windows", it loads like Windows, it uses Windows protected mode drivers, etc. what the memdisk guys say about Windows is also valid for PE. Memedisk approach as I've said before is not reliable; as they say, some PCs need the parameter "raw", while others don't, while others miserable fail. That's it. pxeboot.n12 is an "NBP" that is requested and run by the booting PXE client, it doesn't matter if the PXE server is Linux or Windows. pxeboot.n12 can be found on any Windows DVD/ISO.
Comment: Strange, I have an official windows install disk but it does not have pxeboot.n12 on it: `find ./ | grep pxe` returns nothing
Comment: it is within Boot.wim
Comment: ah, I'll mount that and take a look for it
Comment: Save time just extracting it with 7z...
Comment: The problem actually seemed to be with how I copied the winPE.iso from my windows workstation to the PXE server. I was using windows built in FTP server and the linux ftp client, and I noticed the ftp get reported the file may not have transferred fully. Tried ftp through mozilla and it PXE booted successfully
Answer: The issue I experienced was a result of a bad FTP-get, which caused the WinPE ISO I had to truly be unbootable like the error said (tested trying to boot the CD in a VM). Leaving the question in case someone finds it useful.
Answer: As Pat's answer so nicely explains, WinPE (which is windows) will fail to know about the "CD" once INT13 calls no longer are available during the boot process.
A more modern solution to this problem would be to use iPXE and wimboot

PXE boot windows PE from Linux


Problemas API Facebook

Question: Criei uma aplicação com a API do Facebook para uma empresa em que trabalho. Fato é que tudo funciona perfeitamente até a parte de Logout do usuário. Todas as vezes que você desloga, acontece o seguinte erro:

FacebookApiException Object
(
    [result:protected] => Array
        (
            [error] => Array
                (
                    [message] => An active access token must be used to query information about the current user.
                    [type] => OAuthException
                    [code] => 2500
                )

        )

Os scripts do facebook no meu index.php está da seguinte maneira:

require 'src/facebook.php';
$facebook = new Facebook(array(
'appId' => 'x42xxx7191xxxxxx',
'secret' => 'xxxxbb2ce7xxxxxx472xxxx2fxf38xxx',
'cookie' => true,
));

// See if there is a user from a cookie
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
echo ''.htmlspecialchars(print_r($e, true)).'';
$user = null;
}
}

if ($me) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl();
}

e também o seguinte código:

        window.fbAsyncInit = function() {
        FB.init({
        appId: 'getAppID() ?>',
        cookie: true,
        xfbml: true,
        oauth: true
        });
        FB.Event.subscribe('auth.login', function(response) {
        window.location.reload();
        });
        FB.Event.subscribe('auth.logout', function(response) {
        window.location.reload();
        });
        };
        (function() {
        var e = document.createElement('script'); e.async = true;
        e.src = document.location.protocol +
        '//connect.facebook.net/en_US/all.js';
        document.getElementById('fb-root').appendChild(e);
        }());

O código do meu logout está da seguinte maneira:

$logoutUrl = $facebook->getLogoutUrl();
echo 'Deslogar';

Lembrando que ele até desloga o usuário, da um refresh na página corretamente mas antes do conteúdo da página, ele informa o erro no começo do texto.
Answer: Acredito que você precisa mudar o cookie para expirar, por isso que o erro ta acontecendo. Não conheço PHP mais para o meu programa desenvolvi um algoritmo em Python que realiza o Logout. Abaixo a minha solução em Python
<code>class LogoutHandler(BaseHandler):
    def get(self):
        set_cookie(self.response, "fb_user", "", expires=time.time() - 86400)

    self.redirect("/")
</code>
Tomara que seja útil para a sua aplicação esse exemplo.

Problemas API Facebook


PHP + Jquery + JSON

Question: Tenho function que chama um ajax. Como segue abaixo:
    function verifica(){
      var meuid = $('.meuid').attr('id');
      var datas = "user="+meuid;
      $.ajax({
             type: "GET",
             url: 'sys/stream2.php',
             data: datas
          }).done(function( data ) {
            //alert(data);
            $('#nome').html(data);
          });
    }

E no stream, tenho um select para isso junto com um foreach como segue:
foreach ($gUsuarios as $usuarios) {
        $agora = $usuarios['AGORA'];
        if ($agora >= $usuarios['cUsu_Limite']) {
            echo json_encode(array('usuarioon' => $usuarios['cUsu_ID'],
                                   'status' => 'fa fa-circle-o text-red'));
        }else{
            echo json_encode(array('usuarioon' => $usuarios['cUsu_ID'],
                                       'status' => 'fa fa-circle-o text-green'));
        }

e o retorno, me apresenta assim:
{"usuarioon":"1","status":"fa fa-circle-o text-red"}
{"usuarioon":"3","status":"fa fa-circle-o text-red"}

Isso quer dizer que ele me retorna corretamente, mas o problema é: como dividir isso individualmente? Já tentei com ParseJson, mas não deu certo, creio que seja porque estou retornando um array, dentro de um foreach.
O que quero na verdade, é:
no elemento  ele mude a classe para: 'fa fa-circle-o text-green', mas pra isso preciso saber que usuário, então trago o código do usuário atrelado. Preciso setar assim:

$('#'+data.usuarioon).addClass(data.status);

Alguém já passou por isso, podem me ajudar ??
Comment: Acho que o título da pergunta deveria ser mais específico, não?
Comment: E como acha que deveria ser o título @WallaceMaxters ?? Ao que vejo o título seria simplesmente para identificar o meu problema, por isso existe o conteúdo... Algo que possa acrescentar para sanar minha dúvida ?
Comment: Está certo que o conteúdo está na pergunta, então é por isso que você precisa de um bom título. Pois outras pessoas que passarem pelo seu problema poderão pesquisar e achar.
Comment: Bruno apenas como sugestão, o titulo deve resumir o problema de forma mais curta possivel, assim quem veja sua pergunta, já entra sabendo do problema, e vai ler sua descrição para mais detalhes de como te ajuda a resolver. Não leve para o pessoal, a sugestão do @WallaceMaxters foi para te ajudar a melhorar a visibilidade da pergunta no site :)
Answer: Este problema é o mesmo do jquery ui autocomplete + php não funciona
Você está a gerar mais de um JSON.
Mude o PHP:
Troque isto:
foreach ($gUsuarios as $usuarios) {
        $agora = $usuarios['AGORA'];
        if ($agora >= $usuarios['cUsu_Limite']) {
            echo json_encode(array('usuarioon' => $usuarios['cUsu_ID'],
                                   'status' => 'fa fa-circle-o text-red'));
        }else{
            echo json_encode(array('usuarioon' => $usuarios['cUsu_ID'],
                                       'status' => 'fa fa-circle-o text-green'));
        }
}

Por isso:
$jsonAux = array();
// Algumas versões do PHP (acho que < PHP 7) exibem no erro se não houver isso!

foreach ($gUsuarios as $usuarios) {
        $agora = $usuarios['AGORA'];
        if ($agora >= $usuarios['cUsu_Limite']) {
            $jsonAux[] = array('usuarioon' => $usuarios['cUsu_ID'],
                                   'status' => 'fa fa-circle-o text-red');
        }else{
            $jsonAux[] = array('usuarioon' => $usuarios['cUsu_ID'],
                                       'status' => 'fa fa-circle-o text-green');
        }
}

echo json_encode($jsonAux);

Resultado:
[{"usuarioon":"1","status":"fa fa-circle-o text-red"},{"usuarioon":"3","status":"fa fa-circle-o text-red"}]

Enquanto isso no JQuery:
Você precisa criar um loop para executar a cada array definida acima, assim irá executar a cada vez.
function verifica(){
  var meuid = $('.meuid').attr('id');
  var datas = "user="+meuid;
  $.ajax({
         type: "GET",
         url: 'sys/stream2.php',
         data: datas
      }).done(function( data ) {

         // Cria um loop para cada array do data:
         $.each(data, function(a) {
            $('#'+this.usuarioon).addClass(this.status);
         }

      });
}

Teste-me:
Por motivos de visualização o addClass foi alterado para text!

var data = [{
  "usuarioon": "1",
  "status": "fa fa-circle-o text-red"
}, {
  "usuarioon": "3",
  "status": "fa fa-circle-o text-red"
}];

$(':button').click(function() {

  $.each(data, function(a) {
    $('#' + this.usuarioon).text(this.status);
  });

});

<x id='0'>Meu é ID 0</x>

<x id='1'>Meu é ID 1</x>

<x id='2'>Meu é ID 2</x>

<x id='3'>Meu é ID 3</x>

<x id='4'>Meu é ID 4</x>

<button>SIMULAR AJAX</button>

PHP + Jquery + JSON


Table tennis change of hand

Question: Can I change my playing hand anytime in the game? What is the specific rule for hand change in table tennis? Is it allowed to play using one paddle by holding it any of the hands?
Answer: I've looked through the rule book and there does not appear to be any rule addressing this specifically.  Since it is not addressed, it is safe to assume that it is indeed legal to change racquet hand/free hand during a game, and apparently even during a point.
There are specific rules that apply to raquet hand and others to free hand, but there is nothing specific about that being a static thing (unchanging).
Answer: In short, Yes! According to ITTF rules there is no mention of losing the point if you decide to switch your playing hand in between a rally.
However in the description of the question, you have suggested using the other hand with another paddle, that is not allowed. A player may use only one paddle during a point. In addition in case you are switching by throwing your paddle to your other hand you will not be awarded the point if the ball hits the paddle while it is in air. Throwing the paddle to win a point is not allowed and it has to be in full contact with your hand for the point to be won.
Comment: https://youtu.be/VyVrYqJXPxA
Answer: Yes, it is legal to hold the racket with two hands. During the serve you need to hold the racket with one hand, because you need to hold the ball with your other hand.

Table tennis change of hand


still confused about 12/4 time- strong and weak beats

Question: giving this a last shot, sorry if asking this question again annoys anyone, been doing lots of research and it's still bothering me
i know 12/4 time has 12 pulses and 4 beats , each beat has 3 pulses
if we're trying to make syncopated music in 12/4 time, how do we know where is strong and weak?
do we look at the level of the beat?
we know there are 4 beats, so strong-weak-medium-weak
Or below the level of the beat (within the beat)?
we know each beat has 3 pulses, so strong-weak-weak
Comment: "if we're trying to make syncopated music in 12/4 time" can you elaborate on that? "Syncopation" is a very wide concept.
Answer: 12/4 and 12/8 are, to my mind at least, basic 4/4 count wise. 1 2 3 4. As usual, 1 gets the main emphasis, 3 less so, with 2 and 4 the weaker beats.
The fact that each beat is subdivided doesn't really affect that. It's like 6/8 can be played as 1 --2--, or 123456.
Syncopation? Syncopate anything, and those emphases go out of the window. Surely that's the point of syncopation? It throws the well-known emphasised parts out, to produce other, often unexpected ones. So, anything goes.
Answer: Normally, unless differently indicated, usually slurring, 12/4 can be thought of a consisting of 4 quarter-note triplets. Your description is correct. The "outer" beats are just like 4/2: strong-weak-medium-weak. The triplets I think are about even rather than strong-weak-weak but much depends on style.
For syncopation, the composer (or arranger or editor....) will indicate stress by accents or by slurs (on a keyboard) or by beaming (if the notes have beams) or even by using (in keyboard again) several note chords on the accented beats and single notes on the other beats.
As a preference when I compose, I prefer to use 12/8 so that beaming can be used to indicate grouping; a hemiola may be beamed as 4 groups of 3 eighth notes and then 3 groups of 4eighth notes. I suppose sometime I'll write something that needs 12/4 (I have used 6/4 and 5/4 so who knows?).
Answer: Usually the beats in 12/4 are similar like in a 4/4 (emphasis on the 1st and 3rd group of the "triplets" =4 groups of 3x1/4th notes.
Even if the tune may be  off-beat, the accompaniment of the percussion (drums, bass, ev. piano chords will still be on beat.
Other syncopations can be happen by sub-groups e.g. 5+5+2 or 7+5 and any other combination of summands of 12: in this case you should transform the rhythm assignment of 12/4 and change it in the time sign that it actually represents.
With other words rhythm and time assignment are related. I wouldn't speak of 12/4 if not the beat is steady 1-2-3-4, in this case it doesn't matter what syncopations are in the melody or solo part.


PHP checking if username in multiple tables

Question: I am trying to check if a passed in username is in either one of 3 tables. If it is then it exists and will return true, or else it will return false. Currently it just returns true no matter what.
<code>$stmt = $conn->prepare("SELECT * FROM Table1 INNER JOIN Table2 INNER JOIN Table3 WHERE Table1.username = :name OR Table2.username = :name OR Table3.username = :name");
$stmt->bindParam(':name', $_POST["username"] );
$num_rows = $stmt->execute();

if ($num_rows > 0)
   {
    echo "true";
   }
 else
    {
    echo "false";
    }
</code>
Comment: why are you joining the tables? there are no appearant reasons to join 3 tables without any condition.  why don't you run 3 seperate queries?
Comment: What is the value of `$num_rows`?  From the looks of the query, it's not going to be an integer.  It's going to be a set of matching records.  I imagine that object itself will always evaluate to `true` or `> 0`.
Answer: It's way better to use UNION in that case.
<code>$sql = 'SELECT 1 FROM Table1 WHERE username = :name
        UNION
        SELECT 1 FROM Table2 WHERE username = :name
        UNION
        SELECT 1 FROM Table3 WHERE username = :name';
$stmt = $conn->prepare($sql);
$stmt->bindParam(':name', $_POST["username"] );
$qry = $stmt->execute();

if ($stmt->rowCount() == 0) {
  // no match
} else {
  // match
}
</code>
Comment: Assuming this is PDO, [$stmt->execute](http://us1.php.net/manual/en/pdostatement.execute.php) return a bool not a result set object.


read textbox inside a repeater

Question: I have 2 repeaters that print menu headers and menu items - on inside the other.
They look like this:
<asp:Repeater ID="ParentRepeater" runat="server" OnItemDataBound="ParentRepeater_ItemDataBound">
        <ItemTemplate>

                <%#DataBinder.Eval(Container.DataItem, "typenavn") %>

            <asp:HiddenField ID="HiddenField1" Value='<%# Eval("id") %>' runat="server" />
            <asp:Repeater ID="ChildRepeater" runat="server">
                <ItemTemplate>

                                <%#DataBinder.Eval(Container.DataItem, "productName") %>

                                <%#DataBinder.Eval(Container.DataItem, "pris") %>

                                <asp:HiddenField ID="HiddenField2" runat="server" />
                                <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

                </ItemTemplate>
            </asp:Repeater>
        </ItemTemplate>
    </asp:Repeater>

It's all good and fun and works.
But now I need to find the different textboxes - in the textboxes you can write how many of the different menu items you want.
I have tried many different things:
Control myControl1 = FindControl("MainContent_ParentRepeater_ChildRepeater_0_HB1_0");

And this:
foreach (RepeaterItem item in ParentRepeater.Items)
{
    if (item.ItemType == ListItemType.Item)
    {
        TextBox txt = (TextBox)item.FindControl(("MainContent_ParentRepeater_ChildRepeater_0_HB1_0")) as TextBox;
        // do something with "myTextBox.Text"
        break;
    }
}

And this:
foreach (RepeaterItem item1 in ParentRepeater.Items)
{
    if (item1.ItemType == ListItemType.Item || item1.ItemType == ListItemType.AlternatingItem)
    {
        ChildRepeater = (Repeater)item1.FindControl("ChildRepeater");

        foreach (RepeaterItem item2 in ChildRepeater.Items)
        {
            if (item2.ItemType == ListItemType.Item || item2.ItemType == ListItemType.AlternatingItem)
            {
                TextBox txt = (TextBox)item2.FindControl(("ct100$MainContent$ParentRepeater$ct100$ChildRepeater$ct100$HB1")) as TextBox; // MainContent_ParentRepeater_ChildRepeater_0_HB

             }
         }
     }
     break;
 }

And none of it work. Can anybody out there help me?? How do I get hold of my textbox inside the repeater??
Answer: The FindControl function should take the ID of the server control, not the rendered client control. You should be able to do this:
var txt = item.FindControl("TextBox1") as TextBox;
if (txt != null)
{
    // found it!
}

To adjust your code:
foreach (RepeaterItem item1 in ParentRepeater.Items)
{
    if (item1.ItemType == ListItemType.Item || item1.ItemType == ListItemType.AlternatingItem)
    {
        ChildRepeater = (Repeater)item1.FindControl("ChildRepeater");

        foreach (RepeaterItem item2 in ChildRepeater.Items)
        {
            if (item2.ItemType == ListItemType.Item || item2.ItemType == ListItemType.AlternatingItem)
            {
                 TextBox txt = (TextBox)item2.FindControl(("TextBox1")) as TextBox;
            }
        }
    }
}

Answer: First, you should use FindControl on the repeater you wish to locate a control within - for instance, ParentRepeater.FindControl("controlName") - as opposed to this.FindControl().
Secondly, you should use the ID of the control, not the Client ID - which is a different beast.

read textbox inside a repeater


Using one ethernet interface to communicate with two routers separately

Question: We have a computer that needs to communicate with two routers over one physical ethernet interface.  I know this sounds weird, but each router is actually interfaced to an Iridium L Band receiver/transmitter, and we are hoping to double our bandwidth by using two.
I would like to be able to select which link to send data over at the application level, but I'm not quite sure how to do it.  My first thought was to establish a virtual IP address in addition to the pre-configured static IP address and use two separate sockets to send() data out over each "interface" separately.  My question is, how do I make it so that only one of the routers actually routes the data out to a remote host?  The IP addresses and subnet masks of the Iridium transceivers are configurable.  Is it possible to make one transceiver only listen to the data coming from one computer IP address?  Subnets maybe?
Comment: Which OS are you using ? Are you willing to work with experimental software ?
Comment: Slackware Linux, we need absolute reliability for this application so I dont know about experimental software, but show me anyways, Im curious
Comment: I am hoping that this can be achieved within the framework of standard networking stuff :-/
Answer: Create vlan inter faces in your machine
ip link add link eth0 name eth0.1 type vlan id 10
ip link add link eth0 name eth0.2 type vlan id 20

assign ip address to eth0.1 and eth0.2 in two networks. Later you can choose which one to bind at application level.
say like this
ifconfig eth0.1 192.168.10.2/24 up
ifconfig eth0.2 192.168.20.2/24 up

Then configure your router in two networks rather than one. Your computer and the routers should be connected to trunk port in the switch. Configure your routers to be in two networks rather than same. Configure subinterfaces in routers so that they listen for vlan 10 and 20 respectively. (how exactly to do this depends on the type of router) I can give you commands only for cisco.
Comment: Thanks, this was the answer I was looking for


Prove that $f'$ is continuous, knowing that it has lateral limits

Question:
Let $f:\mathbb{R} \to \mathbb{R}$ be a differentiable function such that $f(x)-f'(x)$ is monotonic.
  Prove that $f'$ is continuous

$f(x)-f'(x)$ is monotonic, so it has finite left/right-hand limits at any point. The same can be said about $f$, because it is continuous, so $f'$ has also finite left/right-hand limits at any point $a\in \mathbb{R}$, call them $l=\lim_{x\nearrow a}f'(x)$ and $r=\lim_{x \searrow a}f'(x).$ But $f'(a)=\lim_{x \to a}\frac{f(x)-f(a)}{x-a}$, so $$f'(a)=\lim_{x \nearrow a}\frac{f(x)-f(a)}{x-a}=\lim_{x \nearrow a} f'(x)=l$$
and $$f'(a)=\lim_{x \searrow a}\frac{f(x)-f(a)}{x-a}=\lim_{x \searrow a} f'(x)=r$$
from l'Hospital rule. But this means that $f'(a)=l=r$, so $f'$ is continuous at $a$.
Is this proof ok?
Comment: Can't we apply l'Hospital rule? The numerator and denominator both go to $0$, so I replaced them with their derivatives, knowing that the latter limits exist.
Comment: Sorry I overlooked the mention of L'Hospital's Rule. It's not one of my favorite tools. But then your solution is correct /rigorous.
Comment: How do the second equalities (in each line) come about?
Comment: I would just add that as an explanation. Otherwise, good. Nvm. I just saw that. My oversight. Sorry.
Comment: Alright, thank you very much!
Comment: No, your proof is not correct.
Comment: @ GhD Can you please point out which part is wrong?
Comment: @GhD The proof is good.
Comment: $\lim_{x \nearrow a}\frac{f(x)-f(a)}{x-a}=\lim_{x \nearrow a} f'(x)$ this is completely wrong.
Comment: By Darboux theorem derivatives can't have simple discontinuity. So if the lateral limits for $f'$ exist they must be equal to the value of $f'$ and thus it is continuous.
Comment: Your approach has a minor flaw. You need to write $\lim_{x\to a^{-}} f'(c_x)=l$ where $x<c_x<a$ via mean value theorem.
Comment: Thank you for your response! But isn't it quite the same as what I did with l'Hospital? I just applied it for left/right-hand sides, and according to  https://math.stackexchange.com/q/1523407 it should be fine.
Answer:
Hint:

We know that men value theorem is true for $f'$. Now use proof by contradiction and suppose $f'$ is not continuous. You should find use of continuity of $f$ and discontinuity of $f'$, then you will find $f(x)-f'(x)$ non-monotonic.


Optimal binning methods for categorical variables

Question: I'm running a multinomial logit to predict the outcome of a categoric response variable.
I have both continuous and categoric independent variables, and I know it's bad practicde to bin the continunous ones.
For the categoric, however, I've seen it's very used (and it makes sense, specially since I have a lot of observations) to make dummies out of the n-1 categories. I also don't have too many categories in each categoric variable (less than 20), and not many categoric variables in total.
But I was wondering which is better: to simply make dummies for the n-1 categories, or to create bins using any binning method, like IV, WoE, Chi square, KS?
Intuitively I feel like creating dummies would be better since you're capturing precisely the effect of each category, while with the bins you're always losing a bit of predictive power because you're joining them.
Comment: See https://stats.stackexchange.com/questions/146907/principled-way-of-collapsing-categorical-variables-with-many-levels
Comment: I wouldn't state that binning a continuous variable is always a bad practice. It depends.
Comment: Yeah, "always" is never true haha but most of the times. The thing is that for my study I decided that it is not suitable.
Comment: By common definition, binning aka discretization aka categorization is for continuous variables only. What you are asking about categorical variables is combining them into bigger, fewer categories. This should go with tag [many-categories], I might suggest.
Comment: ah, thank you! I have always called it the same for both types of variables. Just changed the tags.
Comment: "Predictive power" attained with many dummies (or categories, or predictors) is prone with overfitting, and it consumes many df's when it comes for inference. Joining similar categories is often a way to go. There are many methods of it, including such one as CHAID tree. Another one is optimal quantification (such as in Categorical Regression) which goes the opposite direction: it turns variables with many categories into few continuous variables.
Answer: Note there's already a number of good questions on this topic, like this one or this one.
In those, some alternative options to one-hot-encoding (aka dummy variables) are mentioned. These include to allow for partial pooling (i.e. especially rare classes would be pulled towards being an average category, while large classes that do have a lot of data showing different behavior than other classes end up being "alllowed to be different") using random effects.
Another option that's also mentioned in one of the answers is target encoding. This is also very popular on Kaggle. To adapt this for multinomial logistic regression, you could in the regression equation for each target category have a covariate that target encodes that target category. I.e. you create a covariate that captures for what proportion of cases this class level has resulted in this target category, but you shrink these proportions towards the overall proportion (and possibly even the proportion for each target category towards an equal proportion for all target categories). The extent of shrinkage is a tunable hyperparameter.
If there's some sensible way of doing it, you could also consider finding a suitable embedding for the features. E.g. one can create these using some pre-training task (e.g. like one creates Word2Vec/GloVe etc. word embeddings), or one could project properties of the classes (assuming you know them) into a low dimensional space using some technique like UMAP or t-SNE. However, both of those options require some extra information and might not always be possible. If you train a neural network for tabular data, you could of course create (or fine-tune) these as you train on your target task - or even train on that task and then use these embeddings in another model.
Answer: As @ttnphns indicates in the comments, you are asking whether you should collapse categories of a categorical variable into fewer "levels" of the category.  There is nothing wrong with this approach and is sometimes a necessity.  For example if you have a categorical variable with, say, 1000 categories, but you can logically collapse these into a only two categories that makes sense in the context of your analysis, then you should do so.  Indeed, using the original 1000 categories, generally uses $p-1=999$ degrees of freedom in your model.  However, if you then collapse these categories into only 2 categories, this will consume only a single degree of freedom:  you model will then only contain 1 dummy variable in your model, rather than 999 dummy variables.
Comment: I forgot to write that there aren't many categories (less than 20) in any of my categoric variables. And I have a lot of observations (17000+) so I don't think the degrees of freedom in this case would be a problem. Do you have any suggestion for the method to choose for collapsing the categories?
Comment: I doesn't really matter if you have a lot of categories.  If the intent of your model is for it to be descriptive, rather than predictive, I'd argue for collapsing categories if it makes sense from a contextual perspective.  If your intent is purely predictive, then I'd chose the method that results in the smaller mean squared predicted error.