Como eu faço para colocar um select dentro do while?

Question: Uso Sublime text, Mysql Workbench e Xampp.
Eu fiz um inner join no select abaixo, em uma tabela chamada Organizacoes.Copia. Nessa tabela tem um campo chamado "id" e eu preciso que ele apareça nesse código do Php.
Vi vários vídeos e exemplos, e não consegui fazer. Como eu coloco pra que puxe a cópia desses clientes que retornam na minha variável "$result"? Como incluo isso no while?
Segue o código pronto:
<?php

$servidor = '****';
$user = '****';
$senha = '****';
$banco = 'Organizacoes';

// Cria conexão
$conn = new mysqli($servidor, $user, $senha, $banco);
// Checa conexão
if ($conn->connect_error) {
    die("Conexão falha: " . $conn->connect_error);
}

$sql = "SELECT   Org.id
        ,Org.nome
        FROM Organizacoes as Org

        INNER JOIN Organizacoes.Rel_Organizacoes as Grupo on Org.id = Grupo.id_Organizacao
        INNER JOIN Organizacoes.Copias as Copia on Org.id = Copia.id_Organizacao

        WHERE  Grupo.id_grupo = 210
        GROUP BY Org.id
        ORDER BY Org.id";

$result = $conn->query($sql);

echo "
";

if ($result->num_rows > 0) {
    // dados de saída de cada linha
    while($row = $result->fetch_assoc()) {
        echo "id: " . $row["id"]. " - nome: " . $row["nome"]. " " . "
";
    }

} else {
    echo "0 results";
}
$conn->close();

?>

Comment: Traz, ela trás o nome de cliente e o código dele.. Essa "cópia" é um id, mas de outra tabela. Mas não consigo incluir esse campo "Id.Copia nesse while atual.
Comment: Então, na verdade eu tirei pra postar aqui porque não consigo montar no while.. Se eu colocar na minha variável $result select Org.id
        ,Org.nome , Copia.id .. Como eu vou colocar pra ele aparecer no while? Como que eu estruturo? Essa parte que to tendo dificuldade sabe?
Comment: Ficarei muito grata.. Percebi que é a dúvida de muitos iniciantes em php.
Comment: Então eu adiciono o id.copia na minha variável $result, e coloco o "var_dump ($result) " depois do while? Onde eu deixo ele?
Comment: Teria como eu colocar uma "query2" com "$result2" dentro desse while? Ou você acha que é melhor fazer do jeito que vc disse?
Comment: Deu em partes.. Ele puxou a cópia, mas substituiu meu outro id de clientes..
Comment: Mas como vou fazer isso? Se eu alterar o nome ele dá erro: Notice: Undefined index: ['id_copia'] in C:\xampp\htdocs\query.php on line 29
Comment: O nome dos campos são iguais, mas as tabelas são diferentes. TabA.id, TabB.id.. Entendeu?
Comment: a query traz os resultados?
Comment: é porque vc não pediu pro select trazer ele
Comment: apaguei sem querer, meu mouse ta no fim da vida ja
Comment: chama o id que vc quer e da um `var_dump($result)` e veja como ficou a estruturação
Comment: pode ser antes do while, desde que seja dps que $result apareceu
Comment: Deu certo o var_dump?
Comment: então o problema esta na nomenclatura dos campos das tablas, esta com nomes iguais, basta alterar
Comment: assim vc consegue separar dentro do $row['id_copia'] do $row['id']
Comment: Poste o retorno do var_dump
Answer: Bom dia, você poderia usar essa solução. Não sei se no php estaria correto, mas na query pode ser essa solução.
<?php

$servidor = '****';
$user = '****';
$senha = '****';
$banco = 'Organizacoes';

// Cria conexão
$conn = new mysqli($servidor, $user, $senha, $banco);
// Checa conexão
if ($conn->connect_error) {
    die("Conexão falha: " . $conn->connect_error);
}

$sql = "SELECT Copia.*,  Org.id
    ,Org.nome
    FROM Organizacoes as Org

    INNER JOIN Organizacoes.Rel_Organizacoes as Grupo on Org.id = Grupo.id_Organizacao
    INNER JOIN Organizacoes.Copias as Copia on Org.id = Copia.id_Organizacao

    WHERE  Grupo.id_grupo = 210
    GROUP BY Org.id
    ORDER BY Org.id";

$result = $conn->query($sql);

echo "
";

if ($result->num_rows > 0) {
    // dados de saída de cada linha
    while($row = $result->fetch_assoc()) {
    echo "id: " . $row["id"].  "id_Copia: " . $row["Copia.id"]. " - nome: " . $row["nome"]. " " . "
";
    }

} else {
    echo "0 results";
}
$conn->close();

?>

Comment: Então, no mysql a query até funciona.. Mas puxaria todos os dados da tabela cópia, e eu precisava só do id.

No php, ele dá erro: Notice: Undefined index: Copia.id in C:\xampp\htdocs\query.php on line 39
id: 1044 id_Copia: - nome: EXEMPLO CLIENTE 1
Answer: Pode fazer assim
$sql="
    SELECT
        Copia.id AS copia_id,
        Org.id,
        Org.nome
        FROM Organizacoes as Org

        INNER JOIN Organizacoes.Rel_Organizacoes as Grupo on Org.id = Grupo.id_Organizacao
        INNER JOIN Organizacoes.Copias as Copia on Org.id = Copia.id_Organizacao

        WHERE  Grupo.id_grupo = 210
        GROUP BY Org.id
        ORDER BY Org.id";

$result = $conn->query($sql);

echo "
";

if ($result->num_rows > 0) {
    // dados de saída de cada linha
    while($row = $result->fetch_assoc()) {
        echo "id: " . $row["id"]. " copia-id: " . $row["copia_id"]. " - nome: " . $row["nome"]. " " . "
";
    }

} else {
    echo "0 results";
}

Comment: Deu certinho Wess Smith.. Resultado: id: 110 copia-id: 8451 - nome: CLIENTE 2.  Posso só fazer uma última pergunta?
Comment: Essa id_copia, eu preciso do id mais recente. Sabe me indicar alguma função que eu possa usar? Eu até tentei o max(id_copia), mas ele respeita somente pra alguns..
Comment: claro, quando quiser
Comment: ORDER BY Org.id, Copia.id DESC
Comment: Respeita em alguns somente.. Quando você me orientou a utilizar o var_dump ele puxou certinho
Comment: como assim em alguns?
Comment: Por exemplo, tenho o Cliente 5.. Esse cliente tem duas copia.id. (Uma de 2011 e outra de 2018). Ele mostra Cliente 5 - E a cópia de 2011. Daí tem o Cliente 2 que tem duas cópias tbm (2015 e 2017). Dai ele mostra: Cliente 2 - Copia de 2017 (correta, pq é a última).. Entendeu?
Comment: entendi sim, mas na tabela o id do 2011 ta menor ou maior q 2018?
Comment: confirma, porque as vezes é esse o BOzinho
Comment: Então, o id dá de 2011 é 1195.. E o id da de 2018 é 1660. As duas atreladas ao Cliente 5.
Comment: tenta colocar um ORDER BY Org.id, Copia.id DESC LIMIT 1
Comment: Com o Limit 1 ele só vai puxar 1 único cliente.. Coloquei no where pra ser o "Cliente 5" que está com esse problema e ele continua puxando a cópia de 2011. Estranho ele não respeitar né..
Comment: sim, mto estranho, porque como vc colocou DESC ele ja automaticamente pegaria o ultimo
Comment: Pois é.. Tentei e estou tentando várias maneiras e não dá certo.


VS consider ' as a comment note formula

Question: I am trying to open a excel file in vb.net with excel interop
then add a formula to F2 then save as excel as csv
Can someone point me how to concatenate an ' with number in a formula cs when i write ' the Visual studio consider it as a comment not a formula
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
    Dim newFileName As String = "Libanpost" + Date.Today.ToString("ddMMyyyy") + ".csv"
    Dim oExcelFile As Object

    Try
        oExcelFile = GetObject("c:\database", "Excel.Application")
    Catch
        oExcelFile = CreateObject("Excel.Application")
    End Try

    oExcelFile.Visible = True
    Dim strfilename As String = "Libanpost" + Date.Today.ToString("ddMMyyyy") + ".xls"
    Dim strFolderPath As String = "c:\database"

    oExcelFile.Workbooks.Open(strFolderPath + "\" + strfilename)
    Dim oExcelsheet As Excel.Worksheet
    oExcelsheet = oExcelFile.sheets("table1")
    oExcelsheet.Range("f1").Value = "CRC"
    oExcelsheet.Range("f2").Formula = " = IF(LEN(A2)=2,(CONCATENATE("'00000",A2)),IF(LEN(A2)=3,CONCATENATE("'0000",A2),IF(LEN(A2)=4,CONCATENATE("'000",A2),IF(LEN(A2)=5,CONCATENATE("'00",A2),IF(LEN(A2)=6,CONCATENATE("'0",A2),A2)))))"

    oExcelFile.DisplayAlerts = False

    oExcelFile.ActiveWorkbook.SaveAs(Filename:=strFolderPath + "\" + newFileName, FileFormat:=Excel.XlFileFormat.xlCSV, CreateBackup:=False)

    oExcelFile.ActiveWorkbook.Close(SaveChanges:=False)

    Dim file_count As Integer = File.ReadAllLines(strFolderPath + "\" + newFileName).Length
    MsgBox(file_count)

    oExcelFile.DisplayAlerts = True

    oExcelFile.Quit()

    oExcelFile = Nothing

Comment: possible duplicate of [Escaping single quote in String.Format()](http://stackoverflow.com/questions/1351074/escaping-single-quote-in-string-format)
Comment: Use two single quotes, `''`.
Answer: The problem is that you have included double quotes (") inside your string literal. The first double quote inside the string is taken to mean the end of the string. It happens to be followed by a single quote which indicate the start of a comment. If you include a double quote inside a string literal, you need to have two of them. Here is the corrected statement (I split it over three lines for readability).
oExcelsheet.Range("f2").Formula = "=IF(LEN(A2)=2,(CONCATENATE(""'00000"",A2))," _
  & "IF(LEN(A2)=3,CONCATENATE(""'0000"",A2),IF(LEN(A2)=4,CONCATENATE(""'000"",A2)," _
  & "IF(LEN(A2)=5,CONCATENATE(""'00"",A2),IF(LEN(A2)=6,CONCATENATE(""'0"",A2),A2)))))"

VS consider ' as a comment note formula


Why was Chattanooga the host of the 2015 NPSL National Championship game?

Question: On August 8th, 2015, Chattanooga FC played host to the NPSL final game at Finley Stadium in Chattanooga, TN.
However, they finished with a lower points per game record than their opponents the New York Cosmos B.
Why was Chattanooga allowed to host the game?
Answer: According to the Chattanooga FC Website, New York Cosmos B did indeed have the better record, and therefore right of refusal for home-field advantage, but they agreed to play the match in Chattanooga.

Immediately following Saturday's matches, work began to determine the
  best location for the 2015 Championship game. While their #1 seed
  gives the NY Cosmos B the right of refusal for home-field advantage,
  Chattanooga was able to secure the home field advantage, with the
  Championship to be played at Finley Stadium's Davenport Field on
  Saturday, August 8 at 7:30pm.

They also give a couple of reasons why NY Cosmos agreed to this, which could be summarized as "bums on seats".

While there were a number of factors at play, according to CFC board
  member Tim Kelly, one of the most persuading arguments to bring the
  game to Chattanooga was the combination of a world-class soccer
  facility and the strongest fan base in the NPSL.
"In a league where most teams enjoy the regular support of a few
  hundred fans, our fan-base here Chattanooga is envied—and our
  partnership with Finley stadium insures a great experience for fans
  and players alike. Teams want to play here."

Reading between the lines, especially the words "work began" in the first quote, I think that means that the teams negotiated that a share of that gate money (18,227 fans attended, a national record for an amateur match) went also to NY Cosmos B, and this share was more than they would have got by holding the match at home.


Does the redirect_uri param for the access token have to be the same as the one used for the request token

Question: I apologize in advance for some confusion over the terminology. I get a bit confused with the whole OAUTH process.
I've noticed that I need to pass a redirect_uri to the facebook grant access token method even though I can't see how it's being used. My server is making the request and getting the response so there is no redirect going on. Plus it seems that the redirect uri in the granting access token call must be the same one used in the request access token call (I understand that it's needed in the request access token call but not in the grant access token call).
Not sure this is needed but here is the code I'm using in order to get facebook to grant the access token.
<code>    var url = String.Format(
      "https://graph.facebook.com/oauth/access_token?client_id={0}&client_secret={1}&code={2}&redirect_uri={3}",
      this.AppId,
      this.AppSecretKey,
      code,
      System.Web.HttpContext.Current.Server.UrlEncode(this.CallbackUrl)
     );
</code>
Answer: Yes, to help Facebook verify the request to exchange the auth code for an access token, the redirect_url must be the same for both requests.
You're right in that to get the access token, no actual redirect is performed, the access token is returned in the body of the HTTP response.


Invocar component dentro de outro component - laravel

Question: Preciso chamar um component dentro de outro no blade em laravel.
Suponhamos que possuo o seguinte component
<x-component />

Então no arquivo de component eu declaro:

Titulo normal

  <x-subcomponent prop1 prop2 />

testando

Porém x-subcomponent não é renderizado enquanto que component é.
Answer: Você pode usar a diretiva @include para incluir um componente dentro de outro componente no Blade.

Titulo normal

  @include("components.seu-componente", ["prop1" => "foo", "prop2" => "bar"])

testando


Integral inequality (Cauchy-Schwarz)

Question: Let $u\in \mathcal{C}^1[a,b]$ be such that $u(a)=u(b)=0$. Show that
$$\int_a^b u^2(x)dx\leq (b-a)^2\int_a^b (u')^2(x)dx$$
using the Schwarz's inequality.
Comment: This is a possible duplicate. But, I don't seem to find the same question which was asked earlier.
Comment: The condition $u(b)=0$ is not needed.
Answer: We have  $|u(x)|\leq \int_a^x|u'(t)|dt\leq \sqrt{x-a}\sqrt{\int_a^b|u'(t)|^2}dt$ so
$$u(x)^2\leq (x-a)\int_a^bu'(t)^2dt$$ and integrating
$$\int_a^bu(x)^2dx\leq \frac{(b-a)^2}2\int_a^bu'(t)^2dt.$$

Integral inequality (Cauchy-Schwarz)


RainTPL não renderiza o HTML

Question: Estou tendo um problema ao usar o RainTPL, ele não renderiza o HTML na página.
//Função que eu pego os dados do banco e retorno.

public static function listAll()
{
    $sql = new Sql();
    return $sql->select("SELECT * FROM tb_users a INNER JOIN tb_persons b
    USING(idperson)");
}

-----------------------------------------------------------------

//Rota responsável por mandar os dados para o template users.

$app->get('/admin/users', function(){
User::verifyLogin();
$users = User::listAll();
$page = new PageAdmin();
$page->setTpl("users", array("users"=>$users));
});

-----------------------------------------------------------------

//Funções responsáveis por chamar o template e jogar os dados nele.

private function setData($data = array())
{
    foreach ($data as $key => $value) {
        $this->tpl->assign($key, $value);
    }
}
public function setTpl($name, $data = array(), $returnHTML = false)
{
    $this->setData($data);
    return $this->tpl->draw($name, $returnHTML);
}

-----------------------------------------------------------------

//O Template onde deveria ser renderizado o HTML

{loop="$users"}

              {$value.iduser}
              {$value.desperson}
              {$value.desemail}
              {$value.deslogin}
              {if="$value.inadmin == 1"}Sim{else}Não{/if}

                <button class="btn btn-xs btn-primary">Editar</button>
                <button class="btn btn-xs btn-danger">Excluir</button>

          {/loop}

Answer: Nos parâmetros de configuração você deve informar que "auto_escape" => false, ficando mais ou menos assim:
    // config
    $config = array(
        "tpl_dir"       => $_SERVER['DOCUMENT_ROOT'].$tpl_dir,
        "cache_dir"     => $_SERVER['DOCUMENT_ROOT']."/views/views-cache/",
        "auto_escape"   => false,
        "debug"         => false
    );

RainTPL não renderiza o HTML


If $X=\{x\}$, then $\dim(X)=0$

Question: If $X$ is a quasiprojective variety, then by definition $\dim(X)=trdeg(k(X)|k)$.
I'm trying to prove if $X=\{x\}$ is a point, then $\dim(X)=0$
I'm already proved that $k[X]\cong k$, now if I prove $k(X)\cong k[X]$, I'm done.
I'm almost sure it's just a simple argument, if someone has some idea or hint how to proceed I would really appreciate.
Thanks in advance
Comment: This "definition" is rather a characterization which holds in that very special case. See any good text on algebraic geometry which gives the correct definition of the dimension, measuring the lengths of chains of irreducible closed subsets. In any case it is trivial that a point is $0$-dimensional ...
Comment: @MartinBrandenburg yes, I know, the book I'm using is based on Shafarevich's book which defines dim(X) as trdeg(k(X)|k) and leaves the usual definition using lengths of chains as a theorem.
Answer: $k(X)$ is the field of fractions of $k[X].$ What is the field of fractions of the field $k?$
Comment: Of course it's isomorphic to $k$, since $k$ is a field. Thank you very much
Comment: I don't know, $k$ itself? why?
Answer: That's not the usual definition of dimension. What you state as a definition is probably a theorem to most people.
If you're familiar with the usual definition, then it's pretty clear that the maximal chain of irreducible closed subsets of $\{x\}$ is just the one-step chain $\{x\}$.
Comment: yes, I know, the book I'm using is based on Shafarevich's book which defines dim(X) as trdeg(k(X)|k) and leaves the usual definition as a theorem.

If $X=\{x\}$, then $\dim(X)=0$


How do I iterate through a vector of maps

Question: I code for fun. I created a vector of maps to see what I can do with containers. When I iterate through the vector, only Alfred and Angela show up. How do I display all the names? Is it even possible? Here is what I have so far:
#include <map>
#include <iostream>
#include <conio.h>
#include <vector>
#include <string>

int main()
{
    //create a map
    std::map<std::string, unsigned int> mySuperCoolMap;
    mySuperCoolMap["Edward"] = 39;
    mySuperCoolMap["Daniel"] = 35;
    mySuperCoolMap["Carlos"] = 67;
    mySuperCoolMap["Bobby"]  =  8;
    mySuperCoolMap["Alfred"] = 23;

    std::cout << "\n\n";

    //Ranged based for loop to display the names and age
    for (auto itr : mySuperCoolMap)
    {
        std::cout << itr.first << " is: " << itr.second << " years old.\n";
    }

    //create another map
    std::map<std::string, unsigned int> myOtherSuperCoolMap;
    myOtherSuperCoolMap["Espana"]  =  395;
    myOtherSuperCoolMap["Dominic"] = 1000;
    myOtherSuperCoolMap["Chalas"]  =  167;
    myOtherSuperCoolMap["Brian"]   =  238;
    myOtherSuperCoolMap["Angela"]  = 2300;

    //Display the names and age
    for (auto itr : myOtherSuperCoolMap)
    {
        std::cout << itr.first << " is: " << itr.second << " years old.\n";
    }

    //create a vector of maps
    std::vector<std::map<std::string, unsigned int>> myVectorOfMaps;

    myVectorOfMaps.push_back(mySuperCoolMap);
    myVectorOfMaps.push_back(myOtherSuperCoolMap);

    std::cout << "\n\n";

    //Display the values in the vector
    for (auto itr : myVectorOfMaps)
    {
        std::cout << itr.begin()->first << " is: " << itr.begin()->second << " years old.\n";
    }

    _getch();
    return 0;
}

Comment: Perhaps a nested loop? So first loop over the vector then inside that loop over the maps.
Comment: (side-note:) best to avoid `conio.h` altogether and if you need to hold the terminal open under windows, simply use `getchar()` which is part of the standard C library.
Comment: Naming: `for (auto itr : mySuperCoolMap)`: `itr`is not an iterator, but a value (a pair in your case), `p` is so a better name than `itr`. (In C++17, you might even do `for (const auto& [name, age] : mySuperCoolMap)`).
Answer: You need to use nested loops. Using a debugger and printing itr can possibly give this intuition to you if you are learning new concepts.
//Display the values in the vector
for (const auto &vec : myVectorOfMaps)
{
    for (const auto &p : vec)
    {
        std::cout << p.first << " is: " << p.second << " years old.\n";
    }
}

Demo
You are asking to print only first element that is why you get first element only. Note that this is a bug because you are accessing first element of map without ensuring whether map is non-empty or not.

Note that <conio.h> is not a standard header and may not be available for standard platforms
Comment: Your loops should iterate using references to avoid making copies of all the objects involved: `for (auto &vecitr : myVectorOfMaps) { for (auto &mapitr : vecitr) { ... }`
Comment: Thank you so much. I got it to work with your suggestion @GyaptiJain.
Comment: Thank you @RemyLebeau. I always forget about those references.
Answer: The object you obtain in the for loop is an std::map. So you need to use another for loop to go through all the entries in each map.


Prism RequestNavigate does not work

Question: In each view
public partial class View2 : UserControl, IRegionMemberLifetime, INavigationAware
{

  public bool KeepAlive
  {
    get { return false; }
  }

  bool INavigationAware.IsNavigationTarget(NavigationContext navigationContext)
  {
    return true;
  }
  void INavigationAware.OnNavigatedFrom(NavigationContext navigationContext)
  {
    // Intentionally not implemented.
  }
  void INavigationAware.OnNavigatedTo(NavigationContext navigationContext)
  {
    this.navigationJournal = navigationContext.NavigationService.Journal;
  }

}

Initialize:
container.RegisterType<object, View1>("View1");
container.RegisterType<object, View2>("View2");

regionManager.RequestNavigate("Window1", new Uri("View1", UriKind.Relative));
regionManager.RequestNavigate("Window2", new Uri("View2", UriKind.Relative));

I am following the developer guide, it does not change the view if view exists.
Comment: in developer guide, it write in this way, i do not know which base interface, does you mean IModule?
Comment: Should you not be registering your types against base interfaces rather than against the `object` type?
Comment: Which developer guide are you referring to?
Comment: Microsft official developer guide
Comment: @Dan Puzey http://blogs.msdn.com/b/kashiffl/archive/2011/03/10/prism-4-region-navigation-with-silverlight-frame-navigation-and-unity.aspx
Comment: In your question i found answer to my question=) Thanks!
Answer: Are you sure the view gets populated by the container?
I would suggest you to provide a callback for the RequestNavigate method, so you'll be able to track what happens with your view thru the NavigationResult:
regionManager.RequestNavigate
(
    "Window1",
    new Uri("View2", UriKind.Relative),
    (NavigationResult nr) =>
    {
        var error = nr.Error;
        var result = nr.Result;
        // put a breakpoint here and checkout what NavigationResult contains
    }
);

Comment: After 7 years, and I'm thinking let's upvote this answer. Was simple and helped me tackle the issue easily, then I figure I'm the one who answered it...
Comment: https://www.reddit.com/r/ProgrammerHumor/comments/19bcozs/goingfullcircle/
Answer: I have seen that if I implement IConfirmNavigateRequest and do not call continutationCallback(true), the navigation fails quietly.
public void ConfirmNavigationRequest(NavigationContext navigationContext, Action<bool> continuationCallback)
    {
        //***Should have actual logic here
        continuationCallback(true);
    }

While this may not be your case, I figured this out by debugging through the Prism code.  I would suggest you do this to figure out your issue.  Delete the references to the following in each relevant project.

Microsoft.Practices.Prism
Microsoft.Practices.Prism.Interactivity
Microsoft.Practices.Prism.MefExtensions
Microsoft.Practices.Prism.UnityExtensions

Then add the projects from the PrismLibrary DeskTop, Silverlight or Phone directory (where you installed PRISM).  Then reference these projects.
Comment: Thanks! That was exactly my problem, which I justed wasted an hour on.
Answer: This is your problem:
bool INavigationAware.IsNavigationTarget(NavigationContext navigationContext) => true;

If you want a new view to be created and added to your region each time you call RequestNavigate(), IsNavigationTarget() must return false instead of true.

Prism RequestNavigate does not work


How can I set a View contextual filter fallback?

Question: Ok I have 2 content-types:

Page
Video

I have a block in the sidebar that shows videos embed by youtube.
In the Video content-type, I have a Node References field that can reference any Page-type node.
I would like to set up the sidebar block View so that it can output a random video-type tagged with the current page-type node, however if there are no video-type nodes referencing the current page, or if the current page is not a page-type node, then it would select ONLY  video-type nodes that are either (depending on what is simpler to implement):

Have another field on the video-type which can tag the node as "global" (this would be preferable)
OR Not referencing any page-type nodes

I was hoping to try and make use of the Context module, but I'm wondering whether the module is quite so granular or conditional?
Thanks!
Answer: Ok, decided to write my own context condition plugin for this, all in a single file for a custom module that would be called custom_context:
function custom_context_context_registry() {
  $registry = array(
    'conditions' => array(
      'views_result' => array(
        'title' => t('Views Results'),
        'description' => t('Set this context when one of these views returns a result.'),
        'plugin' => 'custom_context_condition_views_result',
      )
    )
  );
  return $registry;
}

function custom_context_context_plugins() {
  $plugins = array();
  $plugins['custom_context_condition_views_result'] = array(
    'handler' => array(
      'class' => 'custom_context_condition_views_result',
      'parent' => 'context_condition',
    ),
  );
  return $plugins;
}

function custom_context_init(){
  if ($plugin = context_get_plugin('condition', 'views_result')) {
    $plugin->execute();
  }
}

class custom_context_condition_views_result extends context_condition {

  /**
   * Generate a list of database and module provided views.
   */
  function condition_values() {
    $enabled_views = array();

    $views = views_get_all_views();
    ksort($views);

    foreach ($views as $view) {
      if (!isset($views[$view->name]->disabled) || !$views[$view->name]->disabled) {
        $displays = array();
        foreach ($view->display as $id => $display) {
          $displays[$view->name . ":" . $id] = check_plain("{$view->name} : {$display->display_title}");
        }
        $enabled_views += $displays;
      }
    }
    return $enabled_views;
  }

  function execute() {

    $view_name_displays = array();

    // Gather all required views for checking, to prevent duplicate checking
    foreach ($this->get_contexts() as $context) {
      foreach ($context->conditions['views_result']['values'] as $view_name_display){
        $view_name_displays[$view_name_display] = $view_name_display;
      }
    }

    foreach($view_name_displays as $view_name_display){
      list($view_name, $view_display) = explode(':',$view_name_display);
      $view = views_get_view($view_name);
      $view->set_display($view_display);
      $view->build();
      $view->execute($view->current_display);
      if(count($view->result)){
        foreach ($this->get_contexts($view_name_display) as $context) {
          $this->condition_met($context, $view_name_display);
        }
      }
    }
  }
}

Just to explain how this works, it loads all the views which context module should check on hook_init and checks whether each view has rows or not. I've combined this with certain views which obtain their contextual filters from the current node ID.


Arredondar números em C# sendo a casa decimal 0 ou 5

Question: Eu preciso arrendondar números de tal forma que tenham somente uma casa decimal valendo 0 ou 5.
Por exemplo
1 -> 1
1.1 -> 1.5
1.4 -> 1.5
1.5 -> 1.5
1.6 -> 2
2 -> 2

Alguém sabe de um jeito simples de fazer isso?
Comment: A solução do @mgibsonbr ficou melhor do que a minha para casos gerais. (Eu apenas armazenaria o resultado de `x - y` em uma variável temporária, para evitar repetir o cálculo 3 vezes)
Comment: @carlosrafaelgn Bem observado! Na prática, *acho* que o compilador faria isso por si só, mas não custa deixar explícito...
Comment: Como exatamente é essa regra? Acima de um inteiro `X`, arredonda pra `X.5`, e acima de `X.5` arredonda pra `X+1`? Em que contexto isso é usado?
Comment: Exatamente isso. Estou utilizando em um sistema de cauculos.
Comment: @mgibsonbr pois é, também acho que sim, se ambas variáveis forem locais. Se pelo menos uma das duas não for local, *acho* que ele vai fazer 3 vezes...
Answer: Para fazer esse tipo de arredondamento, supondo que seu valor esteja em uma variável float chamada x, pode-se fazer o seguinte:
x = (float)((int)((x + 0.4f) * 2.0f)) * 0.5f;

Se for double:
x = (double)((int)((x + 0.4) * 2.0)) * 0.5;

Para arredondar mais casas, como 1.51 para 2, pode utilizar 0.49f (ou 0.49) em vez de 0.4f.
Quanto mais casas fossem necessárias, mais 9's seriam necessários depois do 0.4.
Comment: @mgibsonbr bem notado! Vou editar, para contemplar casos com mais casas decimais.
Comment: Muito obrigado!! sou iniciante no C# não sabia desta solução.
Comment: @LucasAnjos Se `x = 1.51` o resultado será `1.5`. É isso mesmo que você quer?
Comment: @carlosrafaelgn Realmente, obrigado a dele se adapta melhor a meu caso.
Answer: Dada a especificidade da regra, sugiro separar a perte inteira da parte fracionária e - conforme desejado - acrescentar 0.5, 1 ou nada:
int y = (int)x; // Descarta a parte decimal, arredondando pra baixo
if ( 0 < x - y && x - y <= 0.5 ) // Se a parte decimal for não-nula e menor ou igual a 0.5
    x = y + 0.5;                 // acrescenta 0.5 à parte inteira
else if ( 0.5 < x - y ) // Se a parte decimal for não-nula e maior a 0.5
    x = y + 1;          // arredonda pro próximo inteiro

Comment: Realmente, para um caso geral, essa solução é mais segura :)
Comment: Obrigado @mgibsonbr, pela preocupação!
Answer: Resolvi responder porque há problemas nas outras respostas. Elas não estão erradas, existe solução melhor. Elas não contemplam negativos e há problemas de performance, embora isso não seja muito relevante. Uma delas acho uma solução feia e a outra desnecessariamente complicada. Espero não ter criado outros problemas na minha.
Eu começaria fazendo algo simples e elegante:
Ceiling(value * 2) / 2

Esta solução não resolve o problema dos números negativos, apenas mostra como pode ser simplificado. A solução dos negativos não torna muito mais complicado.
Solução completa
Para os tipos Decimal e double. Se precisar, é muito fácil criar para float. Note que estou usando o compilador Roslyn (C# 6, veja mais informações em Qual é o jeito correto de chamar as versões do C#?). Se for necessário usar um compilador mais antigo é só eliminar os dois últimos using e chamar os métodos estáticos com o nome da classe. Se preferir usar sem extension method para não poluir o namespace, basta tirar o this no primeiro parâmetro.
using System;
using static System.Console;
using static System.Math;

public class Program {
    public static void Main() {
        WriteLine("Decimal");
        for (var valor = -1M; valor <= 1M; valor += 0.05M) WriteLine("{0:N1} => {1:N1}", valor, valor.RoundMidPoint());
        WriteLine("Double");
        for (var valor = -1.0; valor <= 1.0; valor += 0.05) WriteLine("{0:N1} => {1:N1}", valor, valor.RoundMidPoint());
    }
}

public static class RoundUtil {
    public static Decimal RoundMidPoint(this Decimal value) => Sign(value) * Ceiling(Abs(value) * 2) / 2;

    public static double RoundMidPoint(this double value) => Sign(value) * Ceiling(Abs(value) * 2) / 2;
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
Performance
Fiz outro teste para avaliar a performance dos algoritmos. Nele podemos notar que a minha solução é bem mais rápida. Ainda fiz um teste, não postado, sem resolver o problema dos negativos, que seria mais justo, e a diferença é maior, chega ser mais que o dobro do tempo. Fiz várias combinações e deixei só os mais relevantes. Espero não ter cometido injustiças. Na minha máquina os resultados foram consistentemente:

Decimal Arredondando: 131 ms
Double Arredondando: 138 ms
Decimal mgibsonbr Arredondando: 240 ms
Double carlosrafaelgn Arredondando: 247 ms

Código:
using System;
using static System.Console;
using static System.Math;
using System.Diagnostics;

public class Program {
    public static void Main() {
        var tempo = new Stopwatch();
        WriteLine("Decimal");
        tempo.Start();
        for (var valor = -10000M; valor <= 10000M; valor += 0.05M) valor.RoundMidPoint();
        tempo.Stop();
        WriteLine("Arredondando em ms: {0}", tempo.ElapsedMilliseconds);
        WriteLine("Double");
        tempo.Start();
        for (var valor = -10000.0; valor <= 10000.0; valor += 0.05) valor.RoundMidPoint();
        tempo.Stop();
        WriteLine("Arredondando em ms: {0}", tempo.ElapsedMilliseconds);
        WriteLine("Decimal Alternativo");
        tempo.Start();
        for (var valor = -10000M; valor <= 10000M; valor += 0.05M) valor.RoundMidPointAlt();
        tempo.Stop();
        WriteLine("Arredondando em ms: {0}", tempo.ElapsedMilliseconds);
        WriteLine("Double Alternativo");
        tempo.Start();
        for (var valor = -10000.0; valor <= 10000.0; valor += 0.05) valor.RoundMidPointAlt();
        tempo.Stop();
        WriteLine("Arredondando em ms: {0}", tempo.ElapsedMilliseconds);
    }
}

public static class RoundUtil {
    public static Decimal RoundMidPoint(this Decimal value) => Sign(value) * Ceiling(Abs(value) * 2) / 2;

    public static double RoundMidPoint(this double value) => Sign(value) * Ceiling(Abs(value) * 2) / 2;

    public static Decimal RoundMidPointAlt(this Decimal value) {
        int intPart = (int)value;
        decimal decimalPart = value - intPart;
        if (0 < decimalPart && decimalPart <= 0.5M) return intPart + 0.5M;
        else if (0.5M < decimalPart) return intPart + 1;
        else return intPart;
    }

    public static double RoundMidPointAlt(this double value) {
        int intPart = (int)value;
        double decimalPart = value - intPart;
        if (0 < decimalPart && decimalPart <= 0.5) return intPart + 0.5;
        else if (0.5 < decimalPart) return intPart + 1;
        else return intPart;
    }
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
Um cast não é uma operação mágica, uma conversão é necessária e algo mais complexo que um Ceiling é realizado nele.
A performance pode não ser tão importante, mas não vejo motivo, neste caso, para evitar algo mais rápido. Além de tudo é mais simples.
Outra observação interessante é que o Decimal executa ligeiramente mais rápido que o double em todas as situações. Tem programador que acha que double é solução para problemas de performance para cálculos numéricos. Não em qualquer situação.
Sugestões para futuras melhorias
Se for necessário dá para permitir a configuração do midpoint e arredondar para 0,4 ou 0,7 ao invés de 0,5, por exemplo. Não vou entrar em detalhes porque algumas definições precisas são necessárias para tratá-lo adequadamente.
Também é possível deixar configurar quantas casas decimais se deseja arredondar. Não fiz um teste mas a grosso modo isto seria muito fácil:
public static Decimal RoundMidPoint(this Decimal value, int decimais) => Sign(value) * Ceiling(Abs(value) * (2 * Pow(10, decimais - 1)) / (2 * Pow(10, decimais - 1);

Dá para pensar nisto de outras formas, não pensei muito a respeito. Pode ser melhor colocar steps e não a quantidade de decimais que deve arredondar. Enfim, é só uma ideia inicial para desenvolver. Provavelmente tem algo errado mas vai em exemplo inicial:
public static Decimal RoundStep(this Decimal value, Decimal step) => Sign(value) * Ceiling(Abs(value) / step) * step;

Certamente dá para achar um nome melhor para o método RoundMidPoint, aceito sugestões.


How to calculate all the possible leagues for a group of n teams

Question: Given a set of $n$ teams, I would like to calculate how many different leagues exist. For a league, I mean a series of days, where in each day (with $\frac{n}{2}$ matches) every team plays a match against another team, and the total number of days $(n-1)$ produces the league, such that every team competed with every other team.
Calculating the combinations of pairs from a group of $n$ elements gives all the possible matches, and calculating the combinations of all the possible matches in groups of $\frac{n}{2}$ gives all the possible different days (the order is not important).
Matches and days can be easily calculated with $\frac{n!}{k!(n-k)!}$ but at this point, how to calculate all the possible combinations of matches in $n-1$ days, without having the same match more than once?
For example, for a group of 8 teams, there are 28 possible matches and a total of 105 possible days (4 matches each). The question is, how many leagues (series of 7 days) with everyone of the 28 matches disputed only once, do exist?
Thanks for reading.
Answer: I implemented a brute-force calculation for this problem. Unless I made a mistake, the count for $n = 2, 4, 6, 8$ is respectively 1, 6, 720, 16511040. I couldn't find a match in OEIS, so this leads me to suspect there is no simple answer.
My Mathematica code for the $n=8$ case (I was to lazy to code a function that works directly for any $n$, but it should be obvious how to generalize):
<< Combinatorica`
n = 8; X = Select[Involutions[n, Cycles], Length[#] == (n/2) &]; Sum[
     Y = Select[X, Intersection[X[[i]], #] == {} &];
     Sum[
      Z = Select[Y, Intersection[Y[[j]], #] == {} &];
      Sum[
       W = Select[Z, Intersection[Z[[k]], #] == {} &];
       Sum[
        VVV = Select[W, Intersection[W[[l]], #] == {} &];
        Length[VVV]
        , {l, 1, Length[W]}]
       , {k, 1, Length[Z]}]
      , {j, 1, Length[Y]}]
     , {i, 1, Length[X]}]

EDIT: The above code does not give the correct result. For $n=8$ the value should be 31449600, and the relevant OEIS sequence is https://oeis.org/A036981. Here is new code which should be correct, and is also much faster (it could be made even faster by exploiting the initial symmetry, but it's meant to be a brute-force script):
<< Combinatorica`

Leagues[adj_, 0] := 1

Leagues[adj_, 1] := Length[adj]

Leagues[adj_, n_] :=
 (
  graph = AdjacencyGraph[adj];
  matchFound = False;
  Do[
   If[IsomorphicGraphQ[graph, CacheGraphs[n][[i]]],
    matchFound = True;
    val = CacheValues[n][[i]]]
   , {i, 1, Length[CacheGraphs[n]]}];
  If[matchFound, val,
   val = Sum[row = adj[[i]];
     itemCount = Total[row];
     newItems = Table[0, {itemCount}];
     j = 1;
     Do[If[row[[k]] == 1, newItems[[j]] = k; j++], {k, 1,
       Length[row]}];
     newAdj = adj[[newItems, newItems]];
     Leagues[newAdj, n - 1]
     , {i, 1, Length[adj]}];
   graph = AdjacencyGraph[adj];
   AppendTo[CacheGraphs[n], graph];
   AppendTo[CacheValues[n], val];
   val]
  )

Result[n_]:= (
X = Select[Involutions[n, Cycles], Length[#] == (n/2) &];
Do[CacheGraphs[m] = {};
CacheValues[m] = {}, {m, 1, n}]; Leagues[
 Table[Boole[Intersection[X[[i]], X[[j]]] == {}], {i, 1,
   Length[X]}, {j, 1, Length[X]}], n - 1])

With a few minutes of calculation it is able to also match the next term in the OEIS sequence, 444733651353600.
Incidentally, it seems the hardest part of the calculation in my new approach can be reduced to the graph isomorphism problem, which is not known to be in either P or NP-Complete.
Comment: Hi Meni, thanks a lot for your answer, indeed you made a mistake, since for n=8 the number is 31449600, which I was obtaining from a script I made. Nevertheless, your answer was very precious, since I had no idea of what the OEIS was, but I googled it and I was then able to find the sequence 1,6,720,31449600 which redirects here:
https://oeis.org/A036981
and answers my question. Thanks!
Comment: @dzang Oh. It's funny because I've actually encountered this sequence while looking up the first 3 terms, but didn't notice the comment that indicates it answers your question. (OEIS has an answer for everything. I never should have doubted that.) I think I see my bug now, I don't have the correct number of days.
Comment: @dzang PS. May I have a look at your script? Perhaps there are ways to do it that are simpler than those I had in mind...
Comment: I wrote a script in Python, it's quite primitive but if you want to have a look at it, you can find it here:
https://www.dropbox.com/s/m1wa8zdepniulya/calculate_leagues.py?dl=0
Comment: thanks for the final edit, I don't know Mathematica, but it's impressive that you can do the calculation for the next number in minutes! My script takes 7 minutes for n=8, I didn't even dare to try with n=10 :)
Great answer!
Comment: @dzang: Thanks. The key insight in my new script is that a naive calculation repeats the same sub-problems many times. To avoid repetition, it memoizes every result it calculates, and when it encounters a problem in the future it first checks if it is equivalent to one that it has already solved.
Comment: Would it be possible to use your code to calculate the next number in the sequence?
Comment: @dzang: I very much doubt it, I suspect it would need to be very heavily optimized for that to work. But I've done a simple optimization and started running it, let's see if it ever finishes...
Comment: @dzang: Well, it hasn't finished in 40 hours and there's no reason to believe it ever will.


Rails: Check output of path helper from console

Question: Rails defines a bunch of magic with named routes that make helpers for your routes. Sometimes, especially with nested routes, it can get a little confusing to keep track of what URL you'll get for a given route helper method call. Is it possible to, using the Ruby console, see what link a given helper function will generate? For example, given a named helper like post_path(post) I want to see what URL is generated.
Answer: You can show them with rake routes directly.
In a Rails console, you can call app.post_path. This will work in Rails ~= 2.3 and >= 3.1.0.
Comment: Just in a follow up of my own comment, seems this is possible from rails 3 console, in case you're using.

First, stick a fake request into your app object, by calling something like

`app.get "/"`

then just instance_eval the wanted methods, as they are now protected by default. Something like:

`app.instance_eval{ post_path(post) }`
Comment: `app.teh_path` still works in Rails 4.0 and is useful for separating engine paths from main application paths.
Comment: If you're mounting an engine, e.g. `mount Spree::Core::Engine, :at => '/'`, then you'd access the paths via the engine name, like `app.spree_core_engine.some_path`. Or, if the "engine_name" is configured to be something different like [in this code](https://github.com/spree/spree/blob/v2.3.0/core/lib/spree/core/engine.rb#L5) then you'd do `app.spree.some_path`.
Comment: Chubas' comment above worked in Rails 3. This is very useful when writing tests so I don't have to wait 1 minute to find out that the route is not correct. Also, it is great to test get and post calls. You don't need to call app.get first.
Comment: I had to add the `host` parameter like so: `app.article_url(my_article, host: 'mydomain.com')`
Answer: you can also
include Rails.application.routes.url_helpers

from inside a console sessions to access the helpers:
url_for controller: :users, only_path: true
users_path
# => '/users'

or
Rails.application.routes.url_helpers.users_path

Comment: This is much easier than the above solution IMO
Comment: I can't be bothered to remember this, so I just come back here every couple days to copy/paste. Thanks.
Comment: this is the right answer to the original question in my opinion
Comment: Couldn't you also reference the url_helpers directly from the console, like `Rails.application.routes.url_helpers.users_path`?
Comment: This should be the best answer IMO
Comment: best answer and it still works in the latest Rails (4.x)
Answer: In the Rails console, the variable app holds a session object on which you can call path and URL helpers as instance methods.
app.users_path

Answer: You can always check the output of path_helpers in console. Just use the helper with app
app.post_path(3)
#=> "/posts/3"

app.posts_path
#=> "/posts"

app.posts_url
#=> "http://www.example.com/posts"

Answer: Remember if your route is name-spaced, Like:
product GET  /products/:id(.:format)  spree/products#show

Then try :
helper.link_to("test", app.spree.product_path(Spree::Product.first), method: :get)

output
Spree::Product Load (0.4ms)  SELECT  "spree_products".* FROM "spree_products"  WHERE "spree_products"."deleted_at" IS NULL  ORDER BY "spree_products"."id" ASC LIMIT 1
=> "test"

Comment: Thanks for the `spree` example, you're an angel that fell from heaven.
Answer: For Rails 18.104.22.168, I had to
app.extend app._routes.named_routes.path_helpers_module
app.whatever_path

Answer: From rails 6 rake routes doesn't exist.
You can run instead
rails routes


firebird 2.5 wait for one trigger from another

Question: In table 1 I have trigger 1 that inserts in table 3 with trigger 3 that uses results of trigger 2 in table 2.
Is there is a way in Firebird 2.5 to lunch trigger 1 in table 1 only after trigger 2 in table 2?
Maybe some "wait for trigger"?
Answer: No, in Firebird 2.5 you can't specify the trigger to only run after some other trigger.
The execution order of triggers is determined by the order of statements that trigger them, ie if you use
INSERT INTO table2 ...
INSERT INTO table1 ...

then the (ON INSERT) triggers of the table2 is executed before table1 ones. If table has more than one trigger of given type then the order is determined by the POSITION clause of the trigger's declaration.
If you can't guarantee the order of INSERT statements then perhaps you can use database trigger as a workaround - create an ON TRANSACTION COMMIT trigger where you check for a flag you did set in the trigger2. If the flag is there then execute the stuff which requires the data generated in the trigger2. For setting up the flag you can use the RDB$SET_CONTEXT with the USER_TRANSACTION namespace. Something like
CREATE TRIGGER trigger2 ACTIVE AFTER INSERT ON table2
AS
BEGIN
  RDB$SET_CONTEXT ('USER_TRANSACTION', 'doTrigger1', 1);
END

CREATE TRIGGER trigger1 ACTIVE ON TRANSACTION COMMIT
AS
BEGIN
  IF(RDB$GET_CONTEXT ('USER_TRANSACTION', 'doTrigger1') = 1)THEN BEGIN
     -- proccess data
  END
END

See the Firebirds language reference for the complete TRIGGER DDL syntax.


Suppose $\mathbf{X, Y}$ are independent random vectors. Are their components independent?

Question: Let $\mathbf{X} = (X_1, \dots, X_p)^\top$ and $\mathbf{Y} = (Y_1, \dots, Y_p)^\top$ be independent. Does it then follow that $X_i$ is independent with $Y_j$ i.e. cov$(X_i, Y_j) = 0$?
Comment: Since (obviously) the components are functions of the vectors, the duplicate says it all.  Please note that independence and zero covariance are not equivalent: independence implies zero covariance *if the covariance exists* and zero covariance does not generally imply independence.
Answer: If the two vectors are independent, we have $p(\textbf{X,Y})=p(\textbf{X})p(\textbf{Y})$. Considering a specific pair $X_i$,$Y_j$, $$\begin{align}p(X_i,Y_j) &=\int_{X_k,k\neq i}\int_{Y_m,m\neq j}P(\textbf{X},\textbf{Y})\\ &=\int_{X_k,k\neq i}\int_{Y_m,m\neq j}P(\textbf{X})P(\textbf{Y})\\ &=\int_{X_k,k\neq i}P(\textbf{X})\int_{Y_m,m\neq j}P(\textbf{Y}) \\ &=P(X_i)P(Y_j)\end{align}$$ So, they're independent, which means $\operatorname{cov}(X_i,Y_j)=0$. But, having $\operatorname{cov}(X_i,Y_j)=0$ doesn't mean that the two are independent, as you asked.
Answer: In addition to the answer by @gunes, here it is better to use the definitions directly. Two random variables (or vectors, as in this case) $\mathbf{X}, \mathbf{Y}$ are independent if all events determined by $\mathbf{X}$ are independent from all events determined by $\mathbf{Y}^\dagger$.
But an event determined by $X_i$ is certainly (indirectly) determined by $\mathbf{X}$. So the conclusion follows directly from the definition, without any need for integration or summation.
$^\dagger$ events determined by $\mathbf{X}$ means *member of the $\sigma$-algebra generated by $\mathbf{X}$.


E/DefaultDrmSession: DRM session error java.lang.IllegalArgumentException: Failed to restore keys

Question: Issue
The DRM protected video downloaded successfully to local storage. When try to play the video from local storage the exo-player throw DRMSession error as mention below. Is there way to debug DRM find why its "Failed to restore keys"
Expected Result
Locally downloaded should player properly
ExoPlayer Version
2.14.2
Devices that reproduce the issue

Nokia G20 running Android 11.
Realme 5 Pro running Android 10

Exception Log
<code>E/DefaultDrmSession: DRM session error
      java.lang.IllegalArgumentException: Failed to restore keys
        at android.media.MediaDrm.restoreKeys(Native Method)
        at com.google.android.exoplayer2.drm.FrameworkMediaDrm.restoreKeys(FrameworkMediaDrm.java:262)
        at com.google.android.exoplayer2.drm.DefaultDrmSession.restoreKeys(DefaultDrmSession.java:437)
        at com.google.android.exoplayer2.drm.DefaultDrmSession.doLicense(DefaultDrmSession.java:401)
        at com.google.android.exoplayer2.drm.DefaultDrmSession.acquire(DefaultDrmSession.java:294)
        at com.google.android.exoplayer2.drm.DefaultDrmSessionManager.createAndAcquireSession(DefaultDrmSessionManager.java:775)
        at com.google.android.exoplayer2.drm.DefaultDrmSessionManager.createAndAcquireSessionWithRetry(DefaultDrmSessionManager.java:684)
        at com.google.android.exoplayer2.drm.DefaultDrmSessionManager.acquireSession(DefaultDrmSessionManager.java:563)
        at com.google.android.exoplayer2.drm.DefaultDrmSessionManager.acquireSession(DefaultDrmSessionManager.java:510)
        at com.google.android.exoplayer2.source.SampleQueue.onFormatResult(SampleQueue.java:918)
        at com.google.android.exoplayer2.source.SampleQueue.peekSampleMetadata(SampleQueue.java:686)
        at com.google.android.exoplayer2.source.SampleQueue.read(SampleQueue.java:412)
        at com.google.android.exoplayer2.source.chunk.ChunkSampleStream.readData(ChunkSampleStream.java:398)
        at com.google.android.exoplayer2.BaseRenderer.readSource(BaseRenderer.java:395)
        at com.google.android.exoplayer2.mediacodec.MediaCodecRenderer.readSourceOmittingSampleData(MediaCodecRenderer.java:996)
        at com.google.android.exoplayer2.mediacodec.MediaCodecRenderer.render(MediaCodecRenderer.java:830)
        at com.google.android.exoplayer2.ExoPlayerImplInternal.doSomeWork(ExoPlayerImplInternal.java:945)
        at com.google.android.exoplayer2.ExoPlayerImplInternal.handleMessage(ExoPlayerImplInternal.java:478)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:223)
        at android.os.HandlerThread.run(HandlerThread.java:67)
E/VideoDisplayComponent: onDrmSessionManagerError
    java.lang.IllegalArgumentException: Failed to restore keys
        at android.media.MediaDrm.restoreKeys(Native Method)
        at com.google.android.exoplayer2.drm.FrameworkMediaDrm.restoreKeys(FrameworkMediaDrm.java:262)
        at com.google.android.exoplayer2.drm.DefaultDrmSession.restoreKeys(DefaultDrmSession.java:437)
        at com.google.android.exoplayer2.drm.DefaultDrmSession.doLicense(DefaultDrmSession.java:401)
        at com.google.android.exoplayer2.drm.DefaultDrmSession.acquire(DefaultDrmSession.java:294)
        at com.google.android.exoplayer2.drm.DefaultDrmSessionManager.createAndAcquireSession(DefaultDrmSessionManager.java:775)
        at com.google.android.exoplayer2.drm.DefaultDrmSessionManager.createAndAcquireSessionWithRetry(DefaultDrmSessionManager.java:684)
        at com.google.android.exoplayer2.drm.DefaultDrmSessionManager.acquireSession(DefaultDrmSessionManager.java:563)
        at com.google.android.exoplayer2.drm.DefaultDrmSessionManager.acquireSession(DefaultDrmSessionManager.java:510)
        at com.google.android.exoplayer2.source.SampleQueue.onFormatResult(SampleQueue.java:918)
        at com.google.android.exoplayer2.source.SampleQueue.peekSampleMetadata(SampleQueue.java:686)
        at com.google.android.exoplayer2.source.SampleQueue.read(SampleQueue.java:412)
        at com.google.android.exoplayer2.source.chunk.ChunkSampleStream.readData(ChunkSampleStream.java:398)
        at com.google.android.exoplayer2.BaseRenderer.readSource(BaseRenderer.java:395)
        at com.google.android.exoplayer2.mediacodec.MediaCodecRenderer.readSourceOmittingSampleData(MediaCodecRenderer.java:996)
        at com.google.android.exoplayer2.mediacodec.MediaCodecRenderer.render(MediaCodecRenderer.java:830)
        at com.google.android.exoplayer2.ExoPlayerImplInternal.doSomeWork(ExoPlayerImplInternal.java:945)
        at com.google.android.exoplayer2.ExoPlayerImplInternal.handleMessage(ExoPlayerImplInternal.java:478)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:223)
        at android.os.HandlerThread.run(HandlerThread.java:67)
</code>
Answer: One quick note first - you need to make sure your DRM license supports offline playback, or persistence. Your DRM provider should be able to help confirm or configure this.
Assuming this is the case, then ExoPlayer requires you to manage the offline licenses using it's OfflineLicenseHelper.
There is an up to date examples of this in the ExoPlayer demo code on GitHub - look at: https://github.com/google/ExoPlayer/blob/03569f9e6536e6c60cb585115d6d7352a4deab71/demos/main/src/main/java/com/google/android/exoplayer2/demo/DownloadTracker.java
(ExoPlayer/demos/main/src/main/java/com/google/android/exoplayer2/demo/DemoDownloadService.java  /)
If you look at the 'WidevineOfflineLicenseFetchTask' you can see the synch fetching of the offline license:
<code>    protected Void doInBackground(Void... voids) {
      OfflineLicenseHelper offlineLicenseHelper =
          OfflineLicenseHelper.newWidevineInstance(
              drmConfiguration.licenseUri.toString(),
              drmConfiguration.forceDefaultLicenseUri,
              dataSourceFactory,
              drmConfiguration.licenseRequestHeaders,
              new DrmSessionEventListener.EventDispatcher());
      try {
        keySetId = offlineLicenseHelper.downloadLicense(format);
      } catch (DrmSession.DrmSessionException e) {
        drmSessionException = e;
      } finally {
        offlineLicenseHelper.release();
      }
      return null;
    }
</code>


hook_page_alter in Drupal 8

Question: I am trying to append a twig template on every page .
In drupal 7, we basically append it using hook_page_alter
      function hook_page_alter(&$page) {
      $page['page_bottom']['devel']= array(
            '#type' => 'markup',
            '#markup' => '
' . theme('TEST') . '
', );  //add test template on every page at bottom position
 }

but in drupal 8 there is no hook_page_alter i think.
How to do this??
Answer: hook_page_alter in Drupal 8:
According to the change record Added hook_page_attachments(_alter)() and removed hook_page_build/alter() you should use hook_page_bottom:
function hook_page_bottom(array &$page_bottom) {
  $page_bottom['mymodule'] = ['#markup' => 'This is the bottom.'];
}

You have another issue, theme() is no longer available. But this is another question as it is unclear what you are trying to do with it. Probably you should use the template in a render array $page_bottom['mymodule'] = ['#theme' => 'TEST'];.
In D8 all page elements are in blocks now. The best approach would be to provide the extra content in a custom block and place it in the block layout in the bottom of the page. See comment from @Kevin.
Comment: It might be easier to do a custom block, or just write the HTML in the theme that should show everywhere (although I would probably not do that). It's hard to say without knowing what/why this is needed.
Comment: @Kevin, I agree. Answer is about the question in the title, but I should add, that D8 is all about blocks.

hook_page_alter in Drupal 8


Is Area under curve a composite function

Question: I have some data examples. If I split the data into three parts and the have some scores for each example of the three parts and then calculate individual AUCs for the three parts
In the next case, I keep all the data examples in one cluster, use the same scores as before and calculate the AUC over this whole dataset. Is it possible that the AUC of the whole bulk could be much greater than the individual parts?
Answer: Just to be clear, AUCs are normalized to be a maximum of one (for a perfect classifier). So I think the question is really "can the AUC for all the data together be very different from the  average AUC for the three parts?"
This really depends on factors that were not specified in your question:
(a) Was the classifier evaluated by each ROC trained and tested on the same data? If so, then your models will tend to be "tuned" to the test set and the smaller the test set, the more severe this issue will be: the average AUC for each of the three data subsets will tend to be higher than that for the full set of data.
(b) When you split the data, did you split it completely randomly? If so (and if you didn't train on the test set as discussed in (a)) and your data sets are large enough than the average AUC's should be reasonably close. If, OTOH, you split the data in a non-random way,  you can get very different results between the two cases. For example, (and I'm making this up) say you were trying to predict which party someone will vote for based on things like education, salary, race, gender, etc.  If you split your data by geography so each ROC was based on a particular geographical region you'd likely get more accurate classification than if you threw all regions in together.


Getting started with neural networks for forecasting

Question: I need some resources to get started on using neural networks for time series forecasting. I am wary of implementing some paper and then finding out that they have greatly over stated the potential of their methods. So if you have experience with the methods you are suggesting it will be even more awesome.
Comment: NNs are totally not obsolete. They hold the best scores on several important benchmarks currently tackled by the ML community. Also, they are the best multi purpose differentiable function approximator around. Check out the work of Bengio's, Hinton's and lecun's groups of the last 5 years.
Comment: Of course the neural nets used back in the 80s/90s are different from what you use today and they are still a very active area of research. Furthermore, you *never* use neural networks when you care about interpretability. You use them when you care about prediction error. Neural networks are fast and they solve problems other methods fail at. They are nice because they are simple from a conceptual perspective due to the lack of any assumptions about the data you are modeling (except Gaussian noise when used with the squared error). They have their own merits and flaws.
Comment: @jason, NN have been characterized as "regression without ethics" as they not only over-fit but make the mistake of "believing the data" rather than "challenging the data for consistency of signal"
Comment: I read the Bengio & Lecun paper and it does change my mind a bit, but what they are doing is quite different from historical neural nets. The OP wants to work with time series, where there are several methods that can work with univariate time series and actually give you useful information about the time series (DLMs come to mind). If you have data beyond the time series itself, you can use a variety of other methods (LMs, etc) that are straightforward and also illuminating. Why use a black box with unlabeled dials when you can do something understandable?
Comment: Please note that NNs are rather... obsolete.
Comment: @Wayne: Well said !
Comment: if neural nets are obsolete, (which I don't believe, it has been successfully used and applied by engineers in wide variety of fields) then I would say ARIMA is obsolete as well. ARIMA/ARIMA like methods has performed worst is all the empirical competitions M1 and M3. There is lack of evidence that ARIMA improves forecast accuracy or useful in forecasting, hence why use it  ?
Comment: some comments/answers are obsolete
Comment: Related thread: [References to learn how to efficiently use neural networks for time series prediction (textbooks, online courses, etc.)](https://stats.stackexchange.com/questions/250443/).
Answer: Here's a good quick introduction:
intro to neural networks.
Note that R has neural-network functionality, so no need to spend any time implementing NN yourself until you've given it a spin and decided it looks promising for your application.
Neural networks are not obsolete, but they have gone through a couple of hype cycles, and then after realizing they don't do everything as was claimed, their reputation goes into a trough for a while (we're currently in one of those).  Neural networks are good at certain tasks, and generally are better for tasks in which a human can do a similar task, but cannot explain exactly how they do it.
Neural networks do not give you much insight into the system you're using them to analyze, even after they are trained and operating well.  That is, they can predict what will happen (for some systems), but not tell you why.  In some cases, that is fine.  In others, that is not fine.  Generally, if you want or especially if you already have an understanding of the rules of how something works, you can use other techniques.
But, for certain tasks, they work well.
For time-series in particular, see this question's discussion:
Proper way of using recurrent neural network for time series analysis
Answer: While it is focussed on statistical pattern recognition, rather than time series forecasting, I would strongly recommend Chris Bishop's book Neural Networks for Pattern Recognition becuase it is the best introduction to neural networks in general, and I think it would be a good idea to get to grips with the potential pitfalls in the use of neural networks in a more simple context, where the problems are more easily visualised an understood.  Then move on to the book on recurrent neural networks by Mandic and Chambers.  The bishop book is a classic, nobody should use neural nets for anything until they feel confident that they understand the material contained in that book; ANN make it all too easy to shoot yourself in the foot!
I also disagree with mbq, nn are not obsolete, while many problems are better solved with linear models or more modern machine learning techniques (e.g. kernel methods), there are some problems where they work well and other methods don't.  It is still a tool that should be in our toolboxes.


Add  after 3rd symbol in Array

Question: I have the following variable:
$checkbox = implode(';', $_POST['product']);

$checkbox is equal to "Product Name;Price;Unit", how can I add a break after every line?
At the moment $checkbox is equal to:
ASFP4040;18.95;1;ASFP4048;21;1;ASGS100100;25.45;1

I need it to be like:
ASFP4040;18.95;1;
ASFP4048;21;1;
ASGS100100;25.45;1;

EDIT:
I am writing this to a .TXT file, \n shows as text and doesn't actually create a new line.
Comment: What does your `$_POST['product']` look like?
Comment: If you add `\n`, it must be in double quotes `";\n"`. If you use single quotes, it will print out `\n` instead.
Comment: @Dan Use `"\n"` instead of `";\n"` in your `implode`
Comment: @MagnusEriksson you mean `implode(";", $_POST['product']);` :)
Comment: if you want to display in html
implode(";", $_POST['product']);
Comment: @bassxzero - Depends on if he wants the like break to be displayed in HTML or printed in a file. Anyway, I just realized that it wasn't after each `;` he wants the break so we need to see the original array.
Comment: yap if he could do a print_r or vardump on that $_POST['product'] would be easier
Comment: @MagnusEriksson this worked but is it possible to remove the semi-colon from the end of each line?
Comment: @roberto06 I have now used ";\n" based on the above comment but I need to somehow remove the end semi-colon on lines 1 and 2... A semi-colon cannot exist on the end of a line.
Comment: Yep, that's why you have to use `"\n"` **without** the semicolon.
Comment: @MagnusEriksson put you answer as an answer so that he can tick it
Answer: As I'm not sure, how your $_POST['products'] var looks like, you might like one of these options:
If you have everything in a single array element like this
Array
(
    [0] => ASFP4040
    [1] => 18.95
    [2] => 1
    [3] => ASFP4048
    [4] => 21
    [5] => 1
    [6] => ASGS100100
    [7] => 25.45
    [8] => 1
)

you could split the array into chunks and join them together
$data = implode("\n", array_map(function($chunk) {
    return implode(';', $chunk);
}, array_chunk($_POST['product'], 3)));

Alternatively, if you have an array of strings like below:
Array
(
    [0] => ASFP4040;18.95;1
    [1] => ASFP4048;21;1
    [2] => ASGS100100;25.45;1
)

a simple implode would be enough
$data = implode("\n", $_POST['product']);

Comment: this $data = implode(";\n", $_POST['product']); works but if I have 3 products in my array, the 1st and second line ends with a semi-colon and the third does not. I somehow need to make each line end without a semi-colon?
Comment: just add a semicolon in the end?
Comment: I am trying to remove the END semi-colon, not add one.
Comment: For example, line 1 and 2 end with a semi-colon, line 3 does not. I need all lines to end without.
Comment: oh.. I see - changed again
Answer: Try this:
 echo "'".implode("','",$checkbox)."'
";

Answer: You can use regular expressions to do this. Just replace my $str with your $checkbox.
$str = 'ASFP4040;18.95;1;ASFP4048;21;1;ASGS100100;25.45;1';
$str2 = preg_replace('/((?:(?:[^;]+);){3})/',"$1\n",$str);
echo $str2;

Answer: As explained in Magnus Eriksson's comment and mine, you just have to use "\n" as first parameter of your implode:
$checkbox = implode("\n", $_POST['product']);

Please notice the use of double quotes (") in order for \n to be used as a linebreak.

Add  after 3rd symbol in Array


Como fazer uma comparação sem id?

Question: Estou fazendo um projeto escolar(um bingo automático), e estou no ultimo passo, comparar o valor sorteado com os valores adicionados pelos usuários, estou em torno de uma semana tentando fazer isso, se alguem puder me ajudar a resolver meu problema, eu agradeço muito!
Ultimo tópico: A cada 4 segundos é sorteado um número, e assim que ele é sorteado eu tenho que comparar ele com todos os usuários, para que se algum possuir eu possa marca-lo (com uma div, ou algum síbolo), para depois eu conferir qual dos jogadores tem todos os números marcado e assim poder da um alerta de vencedor.
Segue aqui as funções que eu utilizei para expor os valores (tanto os escolhidos pelo usúario, quanto o que vai ser sorteado);

    <title>Bingo Online</title>
    <link rel="icon" href="img.png">
    <meta charset="UTF-8">
    <meta name="description" content="jogue bingo online com seus amigos de forma rápida e prática">
    <meta name="keywords" content="bingo, ganhar">
    <meta name="author" content="Ketlly Azevêdo de medeiros">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.1/jquery.modal.min.css" />

        <button type="button" class="close" data-dismiss="alert"></button>
        Atenção! pode escolher do número 1 ao número 75.

      <form id="form">
        Nome:
        <input type="text" class="form-control" id="nome" placeholder="Digite o nome do Usuário...">
        Número 1:
        <input type="text" class="form-control" id="numero" maxlength="2" placeholder="Digite um número..." onkeyup="somenteNumeros(this);">
        Número 2:
        <input type="text" class="form-control" id="numer" maxlength="2" placeholder="Digite um número" onkeyup="somenteNumeros(this);">
        Número 3:
        <input type="text" class="form-control" id="nume" maxlength="2" placeholder="Digite um número" onkeyup="somenteNumeros(this);">
        Número 4:
        <input type="text" class="form-control" id="num" maxlength="2" placeholder="Digite um número" onkeyup="somenteNumeros(this);">
        Número 5:
        <input type="text" class="form-control" id="nu" maxlength="2" placeholder="Digite um número" onkeyup="somenteNumeros(this);">
      </form>
      <button class="btn-sm btn-danger ml-3">Close</button>
      <buttonid="adicionar" class="btn-sm btn-success ml-3" onclick="novoUsuario('tabela',this)">Adicionar</button>

a

          <button class="btn-sm btn-success ml-3" onclick="sortear()">Sortear</button>

                Usuário:

                <button class="btn-sm btn-outline-success" onclick="adicionar()"> adicionar</button>

Answer: Não sei se entendi bem, mas acredito que queira identificar na tabela quais os nomes com o numero sorteado.
Um loop nos elementos da tabela deve ajudar.
  function sortear() {
    var sorte = Math.floor(Math.random() * 75 + 1);
    document.getElementById('mostrar').innerHTML = sorte;
    ganhadores(sorte, "tabela");
  }

  // Recebe como paramentro o numero sorteado e o id da tabela
  function ganhadores(num, tabelaID) {
    var tabela = document.getElementById(tabelaID), // obter a tabela pelo id
      cell;
    // Loop em cada linha da tabela
    for (var row = 0; row < tabela.rows.length; row++) {
      var contador = 0; // Contador para verificar vencedor
      cell = tabela.rows[row].getElementsByTagName("td"); // obter todas as colunas da tabela
      // Loop em cada coluna
      for (var i = 1; i < cell.length; i++) {
        // Verifica se o numero ja foi sorteado
        if (!cell[i].getAttribute("sorteado")) {
          // Verificar se o numero do usuário é igual ao sorteado
          if (parseInt(cell[i].innerHTML) === num) {
            // definir tag para lembrar que o numero já foi sorteador
            cell[i].setAttribute("sorteado", true);
            // colorir o numero de verde
            cell[i].setAttribute("style", "color: green");
            contador++;
          }
        } else {
          // Incrementar contador
          contador++;
        }

        // Verificar se o contador é igual a 5
        if (contador >= 5) {
          // Definir nome do vencedor de verde
          cell[0].setAttribute("style", "color: green");
          alert("Vencedor: " + cell[0].innerHTML);
          parar();
        }

      }
    }
  }

Comment: Compreendi o que você colocou, no entanto, o que eu tenho que colocar é diferente: a cada 4 segundos é sorteado um número, e assim que ele é sorteado eu tenho que comparar ele com todos os usuários, para que se algum possua eu possa marca-lo (com uma div, ou algum síbolo), para depois eu conferir qual dos jogadores tem todos os números marcado e assim poder da um alerta de vencedor. Ai a parte de fazer essa comparação para poder marcar que eu estou emperrada a um bom tempo.
Comment: OK, acho que agora entendi... Editei minha resposta, acredito que seja uma possivel solução

Como fazer uma comparação sem id?


is it possible to edit default output of services module?

Question: Is it possible to edit/customize the default output we get using Services Module ?
For example I want to edit output which I get from this URL : http://example.com/api/node/39
And I want to edit output of this URL : http://example.com/api/user/39
OR is there any way to create a View for single user profile ?
Answer: Using the Services API this is possible: http://cgit.drupalcode.org/services/tree/docs/services.alter.api.php?h=7.x-3.x
/**
 * Implements hook_services_request_postprocess_alter().
 */
function example_services_request_postprocess_alter($controller, $args, &$result) {
  switch ($controller['callback']) {
    case '_node_resource_retrieve':
      $result->foo = 'bar';
      break;
    case '_user_resource_retrieve':
      $result->bar = 'chew';
      break;
  }
}

You could use the Views JSON module (a sub module of the Views datasource module) to build a View with a User ID contextual filter, and then return the field(s) you want for that particular user.
Answer: Are you aware of the Services Views module?
It allows you to create a services path and you can control the output with Views.
From the question:

Is there any way to create a View for single user profile ?

From the module:

Executing view via views resource
After enabling "views" resource in
  your services endpoint you can do GET request to:
http://example.com/<endpoint path>/views/<view name>
This will execute a view and pass results.
Possible arguments:

display_id: views display
args: array of view arguments
filters: array of view filter values
offset: views offset
limit: limit views number of results
format_output: boolean whether we would like to get themed view or data

This module supports Views arguments (args), which are known as 'Contextual filters' in the Views UI. So if you create a contextual filter for the uid, and you pass the args in your request it should work.
Something like http://example.com/rest/views/users?args[uid]=5 or http://example.com/rest/views/users?args[0]=5 probably works.
Please note that this method does not alter the output of the existing services endpoints, but creates a new path.


data in a select list clears out after adding one more field collection

Question: I have a 2 select list inside the field collection. One is a parent list and another is a child list. Child list is populated when the parent list is selected.I use my custom Ajax and JQuery to achieve this. My field collection is in unlimited valued field the problem is whenever I clicked add another item to make a new field collection my previous selected child list looses its data. Is there any way how to retain the previously selected child list.
My jQuery code:
$(".field-name-field-countries .form-select").change(function(){
   $('[id$=field-cities-depend-und]').empty();
    //var id=$(".field-name-field-countries .form-select :selected").text();
    var id=this.id;

    var val=$("#" + id  +" :selected").text();

    var dataString = 'id='+ val;

    $.ajax
    ({
        url: "/sites/all/modules/customs/drop_down/ajax_city.php",
        type: "POST",
        data: dataString,
        dataType: 'json',
        cache: true,

        success: function(json)
        {
             $.each(json, function(i, value) {
                 $('[id$=field-cities-depend-und]').append($('<option>').text(value).attr('value', value));
            });

        }
    });

});

My Ajax code:
<?php

    $con=mysqli_connect("localhost","root","root","d7-demo");
    if (mysqli_connect_errno())
      {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }

     if($_POST['id']){
       $country=$_POST['id'];
       $result = mysqli_query($con,"SELECT country,city FROM cities_link where country='$country'");
       $rows = array();
            while($row = mysqli_fetch_array($result))
             {

             //  $data=$row['city'];
               $rows[] = $row['city'];
             // print json_encode($data);
             }
            print json_encode($rows);
            mysqli_close($con);

    }

?>

Comment: You have to show us your custom Ajax and jQuery script. You must be using non-standard non-form-api methods to do this. Otherwise it should have gotten the values from `$form_state`
Comment: that code is in no way utilizing the standard Drupal ajax framework. I'm afraid if you want this to work properly you'll need to read up: https://api.drupal.org/api/drupal/includes!ajax.inc/group/ajax/7 I'm sure people will be happy to assist once you get started. You'll need to use `hook_form_alter` to attach a `#ajax` property to your parent select field and also build the child select field's options in there too by checking if `$form_state['values']['parent_select_list_field_name']` contains a value. And in the ajax callback just return the child select field.
Comment: @Beebee is right that you should use AJAX provided by Drupal for that to work, but I would rather suggest to read [ajax section in Form API reference](https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#ajax) first.
Comment: @Beebee I used the follow way to do this. Above are the codes that I am using.
Answer: In Drupal, forms are protected from submitting values that was never outputted as available options. When you alter options with custom JavaScript, you are making user to submit values Drupal does not know to be valid. Try to rewrite your code to use form API #ajax parameter. It will look more complicated indeed, but it'll make Drupal know about changed options.
Remember to make actual changes in form building function. Ajax handler is there only to provide the part of the form that needs to get updated, and maybe do some one-time touch-ups you don't care to keep.


Securely mounting a Samba share from a VPS on a local machine

Question: In my own little slice of the internet, I have a share that I want to serve up so I can mount it on my system at home and work with files as if they were local.  I have this setup as a Samba share at the moment.  However, I'm not entirely sure on how to go about keeping this setup secure.  What is the recommended way to secure this setup?
Right now I'm thinking to (obviously) require a username and password and open up the relevant ports, but how does one set this up so that the password isn't transmitted in the clear?  Is there something like a "Samba over SSH" protocol?  Thanks.
Comment: Then I can learn...?  I thought that was the point of the Stack Exchange.
Comment: Yes, OpenVPN. See Lucas' comment below. Note, however, you are now stepping off into deep water. Perhaps you should be doing this with an OS that you are already familiar or at least learn to swim before you venture out to play with the sharks.
Comment: Without explaining why this is "stepping off into deep water" this is kind of a useless comment.  What things should I be aware of?  I work with Linux on a daily basis.
Comment: If you don't know enough about networks to understand *just* how obvious the answer to your question really is, you're stepping off into far deeper waters than you realize.
Answer: I would use VPN over SSL/TLS. (openvpn)


Error uploading ios app?

Question: I'm just about to upload my app.
I have read all over the internet and I can't find an answer that makes sense to me of my problem:
I archived my project and tried clicking "distribute" and clicked the option in the middle, which got me a .ipa file, I think. I tried using it in Application Loader, but only got this error:
Comment: Do you have a valid provisioning profile for the app?
Comment: Do you have your app store distribution profile installed on your machine?  If so, select it before you distribute.
Answer: Here's how to upload an app to the App Store (Xcode 4):

Make sure you have the correct certificates to sign your app build. Google it if you're not sure.
Make sure that Xcode is directed toward an iOS device (top left corner)
Build > Archive
Open the Organizer to the Archives tab.
Click 'Distribute'
Fill in your Identity details
Follow the steps.

IF YOU GET AN ERROR
Usually, errors are something like 'your bundle ID is wrong' or 'bundle version bla bla bla'. These errors look very scary. They are not. Usually, you can just Google the error. Or comment here for help.
If the error is related to code signing
Welcome to the real world. I spent 2 months trying to figure this out. Comment here for help.
EDIT: Noticed your problem was with code signing. Under < your project > > < your target > >Build Settings > Code Signing > Code Signing Identity, play with the values until you find something that works. This often means that your bundle ID doesn't match the one on the certificate, etc. Sometimes you have to make certificates through the Provisioning Portal. For any more help, comment here.

Error uploading ios app?


Swapping each word in a string into a certain order

Question: I am trying to get a string of text from one text box and put it into the next text box inverted but readable like this. "Help please" and in the next box when I click the button it should say "please Help". I have been trying everything that I can think of. Sorry very new to this. Ill attach the code
private void button1_Click(object sender, EventArgs e)
{
    string converttext = txtInputBox.Text;

    StringBuilder sb = new StringBuilder(converttext.Length);
    for (int i = converttext.Length - 1; i >= 0; --i)
    {
        sb.Append(converttext[i]);
    }
    string reversed = sb.ToString();

    txtOutputBox.Text = reversed;
}

Comment: What result DO you get?
Comment: I'm getting "esaelp pleH" from "Help please"
Answer: You can split the string on space and then reverse the result and pass it to string.Join like:
string str = "Help please";
string newStr = string.Join(" ", str.Split().Reverse());

Comment: I think separator should be a string :)
Comment: @SergeyBerezovskiy, yup just fixed that :)
Comment: Note that these are very simple approaches. Words might be separated by other characters as well(like `,;()[]/.` etc). It will also replace tabs or line-breaks with an empty space.
Answer: txtOutputBox.Text = String.Join(" ", txtInputBox.Text.Split().Reverse());


VBA to automatically replace Modules in several workbooks

Question: Someone posted a question on mrexcel, asking how to replace modules in existing workbooks with new ones:
https://www.mrexcel.com/forum/excel-questions/760732-vba-automatically-replace-modules-several-workbooks.html
They answered their question with others support as follows:
Sub Update_Workbooks()
'This macro requires that a reference to Microsoft Scripting Routine
'be selected under Tools\References in order for it to work.
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Dim fso As New FileSystemObject
Dim source As Scripting.Folder
Dim wbFile As Scripting.File
Dim book As Excel.Workbook
Dim sheet As Excel.Worksheet
Dim Filename As String
Dim ModuleFile As String
Dim Element As Object
Set source = fso.GetFolder("C:\Users\Desktop\Testing")   'we will know this since all of the files will be in one folder
For Each wbFile In source.Files
If fso.GetExtensionName(wbFile.Name) = "xlsm" Then  'we will konw this too. All files will be .xlsm
Set book = Workbooks.Open(wbFile.path)
    Filename = FileNameOnly(wbFile.Name)
    'This will remove all modules including ClassModules and UserForms.
    'It will keep all object modules like (sheets, ThisWorkbook)
    On Error Resume Next
    For Each Element In ActiveWorkbook.VBProject.VBComponents
        ActiveWorkbook.VBProject.VBComponents.Remove Element
        Next

    On Error GoTo ErrHandle
'   Export Module1 from updating workbook
    ModuleFile = Application.DefaultFilePath & "\tempmodxxx.bas"
    Workbooks("Update Multiple Workbooks.xlsm").VBProject.VBComponents("Module1") _
    .Export ModuleFile
'   Replace Module1 in Userbook
    Set VBP = Workbooks(Filename).VBProject
    On Error Resume Next
    With VBP.VBComponents
        .Import ModuleFile
    End With
'   Delete the temporary module file
    Kill ModuleFile

book.Close True
End If
Next
    Exit Sub
ErrHandle:
'   Did an error occur?
    MsgBox "ERROR. The module may not have been replaced.", _
      vbCritical
End Sub

However, its quite large, and wanted to show a simple way of doing the same thing. Also, I found that when Importing the Modules to a different sheet, the ThisWorkBook and Sheet files are also imported as ClassModules. This is not always desired, so see answer below for alternative options!
Answer: You can import (or export if you flip the order) Modules from a different sheet using the following Sub:
Sub import_mods()
'First define each module you're looking to
'take from the excel sheet "Workbook_with_Modules.xlsm"

For Each Element In Workbooks("Workbook_with_Modules.xlsm").VBProject.VBComponents

    'MsgBox Element.Name 'I ran this first to see which modules are available

'First, export each module from the "Workbook_with_Modules.xlsm"
Workbooks("Workbook_with_Modules.xlsm").VBProject.VBComponents(Element.Name).Export (Element.Name)

'Then, Import them into the current Workbook
 Workbooks(ThisWorkbook.Name).VBProject.VBComponents.Import (Element.Name)
Next Element

End Sub

I created a separate sub to delete the one's I'm not interested in keeping. You can Call it directly from the previous sub if you prefer, or build the If statement for the type into the previous sub as well, but for this example's sake, its a separate Sub entirely.
Sub rems()
'Types:
'   100 = Sheets and ThisWorkbook for current Workbook
'   1 = Modules (such as "Module1")
'   2 = ClassModules (such as other sheets from a different Workbook "ThisWorkBook1")

For Each Element In Workbooks(ThisWorkbook.Name).VBProject.VBComponents
'I first tested the types and corresponding number
'MsgBox Workbooks(ThisWorkbook.Name).VBProject.VBComponents(Element.Name).Type

'Now, the If function for removing all ClassModules (Type = 2)
        If Workbooks(ThisWorkbook.Name).VBProject.VBComponents(Element.Name).Type = 2 Then
            Workbooks(ThisWorkbook.Name).VBProject.VBComponents.Remove Element
        End If
Next Element

End Sub

Hope this helps anyone!
Answer: I have a problem importing the modules, they are imported adding a 1 at the end of the name.
I tried to delete them before, and then import all, but the deletion is not executed until the sub ends.
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Where is archive-dump for Drush 9?

Question: I have drush 9 installed (current dev release). I can't find the archive-dump command, despite the docs suggesting it should be there.
Executing it produces:

The Drush command 'archive-dump' could not be found. Use 'drush core-status' to verify that Drupal is found and bootstrapped successfully. Look for 'Drupal bootstrap : Successful' in its output.

I can confirm that drush core-status (or status) states that Drupal is successfully bootstrapped. The problem is present for local and remote environments, and on any machine that it's installed on (I've tried 4 so far, a mix of MacOS and Ubuntu environments).
I've even gone so far as to grep drush's code for mentions of archive and ard (the alias that used to work and also should if the docs are to be believed. There doesn't seem to be anything pertinent in there.
So where's archive-dump gone?? If it's been removed, what's its successor?
Answer: Turns out it was removed in this commit to Drush 9 following this issue and follow up.
So archiving no longer exists, or at least not until someone has time to port the logic over to the Composer workflow.
Comment: Grrr. i think having a usable webdir backup with db dumps easily was beneficial, even if the composer workflow files were omitted :(

Where is archive-dump for Drush 9?


Using git desktop I committed my changes and pressed sync. There were merge errors and my local files got changed a lot. How to undo changes?

Question: I accidentally synced when I shouldn't have done and changed a lot of my local files how do I undo this sync?
Answer: The following answer assumes that a) you committed all your valuable work already, and b) you don't want anything which came in from the recent merge ("sync"), from the remote branch.  Assuming both of these are true, you can just do a hard reset to the current HEAD of your branch:
git reset --hard HEAD

In case you ever end up in a similar situation where you don't want to nuke your entire working directory (and maybe stage as well, if you've staged anything), you can use the following command to checkout an individual file from the HEAD:
git checkout -- path/to/some/file.ext

Comment: it won't let me accept your answer yet but omg I love you. It worked perfectly and even undid the directory changes that were made.


Equilateral triangle in Semicircular

Question: I have a geometry question. In this question, We have a Equilateral triangle ($ \triangle BDC$) that we draw it with one point on the circle and 2 point on the diameter. We want to prove if we draw this triangle then $OC = OD$.
Image1
I try to prove it But I can't find any good way to prove that. It must solve with central and inscribed angles. Is it possible to help me to solve it?
I'm sorry for bad English.
Thanks.
Comment: The statement is not true if there is no restriction to the point $B$. Do you mean $B$ is the midpoint of that semicircle?
Comment: B is on semicircle But we don't know where is it. if we draw it then B is the midpoint of that semicircle but we don't know it.
Answer: As you can see from the picture, your claim is not true. You need some other hypotheses.
Comment: thanks. It's not my question But I believe that it's question is not true.

Equilateral triangle in Semicircular


Como descobrir a url base do Laravel?

Question: Eu me lembro que, quando eu usava o framework Codeigniter, eu poderia descobri qual era a url base da aplicação, simplesmente chamando base_url(). No Laravel 3, eu usava URL::base().
Porém agora, no Laravel 5, quando eu chamado URL::base(), retorna o seguinte erro:

BadMethodCallException with message 'Method base does not exist.'

Testei no Laravel 4, e ocorre o mesmo erro.
Sendo assim, qual é a forma correta de descobrir a url base da aplicação, usando Laravel 4 ou 5?
Answer: Para saber o url base basta:
$base_url = url('/');

Url helpers de laravel
Comment: Boa. Testei aqui no `php artisan tinker` (Laravel 4) e funcionou. Porém nem precisou chamar a barra, bastou apenas usar `url()`.
Answer: Existem vários helpers para gerar urls no Laravel, é preciso entender qual seria o caso de uso onde você precisa só a url base.
Em todo caso, podemos usar o helper url() que existe desde a versão 4 do Laravel.
$siteRoot = url('/');

É importante inserir o barra, pois a partir do Laravel 5.2, o helper url() irá retornar uma instância de UrlGenerator.
Comment: Informação importante. Quando você passa `NULL` em `url`, ele realmente retorna `UrlGenerator`. Não vi ainda, mas vou confirmar se ele  usa `__toString` internamente.
Comment: Usa não @WallaceMaxters
Comment: Eu vi aqui. É importante passar pelo menos uma `string` vazia. Interalmente ele verifica se o parâmetro é `NULL`.
Comment: Que o autor da resposta anterior não me leve a mal, mas eu creio que essa resposta está mais completa.
Answer: Na versão 4 do Laravel, é possível fazer isso utilizando o método URL::to(), porém é necessário colocar uma barra ou uma string vazia como parâmetro.
 $base = URL::to('');

 // ou

 $base = URL::to('/')

Isso também funcionará na versão 5 do Laravel, mas nesse caso é melhor usar a função url(), como mencionado na outra resposta.
Comment: Por que não utilizar o helper no Laravel 4? Ele já existia lá https://laravel.com/docs/4.2/helpers#urls
Comment: @gmsantos eu só descobri que tinha essa função agora que fiz a pergunta, hehehe. Em todo caso, eu costumo muito tentar manter um padrão. Percebi que a utilização de funções se tornou muito comum a partir do Laravel 5. Nas versões 4, era comum sempre ter uma classe Facade com um Alias, para você usar um recurso ou uma biblioteca de terceiro. De qualquer forma, essa informação é bem-vinda
Comment: Na época do Laravel 4 era mais comum mesmo as Facades, ainda bem que elas estão caindo em desuso
Comment: Também acho que facades as vezes podem gerar problemas, principalmente com o não uso de namespace (por padrão), pode gerar conflitos de nomes. Aí já viu, né.

Como descobrir a url base do Laravel?


Interpretation of interaction effects in linear mixed models with numeric and factorial IVs

Question: I hope my question is not too basic for this community. I can*t figure out how to interpret the output of my linear mixed model,  especially the interaction effects.
I do my analysis in R using lme from the nlme package. My model consists of 3 factorial IVs (exp.type [2 levels - field vs. lab], org.type [3 levles - autotroph, heterotroph, mixed], system [2 levels - marine vs. freshwater]) and 2 numeric IVs (even, duration).

lme1 = lme(reist ~ even + exp.type + even:exp.type + org.type + even:org.type + system +
        duration, random =~1|authors.year, data = data)

My question is: How do I interpret the interaction effects? How do I get the slopes of the linear regressions for each level of the IVs that have significant interactions
Comment: You could take a look at this online tool to probe interactions in multilevel models: http://www.quantpsy.org/interact/hlm2.htm. Among other things, it does provide you with simple slopes.
Answer: When there is an interaction, there is no unique slope for any of the main effects; those change based on other variables in the interaction.
I have found that the simplest method of interpreting interactions is visually: make graphs of your DV at different levels of your IVs. Since you have two numeric IVs and 3 categorical ones, you could make 6 graphs. For each, plot one numeric IV on the x axis and the predicted value of the DV on the Y axis, with a line for each level of one of the categorical DVs (you will have to make some assumptions about the value of the other IVs - the mean for the continuous and the mode for the categorical may be sensible).
Alternatively, you could make a lattice plot (using the lattice package) or use faceting (with the ggplot2 package).
Another way to go is to make a table of the predicted values of the DV for various common combinations of the IVs. (E.g. the quartiles of the two continuous IVs and all the values of the DVs - which would give a table with 3*3*3*2*2 = 108 rows.
As to what the interactions mean - an interaction means that the relationship between one IV and the DV is different at different levels of the other IV.
Comment: Hello, thanks a lot for your detailed answer. I understand why one should ignore main effects in the face of significant interactions. I already plotted predicted values for each level but I'm not sure if I understood the part where you wrote: "with a line for each level of one of the categorical DVs".
Comment: The categorical IVs (that was a typo, it should be IV) each have a fixed number of levels (2 or 3 in your case, depending on which IV) so you can make one line for each of them.
Comment: ok, thanks :) Thats basically what I did to find the slopes of each level. Comparing these to the data above I then found that "Evenness" in the table above is in fact only the slope of the regression between evenness and resistance BUT! only for exp.type field and autotrophic organisms (so first levels of both IVs). The slope of exp.type lab (still autotrophic) is then the -2.59 + the interaction term for exp.type lab (2.66 = 0.65 or so). So thats for autorophic organisms only...
Comment: If I then add the interaction of evenness*org.type heterotroph (4.01) to the slope of autotrophic field studies (-2.59) I get exactly the slope that I calculated for heterotrophic field studies (calculated via slope of predicted values). If I add the 4.01 from the heterotropic interaction to the 0.65 from above (instead of -2.59) I get exactly the slope of heterotrophic lab studies that i calculated from the predicted values. The same holds true for the 3.Interaction (evenness*organism type mixed = 6.01). This might seem a little confusing but this way I can extract the slopes from the table
Comment: Even though the slopes that I calculated from the predicted values fit nicely to that table, im not shore if this is the right interpretation of the table above, as it is not very intuitive. I hope I didnt confuse you too much. Don't know how to put it more precisely :/
Comment: OK..... What else do you need? If anything?
Comment: I think I just need to know if the way I understood the interactions is correct :)
Comment: It sounds right to me!
Answer: Short update: I was wrong in my interpretation, allthough it fits nicely. I did the same analysis using a simple artificial data set w/o mixed effects (allowing me to fit individual lm for each level of both factors:
a = c(rep(1:10, 4))
b = c(10,20,30,40,50,60,70,80,90,100, 5,8,10,14,17,22,27,35,42,50, 90,82,73,64,56,48,40,33,25,18, 5,6,8,10,12,14,17,20,23,26)
c = c(rep("male", 10), rep("female", 10), rep("male", 10), rep("female", 10))
d = c(rep("low", 20), rep("high", 20))
e = data.frame(yval = b, xval = a, sex = c, education = d)

scatterplot(yval~xval | education, smooth = F, grid = T, spread = F, reg.line = T, data = e, xlab = "x", ylab = "y")

lm2 = lm(yval~xval+sex+xval:sex+education+xval:education, data = e)
summary(lm2)

It turns out that the interaction for the levels of factor A are calculated while ignoring the interaction between the levels of factor B (seeing that I remember that I learned something like that long ago for simple ANOVAs... :).
Strangely, the way I calculated the slopes above in my first post still works, giving the exact numbers from the table output, but completely wrong slopes :)
Calculating:
new_data_lm = expand.grid(xval = c(1:10), sex = c("female", "male"), education = c("high", "low"))
new_data_lm$pred = predict(lm2, new_data_lm, level = 0)
View(new_data_lm)

gives a table with predicted y values for given x values.
When calculating the slopes of these predicted values for each level ob the interactions:
lm_f_h = lm(pred~xval, data = subset(new_data_lm, sex == "female"& education == "high"))
summary(lm_f_h)
lm_f_l = lm(pred~xval, data = subset(new_data_lm, sex == "female"& education == "low"))
summary(lm_f_l)

gives us the slope -1.503 (for female_high) and 8.794 (for female_low). Both slopes are completely wrong but when added together, they give the exact number for the interaction "xval:educationlow" (10.297) from the output of:
summary(lm2)

The same holds true when calculating the difference in slopes between male_high and female_high giving us -2.667, which is exactly what summary(lm2) gives us for the interaction xval:sex_male.
So all in all I managed to find out how to read the table but I don't understand what I did wrong and why it still fits. Have to think about that very thoroughly.
When predicting the y values from the model by predict(lme2) (so without the additional "new_data" argument), the values of the slopes are correct, but when adding a "new_data" argument with x-values to predict from, the slopes dont match, the interaction terms howver, do?!
So whats the difference between these two approaches? What did I miss?