java.sql.SQLException: Column 'id' not found

Question: Meu código de pesquisar no BD pelo id. A classe é ContatoDao:
    //Pesquisa por id
public Contato pesquisaId(int id) {

    String sql = "select nome from contatos where id = "+id;
    Contato contato = null;

    try {
        PreparedStatement stmt = this.connection.prepareStatement(sql);
        ResultSet rs = stmt.executeQuery(sql);

        if(rs.next()) {
            contato = new Contato();
            contato.setId(rs.getLong("id"));
            contato.setNome(rs.getString("nome"));
            contato.setEmail(rs.getString("email"));
            contato.setEndereco(rs.getString("endereco"));
        }
        rs.close();
        stmt.close();
        //return contato;

    } catch (SQLException e) {
        //throw new DAOException("Erro ao pesquisar no banco de dados pelo id.");
        throw new RuntimeException(e);
    }
    return contato;

}

Esse outro é o código da classe de teste desse código acima:
    package br.com.caelum.jdbc.teste;

import br.com.caelum.jdbc.dao.ContatoDao;
import br.com.caelum.jdbc.modelo.Contato;

public class TestaPesquisaId {

    public static void main(String[] args) {

        ContatoDao dao = new ContatoDao();
        Contato contato = dao.pesquisaId(1);

        System.out.println("Nome: "+contato.getNome());

    }

}

Este é o erro que mostra no console:
 Exception in thread "main" java.lang.RuntimeException: java.sql.SQLException: Column 'id' not found.
    at br.com.caelum.jdbc.dao.ContatoDao.pesquisaId(ContatoDao.java:101)
    at br.com.caelum.jdbc.teste.TestaPesquisaId.main(TestaPesquisaId.java:11)
Caused by: java.sql.SQLException: Column 'id' not found.
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:89)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:63)
    at com.mysql.cj.jdbc.result.ResultSetImpl.findColumn(ResultSetImpl.java:556)
    at com.mysql.cj.jdbc.result.ResultSetImpl.getLong(ResultSetImpl.java:829)
    at br.com.caelum.jdbc.dao.ContatoDao.pesquisaId(ContatoDao.java:90)
    ... 1 more

Um detalhe: Esse id existe sim no banco, inseri com o método inserirContato que eu criei.
Comment: Não concatene o ID na query, isso deixa a aplicação vulnerável a ataques de [SQL injection](https://pt.stackoverflow.com/q/100729/112052). Prefira usar os *setters* do `PreparedStatement`, exemplos: https://www.baeldung.com/sql-injection#1parameterized-queries
Answer: O texto da sua query não possui a coluna id, apenas a nome. Todos os campos que você pretende obter devem estar no SELECT:
...
String sql = "select id, nome from contatos where id = " + id;
...

Um outro ponto é o que o hkotsubo comentou. Utilize o campo como parâmetro ao invés de concatenar na query:
...
stmt.setInt(1, id);
ResultSet rs = stmt.executeQuery("select id, nome from contatos where id = ?");
...

Comment: Na verdade o `setInt` e demais parâmetros são feitos no `PreparedStatement`, não no `ResultSet`
Comment: Obrigado! Foi falta de atenção, porque eu to pegando todas as colunas no rs.


C#/Xamarin: Appearing/Disappearing events don't fire

Question: UPDATE: I've looked into this issue further and discovered this is a Xamarin.Forms issue.
To prove the issue I've created the following simple Xamarin.Forms app, from a basic PLC template.
I added a new page with simple handlers for Appearing and Disappearing events, as so.
using System;
using System.Diagnostics;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace TestApp
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class EventPage : ContentPage
    {
        public EventPage()
        {
            InitializeComponent();
            Appearing += EventPage_OnAppearing;
            Disappearing += EventPage_OnDisappearing;
        }

        private void EventPage_OnAppearing(object sender, EventArgs e)
        {
            Debug.WriteLine("Appeared");
        }

        private void EventPage_OnDisappearing(object sender, EventArgs e)
        {
            Debug.WriteLine("Disappeared");
        }
    }
}

I then added two buttons to the main page which navigate to the above page in two different ways:
using System;
using Xamarin.Forms;

namespace TestApp
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private void WorkingButton_OnClicked(object sender, EventArgs e)
        {
            Navigation.PushAsync(new EventPage());
        }

        private void NonWorkingButton_OnClicked(object sender, EventArgs e)
        {
            Application.Current.MainPage = new EventPage();
        }
    }
}

Observations are the same as before, with PushAsync the behaviour is as expected, but setting the root page means the events don't fire.
This came up in my real project when I reset the stack using this line
                    await _navigationService.NavigateAsync($"http://app.com/NavigationPage/HomePage/AlertPage"); so the issue doesn't seem to be isolated to just the root page.
I've come across this issue in my current project which is using Xamarin Forms v220.127.116.11-pre2 with Prism 6.3.0-pre2 (Unity) and in the following test app using Xamarin Forms 126.96.36.199 with Prism 6.3.0 (Dryloc). I'm running on a LG G5, Android 7.0.
I'm not sure if this is a Prism issue or a Xamarin Forms issue as I'm not quite sure how to rewrite this as pure Forms.
To prove the issue I made the following test app.
EventPage has no changes from the basic Prism ContentPage template other than EventPage.xaml.cs, where I've assigned basic handlers to the Appearing and Disappearing Events:
using System;
using System.Diagnostics;
using Xamarin.Forms;

namespace PrismErrorDemo.Views
{
    public partial class EventPage : ContentPage
    {
        public EventPage()
        {
            InitializeComponent();
            Appearing += EventPage_OnAppearing;
            Disappearing += EventPage_OnDisappearing;
        }

        private void EventPage_OnAppearing(object sender, EventArgs e)
        {
            Debug.WriteLine("Appeared");
        }

        private void EventPage_OnDisappearing(object sender, EventArgs e)
        {
            Debug.WriteLine("Disappeared");
        }
    }
}

My MainPage has two simple buttons which navigate to my EventPage, one relatively and one absolutely.
using System;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Navigation;

namespace PrismErrorDemo.ViewModels
{
    public class MainPageViewModel : BindableBase
    {
        private readonly INavigationService _navigationService;

        public DelegateCommand WorkingCommand { get; set; }
        public DelegateCommand NonWorkingCommand { get; set; }

        public MainPageViewModel(INavigationService navigationService)
        {
            _navigationService = navigationService;

            WorkingCommand = new DelegateCommand(WorkingCommandAction);

            NonWorkingCommand = new DelegateCommand(NonWorkingCommandAction);
        }

        private async void WorkingCommandAction()
        {
            await _navigationService.NavigateAsync("EventPage");
        }

        private async void NonWorkingCommandAction()
        {
            await _navigationService.NavigateAsync("http://app.com/EventPage");
        }
    }
}

When I navigate using await _navigationService.NavigateAsync("EventPage"); things behave exactly as they should. Both event handlers are called when they are supposed to be.
However, when I navigate using await navigationService.NavigateAsync("http://app.com/EventPage"); I get an Appearing event called as I navigate to the page, and using the back button to close the app will result in a Disappearing event being called. All other times closing and reopening the app fails to call either event.
I couldn't find any reference to this on the Github issues page and want to make sure I'm not missing anything obvious before posting this there.
Comment: Have you tried logging the bug here: https://bugzilla.xamarin.com/describecomponents.cgi
Comment: BTW, it would be good to say what device or emulator you are testing on.  Android, iOS, UWP?
Comment: Did you find any solutions or work arounds to this? I am trying to solve the exact same problem right now
Answer:
use following override method instead of custom

OnAppearing()
protected override void OnAppearing()
{
    base.OnAppearing();
}

OnDisappearing()
protected override void OnDisappearing()
{
     base.OnDisappearing();
}

Comment: FYI, That's equivalent to attaching a handler to `Appearing` and `Disappearing` events, so I would expect it to behave exactly the same as reported in the question.
Answer: I think you remove something when OnAppearing method created.
Try add base.OnAppearing();  back to the OnAppearing method.
Comment: No, what you describe is relevant when doing `protected override void OnAppearing()`. Even though OP named his function `EventPage_OnAppearing`, notice that it is *not* `override void OnAppearing`. Don't be misled by the name of the function; It is just an event handler; it has no `base` version.
Answer: ContentPage class derives a virtual OnAppearing() method from somewhere back in the hierarchy. Try overriding that function.
Comment: This is not really an answer but a comment. Once you have sufficient reputation you will be able to comment on posts.


Am getting nosuchmethod: the method map was called on null error in my dart code

Question: import 'package:flutter/material.dart';
import './question.dart';
import 'answer.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  var _questionIndex = 0;

  void _answerQuestion() {
    setState(() {
      _questionIndex++;
    });
    print(_questionIndex);
  }

  @override
  Widget build(BuildContext context) {
    var questions = [
      {
        'questionText': 'What\'s your favorite color?',
        'answer': ['Black', 'White', 'Red', 'Green', 'Yellow'],
      },
      {
        'questionText': 'What\'s your favorite animal?',
        'answer': ['Rabbit', 'Snake', 'Monkey', 'Lion', 'Dog'],
      },
      {
        'questionText': 'Who\'s your favorite instructor?',
        'answer': ['Max', 'Joel', 'Emma', 'Moses', 'Jones'],
      },
    ];
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('My App'),
        ),
        body: Column(
          children: [
            Question(questions[_questionIndex]['questionText'] as String),
            ...(questions[_questionIndex]['answers'] as List<String>)
                    .map((answer) {
                  return Answer(_answerQuestion, answer);
                }).toList()

          ],
        ),
      ),
    );
  }
}

I'm a beginner in flutter and I was trying to build this simple app but whenever I run the app it gives me NoSuchMethodError The method 'map' was called on null. Receiver: null Tried calling: map(Closure: (String) => Answer)
Was trying to call the map list i declared at the top which is question. Any help please
Comment: Does this answer your question? [What is a NoSuchMethod error and how do I fix it?](https://stackoverflow.com/questions/64049102/what-is-a-nosuchmethod-error-and-how-do-i-fix-it)
Answer: In one place you use 'answer' and the other 'answers'. just remove the last 's' from there


Apache Shiro - using database to read users, roles and permissions

Question: Currently I've a Swing app and I wan't to integrate Apache Shiro in order to authenticate and delegate permissions to certain roles. I've already managed to read the users from the shiro.ini file that I've created for tests, it looks something like this:
[users]
admin = 123456, Administrator

[role]
Administrator = *:*:*

However this was just for testing, now I need to read the permits from a database so I've stored in a database a table with the info I need and it looks something like this:
users (id,password,username)
userRoles (userId, role)
rolePermission (permissionID,permission,roleID)

I've been trying to understand tutorials that use a JDBC realm, however they use web applications or specials frameworks to manage their connection to the Database like Apache Derby or BoneCP, and they confuse me even more with these examples.
So what I'm asking it's how I need to configure the shiro.ini file if I wanna use a JDBC realm (with an Oracle database) and what classes the shiro.ini needs. Any examples or explanation will be appreciated!
Comment: Before I attempt an answer, do you know how to use JDBC and do you understand relational databases?
Comment: @BalusC not THEY, I said online examples, yes they are pretty straightforward, whenever you use the .ini file to get the users roles and permits, but no when you want to retrieve this information from a relational database
Comment: @SotiriosDelimanolis I'm not an expert, but to my understanding JDBC it's an application programming interface that allows you to execute operations on database from Java language
Answer: The Realm interface is a

security component that can access application-specific security
  entities such as users, roles, and permissions to determine
  authentication and authorization operations.

You can implement it to interact with any source for finding users and their permissions. If you want to interact with an SQL-based database, you can do that. If you want to interact with a text file, you can do that. If you want to interact with a web service, you can do that, too.
There are two useful (almost necessary) extensions of Realm which are AuthenticatingRealm and AuthorizingRealm. They provide an interface for authentication and authorization services, respectively. AuthorizingRealm extends AuthenticatingRealm. You should extend AuthorizingRealm to implement your own authenticating and authorizing logic.
Take an example: You have a database with a table Accounts as
username | password | role

a table Permissions as
permission_id | permission_name

and a table Account_Permissions
username | permission_id

In other words, an Account can have one role, but multiple permissions. With JDBC you can very easily query such a database and retrieve usernames, passwords, roles, and permissions. Your implementation of AuthorizingRealm would do just that and construct objects expected by Shiro's API.
Read this document on Shiro's authentication sequence to understand where the AuthenticatingRealm comes in.
As for the INI file, depending on how you implement your Realm, you would need to declare it as
myRealm = com.company.security.shiro.YourDatabaseRealm

possibly settings some properties
myRealm.databaseName = account_database

Shiro provides its own JdbcRealm class which extends AuthorizingRealm. This class makes some assumptions on the structure of your database, but you can customize it.
Comment: At the end I had to use BoneCP in order to provide a Data Source to Shiro, I was expecting to manage a connection without having to use any external libraries. Thank you for your patience on explaining it Was very helpful and at the end I managed to implement Shiro, and understand the concepts because of your brief over here.
Comment: @nivde92 You're welcome. Note that the above applies regardless of the `DataSource` you use. There are two different layers we're talking about.
Comment: The example tables only reflect *user-based* permissions, **not** *role-based* permissions. *Role-based* also typically implies that a subject can have multiple roles.


Find a formula for $a_n$ that satisfies $a_0 = 1$ and $a_{n} = 2 \sqrt{a_{n-1}}$ if $ n > 0$

Question: $a_{n} = 1 \ \ when \ \ n = 0 , and \ \ a_{n} =  2 \sqrt{a_{n-1}} \ \  when \ \ n > 0$
I'm a complete beginner at solving something like this, and I'm not sure where to start. The two methods I know are iterative expansion which I have trouble understanding how it works. And I know how to use induction, but I'm not sure how to apply it here.
Now just by doing a few terms by hand (hopefully correctly) here's what I got,
$ 1, 2, 2\sqrt{2}, 2\sqrt{2\sqrt{2}}$ and I'm pretty sure it just has n amount of $2\sqrt{2}$ under the sqrt sign.
I'm not sure how to progress with these types of problems in general. Thanks.
Comment: Notice $2\sqrt{2\sqrt{2}} = 2\sqrt{2}\sqrt{\sqrt{2}}=2\cdot2^{\frac{1}{2}}\cdot2^{\frac{1}{4}}=2^{1+\frac{1}{2}+\frac{1}{4}}$
Answer: $$a_n=2\sqrt{2\sqrt{2\sqrt{...}}}$$
$$=2^{(1+\frac12+\frac14+...+\frac1{2^{n-1}})}$$
$$=2^{\bigg(\frac{1-\frac1{2^n}}{1-\frac12}\bigg)}$$
$$=2^{2(1-\frac1{2^{n}})}$$
$$=4^{(1-\frac1{2^{n}})}$$
Comment: Yes the summation $1+\frac12+\frac14+...+\frac1{2^{n-1}}=\frac{1-\frac1{2^n}}{1-\frac12}$
Comment: How did you get to step 3?
Comment: The sum $1+x+x^2+...+x^{n-1}=\frac{1-x^n}{1-x}$. It is a geometric series with $a=1$ and $r=\frac12$ - https://en.wikipedia.org/wiki/Geometric_series.
Comment: So you found the summation of the series in the exponent?
Answer: Divide it by 4 and we get $${a_n\over 4} =\sqrt{a_{n-1}\over 4}$$
Let $b_n = a_n/4$ then we have $$b_n = \sqrt{b_{n-1}}$$ $$=\sqrt[2^2]{b_{n-2}}$$
$$=\sqrt[2^3]{b_{n-3}}$$
$$=\sqrt[2^4]{b_{n-4}}$$
$$\vdots $$
$$=\sqrt[2^n]{b_{0}}$$
Since $b_0= a_0/4 = 1/4$ we have $$a_n = 4\cdot \sqrt[2^n]{{1\over 4}}$$
Comment: As they set $b_n=\frac{a_n}{4}$ the term $b_{n-1}=\frac{a_{n-1}}{4}$ as well. This allows them to proceed to write $b_n=\sqrt{b_{n-1}}$ and then repeatedly apply this formula to get the result.
Comment: Hi! So this is starting to make some sense to me. Could you explain a few things though? At the start when you divide by 4, should there be a 1/2 left on the outside for the RHS? When you set $b_n$ to $a_n$/4 I'm having trouble following you equations, shouldn't the RHS be over 4 inside the square root like the top equation?
Answer: You've found the sequence begins $2^0,\,2^1,\,2^{3/2},\,2^{7/4}$. You may prove by induction that $a_n=2^{2-2^{1-n}}$. (It helps to first define $b_n:=\log_2 a_n$ so $b_0=0,\,b_{n+1}=\frac{b_n}{2}+1$, implying $b_n$ differs from the fixed point $2$ of $x\mapsto\frac{x}{2}+1$ by a geometric sequence.)


GDAL/ogr2ogr/ogrinfo produces an invalid pointer error each time I run it

Question: After installing ogr2ogr following the steps described here
https://mothergeo-py.readthedocs.io/en/latest/development/how-to/gdal-ubuntu-pkg.html
When I run either ogr2ogr or ogrinfo, I get the following error message

free(): invalid pointer

AFTER the execution of the command. Any advice to clean that?
ogrinfo --version
GDAL 3.3.2, released 2021/09/01
free(): invalid pointer
Aborted (core dumped)
-- Edit --
I may have found some kind of tip here.
email@example.com/msg36151.htmllibproj
Excerpt :

so your GDAL is linking against 2 PROJ versions libproj.so.15 and libproj.so.19. Make sure your libspatialite and libgeotiff versions are from the ubuntugis PPA, so they link gainst libproj.so.19 and no .so.15

Now I need to find a way to remove one library, without breaking my os...
Answer: There's a bug regarding linking against 2 PROJ versions libproj.so.15 and libproj.so.19
For Debian/Ubuntu, you can do to remedy it
<code>sudo apt purge gdal-bin -y
sudo rm -f /lib/x86_64-linux-gnu/libproj.so.15
sudo ln -s /lib/x86_64-linux-gnu/libproj.so.19 /lib/x86_64-linux-gnu/libproj.so.15
sudo apt install gdal-bin -y
</code>
Comment: Had the same error, ran these commands but still getting the error


Pequena duvida sobre Buttons

Question: Bom dia gostaria de saber se existe alguma maneira de tirar esta linha azul a volta da imagem, a imagem e um botão
Comment: Poderia elaborar um [mcve] e adicioná-lo na pergunta, por favor?
Comment: Possível duplicata de [CSS - Como remover linhas em volta do botão?](https://pt.stackoverflow.com/questions/273241/css-como-remover-linhas-em-volta-do-bot%c3%a3o)
Answer: Basta tirar o Outline da elemento button assim:
button:focus, button:active {
    outline: none;
}

Mas vc não deveria fazer isso, até por uma questão de Acessibilidade... http://www.outlinenone.com/
Pensen que vc pode tratar o outline com css para ele ter um efeito mais legal em vez de c remove-lo. Aqui na documentação da Mozilla vc pode ver alguns exemplos práticos de como estilizar o outline https://developer.mozilla.org/en-US/docs/Web/CSS/outline
Exemplos de estilização do outline: (repare que mesmo o elemento sendo um P eu posso colocar o outline nele como uma borda só que sem interferir no box-size )

p.dotted {outline-style: dotted; outline-color:red; outline-width: 5px;}
p.dashed {outline-style: dashed; outline-color:blue ; outline-width: 3px;}
p.solid {outline-style: solid; outline-color:green; outline-width: 3px;}
p.double {outline: 2px double gold;}

A dotted outline

A dashed outline

A solid outline

A double outline

Comment: funcionou perfeitamente, muito agradecido

Pequena duvida sobre Buttons


Como iniciar um download automaticamente quando o usuário entra em uma página especifica

Question: Eu tenho uma aplicação MVC C#, onde após o login (será na primeira vez que acessa a plataforma) o sistema inicie o download de alguns arquivos (os arquivos mudam de acordo com a necessidade do departamento, do mesmo modo que pode aumentar o número de arquivos ou diminuir).
Eu já tinha um código que gerava o download dinâmico, porém, não sei como fazer ele ser automático.
public ActionResult Download(string nome, string cpf)
    {
        try
        {
            string contentType = "";
            var arquivos = ListaArquivos();
            string nomeArquivo = (from arquivo in arquivos
                                  where arquivo.Nome == nome
                                  select arquivo.Caminho).First();
            string extensao = Path.GetExtension(nomeArquivo);
            string nomeArquivoV = Path.GetFileNameWithoutExtension(nomeArquivo);
            if (extensao.Equals(".pdf"))
                contentType = "application/pdf";
            if (extensao.Equals(".jpg") || extensao.Equals(".gif") || extensao.Equals(".png")) contentType = "application/image";
            if (extensao.Equals(".txt")) contentType = "text/plain";
            if (extensao.Equals(".docx")) contentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
            if (extensao.Equals(".doc")) contentType = "application/msword";
            File(nomeArquivo, contentType, nomeArquivoV + extensao);
        }
        catch (Exception ex)
        {
            TempData["ErrorMessage"] = true;
            TempData["Message"] = $"Não é possível realizar o download do Anexo! - {ex.ToString()}";
            return RedirectToAction("Formulario", new { cpf = cpf });
        }
    }

    private List<UploadFileResultVM> ListaArquivos()
    {
        List<UploadFileResultVM> lstArquivos = new List<UploadFileResultVM>();
        DirectoryInfo dirInfo = new DirectoryInfo(Server.MapPath(_localUpload));

        foreach (var item in dirInfo.GetFiles())
        {
            lstArquivos.Add(new UploadFileResultVM()
            {
                Nome = item.Name,
                Caminho = dirInfo.FullName + @"\" + item.Name
            });
        }
        return lstArquivos;
    }

E novamente, estou fazendo dessa forma pois não existe um padrão para os arquivos a serem baixados, a quantidade varia, cada área tem um padrão.
A diferenciação das áreas já sei como resolver, o problema é o inicio automático do download quando o usuário acessar a página.
Answer: Você precisa retornar o arquivo:
return File(nomeArquivo, contentType, nomeArquivoV + extensao);


Is strumming and finger picking universal for all the instruments?

Question: I am self taught Ukulele Player and playing Ukulele for almost one and half years now and can play almost all the open chords. Learnt everything with internet resources. And this is my first string instrument experience.
My learning journey (and almost sure, everyone's would be)  consisted of drastically slow sync up with chord switches while keeping the strum going on. It was a process, that I had to struggle for a long time and took me months to do it in an acceptable way. Same happened for some two to three finger picking patterns that I learnt.
I am planning to learn guitar next. My biggest worry, is if I have to restart all the journey of strumming and chord switching once again.
So, my question is, if I learn to strum and pick once on Ukulele, will the same learning be applied to other string instruments like Guitar, Mandolin, Banjo etc. or there will again be a learning curve with these instruments?
Having said that, I have seen guitar players who easily pick up any string instrument
Answer: Arguably, the learning curve is at its steepest when adjusting for the different size and dimensions of the new non-bowed string instrument, to the point where that might actually be the biggest factor for determining whether to continue with the new instrument. I had the good fortune to try out a guitar, an electric bass, and a ukulele at a local music museum, and the increased size of the guitar and bass (compared to the ukulele) was a turn-off for me after a few minutes fumbling with holding them and playing basic notes (I am only roughly 5 feet tall, and I am an adult).
The number of strings and different (standard) tuning(s) of the new non-bowed string instrument also make the learning curve steeper when learning that instrument given experience with an older non-bowed string instrument. Old shapes no longer work, and if this was your primary way of memorizing scales and chords, you now need to learn new shapes.
Other than those, experience with an older non-bowed string instrument should transfer fairly smoothly to the new one, especially if both have frets (at every semitone).
(This is speaking as someone who's also self-taught on the ukulele but who has tried a guitar and electric bass for a teeny bit.)
Comment: What I understood is, for a right handed player, all or most of the work done on right hand and subconscious mind can still be done on a new instrument, only new learning would be on the left hand?
Comment: Besides that, if this is your very first instrument, you're learning lessons that will help with *any* kind of instrument, even piano or winds, maybe without realizing it. You're learning about rhythm and tempo, higher and lower pitch, and even at the most basic levels, building pathways in your brain that learn to move your fingers in time with musical prompts.
Comment: @PalashKantiKundu - No, the right hand still needs to adjust for the new size, dimensions, number of strings, and tuning. Heck, even if all you do is change the tuning of your old instrument, the right hand *still* needs to adjust.
Answer: Strumming involves playing all strings (often) in one up or down movement.
Ukes have 4 strings, guitars 6, more widely spaced, so the action is similar, but not the same. It won't take long to adapt when strumming.
Finger picking is also different, in that the uke strings are closer, and there's only 4. So adapting will take more effort.
Chord shapes - again, different, but have a good think. Due to its tuning, the chord shapes are tranferrable from uke to guitar, with only the bottom 2 strings needing attention. It may be that you can use exactly the same shape fingering for some chords - it's just that the chord names will confuse - for example, an open G shape on uke will deliver an open D chord on guitar.
Another, obvious difference is the physical size - the guitar not only being longer and wider, but deeper, and needing to be strapped on when playing stood up.
Answer: In addition to the difference in physical size and the different (standard) tunings there are further drastic differences between the instruments you mentioned: The usage of plectra and the musical role of the instrument. These differences occur to some extent between all four mentioned instruments and are largest between the guitar and the mandolin:
Both instruments can be played with bare fingers or with a plectrum. Many guitarists are reasonably fluid in picking and strumming, both, with and without plectrum. Yet mandolinists usually never play without a plectrum. The spacing of the strings is too narrow for comfortable finger picking; especially the spacing of the double courses calls for a plectrum. Note also that plectra cut specifically for the mandolin tend to be smaller than plectra for guitar; not only due to the string spacing, but also due to the different thickness and mass of the strings.
If you start to use plectra, you will find plenty of new movements for your right hand (more unbiased: picking hand / non-fretting hand) to learn. In return you will be able to produce a lot more different sound, even if you stick to one instrument.
Both isntruments are suitable for playing melodies and for playing chords, as well. Melodic and chordal literature exists for both instruments. However, when they play together, the mandolin will mostly play melodies and the guitar will mostly play chords. The mandolin's higher pitch and the guitar's larger number of strings lead to this preassignment of roles, to which they lend themselves. In consequence the repertoire of these instruments differs.
Comment: Wow, this is a very good point. This was almost missed out. Thank you very much for making the answers richer.


AMPscript IF Statement returning variable as empty

Question: I am running into an issue in AMPscript where the following IF statement is returning my variable @shippingVendor as nothing when I call it. (Tracking Number is from data extension)
Assuming @trackingNumber = 23456
%%[
var @shippingVendor

IF Substring(@trackingNumber, 1, 1) == "2" THEN
   SET @shippingVendor = "https://www.nzpost.co.nz/tools/tracking/item/"
  ELSEIF Substring(@trackingNumber, 1, 2) == "T1" THEN
   SET @shippingVendor = "https://www.mainfreight.com/en-nz/tracking?trackingnumber="
  ELSEIF Substring(@trackingNumber, 1, 3) == "TP1" THEN
   SET @shippingVendor = "https://www.mytoll.com/?"
ENDIF
]%%

I would expect %%=v(@shippingVendor)=%% to return https://www.nzpost.co.nz/tools/tracking/item/ - however instead it returns nothing...can I please check if I am doing anything wrong?
Fairly new to AMPscript so would love your help on this - thanks in advance!
Comment: You'll get a lot more eyes on your SFMC questions over at [salesforce.stackexchange.com](http://salesforce.stackexchange.com), specifically with the [marketing-cloud](http://salesforce.stackexchange.com/questions/tagged/marketing-cloud) and [ampscript](http://salesforce.stackexchange.com/questions/tagged/ampscript) tags.
Answer: It's dangerous to do substring in AMPscript without checking for existence and length.  I'd also set a default value for the shipping vendor URL.
%%[

set @trackingNumber = 23456

set @shippingVendor = "DEFAULVENDORURLHERE"

if not empty(@trackingNumber) then

   IF length(@trackingNumber) >= 1 and Substring(@trackingNumber, 1, 1) == "2" THEN

      SET @shippingVendor = "https://www.nzpost.co.nz/tools/tracking/item/"

   ELSEIF length(@trackingNumber) >= 2 and Substring(@trackingNumber, 1, 2) == "T1" THEN

      SET @shippingVendor = "https://www.mainfreight.com/en-nz/tracking?trackingnumber="

   ELSEIF length(@trackingNumber) >= 3 and Substring(@trackingNumber, 1, 3) == "TP1" THEN

      SET @shippingVendor = "https://www.mytoll.com/?"

   ENDIF

endif

]%%
shippingVendor: %%=v(@shippingVendor)=%%

Output:
shippingVendor: https://www.nzpost.co.nz/tools/tracking/item/

Demo: https://mcsnippets.herokuapp.com/s/eiSqyIcb


How to use Services to create new node with Entity Reference field?

Question: I am able to create a new node with body field, but when I try to set the value for my entity reference field, I get

{"form_errors":{"field_drawing][und":"An illegal choice has been
  detected. Please contact the site administrator."}}

I am sending a structure similar to the working body field, but with 'target_id' instead of 'value':
<code>'field_drawing' = {
    'und' = [
        0 = {
            'target_id' = 123
        }
    ]
}
</code>
123 is the nid of an existing node. What would cause an 'illegal choice' response?
Answer: I figured out the solution from comments on this issue.
To set the field via services, you can set the field's widget type to "autocomplete" and instead of just sending the nid, send a string with the title of the referenced node, a space, and the nid inside parenthesis.
<code>'field_drawing' = {
    'und' = [
        0 = {
            'target_id' = 'Title of Node (123)'
        }
    ]
}
</code>
Comment: the title of Node can actually be any text. Only the nid matters when storing the field. This can save you from extra work trying to retrieve the node's title before calling the service.
Comment: @LKallipo is correct, you can pass the value of `'... (123)'` as a string for the`target_id` property instead:
Answer: In my case, an external script had to create nodes using json messages so I wanted to only pass the ids of the referenced nodes. to do this you have to switch the widget type to 'select list' and send the following:
<code>'field_drawing':{
    'und':[123,124]
}
</code>
Answer: Just for reference.
I got problem with such data structure in my project, using entityreference field in Entityform entity.
This json fragment:
<code>..."field_f_s_culture":{"und":[{"target_id":"... (336)"}]},...
</code>
triggers next error:
<code>SQLSTATE[HY000]: General error: 1366 Incorrect integer value: '... (336)' for column 'field_f_s_culture_target_id' at row 1)
</code>
I was have to revert entityreference field structure to:
<code>..."field_f_s_culture":{"und":[{"target_id":"336"}]},...
</code>
to get it work.


filter array object from redux react typescript

Question: I'm mapping an array object that is obtained by redux state. I need to create a search filter that filters the array based on the key name. I'm struggling with the this filter, it just doesn't work and I'm going kind of crazy trying various ways.
items contains the array object, filtered contains the typed text from the input, all of those I can get from the redux state and they are saved to props using mapStateToProps
State:
items: [{name: "bla"}, {..}, {..}] (50 objects in array)
filtered: "test"

reducer:
case SEARCH:
      return {
        ...state,
        filtered: action.value
      };

component:
    const Tournaments = (props: TournamentInterface) => {
      const {
        items,
        filtered
      } = props;

    const mapStateToProps = (state: { tournaments: TournamentInterface }) => {
      return {
        items: state.tournaments.items,
        loading: state.tournaments.loading,
        error: state.tournaments.error,
        filtered: state.tournaments.filtered
      };
    };

        return (
         <ItemContainer>
        {items &&
                !loading &&
                items
                  .filter((item: any) => item.name.toLowerCase() === filtered)
                  .map(
                    (
                      item: {
                        name: string;
                        game: React.ReactNode;
                        participants: {
                          current: React.ReactNode;
                          max: React.ReactNode;
                        };
                        startDate: Date;
                      },
                      index: number
                    ) => (

{item.name}

                    )
                  )}
         </ItemContainer>
          );
};

Comment: oh hey I just added includes() this and it works:  .filter((item: any) => item.name.toLowerCase().includes(filtered))
          .map(). But if you can see a nicer way to create this please post an answer.
Comment: You can do the filter in a selector function and use that in mapStateToProps. This moves logic out of the component and into a selector you can re use for other component if needed.
Comment: Hey, I'm writing up an answer for you, but if you could post your `TournamentInterface` I can make sure that I get it right.
Answer: There's a lot to unpack here.  You should not need to assign a type inside a .map callback because the type will be known if the array itself is typed correctly.  But clearly it's not.  So we need to fix your types!
You haven't included your TournamentInterface type but I can get an idea of what it is by working backwards. Since these items are coming from Redux the properties need a more specific type than ReactNode since some of the types that are assignable to ReactNode are not serializable.  Your dates should be stored as raw timestamps rather than Date objects for the same reason.
Try this:
interface Item {
  name: string;
  game: string;
  participants: {
    current: number;
    max: number;
  };
  startDate: number;
}

interface TournamentInterface {
  items: Item[];
  loading: boolean;
  error?: string | null;
  filtered: string;
}

type RootState = {
  tournaments: TournamentInterface;
};

I read somewhere its better not to filter the state directly in redux, but in the component. Yes, when I try that the items array is changed in the state and doesn't not return to show all the objects because it has been filtered.

I agree with that first sentence completely and the second sentence is why.  If you filter the items property then you lose items.  If you store the filtered array in a separate property then you have duplicated data.

You can do the filter in a selector function and use that in mapStateToProps. This moves logic out of the component and into a selector you can re use for other component if needed. – HMR

I like @HMR's suggestion here.  You can use reselect to create a memoized selector that only returns a new value if the state changes.  I'm using your filter function from the comments.
import { createSelector } from "reselect";

const selectFilteredItems = createSelector(
  // input selectors
  (state: RootState) => state.tournaments.items,
  (state: RootState) => state.tournaments.filtered,
  // combiner - types here are inferred correctly
  (items, filtered) =>
    items.filter((item) =>
      item.name.toLowerCase().includes(filtered.toLowerCase())
    )
);

I'm going to use useSelector instead of mapStateToProps as that's the newer, current approach.  We can make use of the createSelectorHook utility so that the RootState type is automatically inferred.
import { createSelectorHook } from "react-redux";

const useSelector = createSelectorHook<RootState>();

const Tournaments = () => {
  const loading = useSelector((state) => state.tournaments.loading);
  const filteredItems = useSelector(selectFilteredItems);

  return (
    <ItemContainer>
      {loading ? (
        <Spinner />
      ) : (
        filteredItems.map((item, index) => (

{item.name}

Started: {new Date(item.startDate).toDateString()}

        ))
      )}
    </ItemContainer>
  );
};

Answer: Try to filter in redux.
case SEARCH:
 return {
   items: state.items.filter((item: any) => item.name.toLowerCase().includes(filtered.toLowerCase())),
   filtered: action.value
 };

Comment: I read somewhere its better not to filter the state directly in redux, but in the component. Yes, when I try that the items array is changed in the state and doesn't not return to show all the objects because it has been filtered. But good idea.
Comment: Actually you don't need to keep items in redux if they are not useable in other components, also filter key too. ( read article about "You don't need redux" ) . Instead store in component state and pass down where you need.
Comment: I would love to not use redux but its a requirement of the project.


Ultrafilters in $\ell^\infty$

Question: Let $Ult(\mathbb{N})$ be the set of ultrafilters over $\mathbb{N}$ and $L=\{f\in(\ell^\infty(\mathbb{N}))':f(x)\in\overline{x(\mathbb{N})},\forall x\in\ell^\infty(\mathbb{N})\}$.
I want to prove that
$$\Phi:Ult(\mathbb{N})\to L\\
\text{ }\text{ }\text{ }U\mapsto\lim_{U}$$
is well-defined. I know that for each $U\in Ult(\mathbb{N})$, $\lim_{U}$ is linear but I don't know if it's continuous.
Comment: I don't understand some of your notation.....  Let $U \in Ult(\Bbb N).$ For each  $x=(x_n)_{n\in \Bbb N}\in l^{\infty}$ let $f_U(x)=r$ iff $\{n:x_n\in V\}\in U$ for every nbhd $V$ of $ r.$ Then $ f_U$ is a well-defined continuous linear functional... Is this what you are trying to prove?
Comment: Yes, DanielWainfleet. I want to prove this. I forgot to specify. I'm a beginner in ultrafilters.
Comment: I was typing a thorough answer when the post became deleted.
Answer: Note that $\lim_U (x) \in\overline{x(\Bbb N)}$, hence $|\lim_U x|≤\|x\|$ for all $x\in\ell^\infty(\Bbb N)$ and $\lim_U$ is a bounded linear map, hence continuous.
You may alternatively view $\lim_U$ as a point evaluation map, which is also necessarily continuous.
First remember that if $x\in \ell^\infty(\Bbb N)$, then $x:\Bbb N\to \overline{x(\Bbb N)}\subset\Bbb C$ is valued in a compact set (as $x$ is bounded) and hence factors over the Stone-Cech compactification, that is there is a map $\beta x:
\beta\Bbb N\to \Bbb C$ so that $x = \beta x\circ\iota$ where $\iota$ is the inclusion $\iota:\Bbb N\to \beta\Bbb N$ into the Stone-Cech compactification. (All this can be expressed in a commutative diagram, but I don't know how to do commutative diagrams in MathJax.)
We may thus identify $\ell^\infty(\Bbb N)$ with $C(\beta\Bbb N)$ (if you give the space on the right the uniform norm these are then the same as normed vector spaces). Now the thing is that $\beta\Bbb N$ is compact and hence every ultra-filter converges. Thus $\lim_U$ applied to a function of $C(\beta\Bbb N)$ is nothing other than the point evaluation of that function at the limit of $U$, which defines a continuous functional on $C(\beta \Bbb N)$.
Comment: But, why $\lim_{U}(x)\in \overline{x(\mathbb{N})}$?
Comment: Because $\overline{x(\Bbb N)}$ is closed, or does your problem lie at another part of that statement?
Comment: Yes. My question was wrong. I understand better now, thanks.
Comment: Why $\lim_{U}(x)\in \overline{x(\mathbb{N})}$ implies that $|\lim_{U}(x)|\leq \sup_{n\in\mathbb{N}}|x_n|$ ?
Answer: Another way to see that $\lim_U$ is continuous is to use monotonicity.
If you have any ultrafilter $U$ and two sequences such that $x\le y$ (i.e., $x_n\le y_n$ for each $n\in\mathbb N$), the you also have $\lim_U x\le\lim_U y$.
If you take as one of the sequences a constant sequence, you will get that
$$\inf x \le \lim_U x \le \sup x.$$
And it's not difficult to prove this also directly, without using monotonicity of $\lim_U$.
And from this you get that $|\lim_U x| \le \sup\limits_{n\in\mathbb N} |x_n|$, i.e., $|\lim_U x| \le \|x\|$.

Mainly as a possible place where to find some references for limit along ultrafilter (filter, filter base), I'll add links to these two answers of mine: Basic facts about ultrafilters and convergence of a sequence along an ultrafilter and Where has this common generalization of nets and filters been written down?

Ultrafilters in $\ell^\infty$


Almost sure converges to a constant

Question: I am relatively new to measure theory and would appreciate if anyone can help me with proving the following assertion. The following statement seems trivial. But I would like to see a formal proof of it or at least identify which existing result (theorem) can be used to show.
Claim:
If $X_n$  a r.v converges a.s to a deterministic quantity, say, $C$.
Then $\lim_{n\to\infty}E[X_n]=C$.
Thanks
Comment: The claim is false. Try to find a counterexample. Hint: the dominate convergence theorem requires that there is a integrable r.v. that dominates the sequence.
Comment: oh!, okay. So just to clarify, if if we add the condition that $|X_n|< X$ for all n, where X is integrable r.v. Then by dominated convergence theorem would the above assertion be true?
Comment: Yes. And it would be also true if the limit of the $X_n$ is any random variable (not necessarily constant).
Answer: Let $Y$ be uniformly distributed on $(0,1)$ and suppose $\displaystyle X_n = \begin{cases} n & \text{if }Y<1/n, \\ 0 & \text{if }Y>1/n. \end{cases}$
Then $\Pr\left( \lim\limits_{n\to\infty} X_n=0 \right) = 1$ and $\lim\limits_{n\to\infty}\operatorname{E}X_n = \lim\limits_{n\to\infty} 1 = 1 \ne 0$.
This can happen because $\operatorname{E}\sup\limits_n X_n = \infty$.
If $\operatorname{E} \sup\limits_n |X_n|<\infty$ then no such problem occurs.  As mentioned in the comments, the dominated converges theorem entails that.
Proof that $\operatorname{E}\sup_n X_n = \infty$:
Notice what happens if $\dfrac 1 {m+1} < Y <\dfrac 1 m$: The fact that $Y< \dfrac 1 m \vphantom{\dfrac\int{\displaystyle\int}}$ means that $X_1 = 1,\ X_2=2,\ X_3=3,\ \ldots,\ X_m=m$, and the fact that $1/(m+1)<Y$ means that $X_{m+1}=X_{m+2}= X_{m+3}=\cdots = 0$. So in that case, $\sup=m$.
$$
\Pr\left(\sup\limits_n X_n = m \right) = \Pr\left( \frac 1 {m+1} < Y < \frac 1 m \right) = \dfrac 1 m - \dfrac 1 {m+1}.
$$
Then we have
$$
\operatorname{E}\sup_n X_n = \sum_{m=1}^\infty m\Pr\left( \sup_n X_n = m \right) = \sum_{m=1}^\infty m\left( \frac 1 m - \frac 1 {m+1} \right) = \sum_{m=1}^\infty \left( 1 - \frac m {m+1} \right).
$$
This series of positive terms must diverge to $\infty$ because its terms do not approach $0$.
(I find myself wondering whether there's some standard name in the literature for this particular probability distribution and whether it arises naturally somehow.)
Comment: Could you please elaborate how you got $E sup X_n=\infty$ ?
Comment: @Indrajit : I've added a proof to the answer. ${}\qquad{}$
Comment: The term of the series does approach 0. But it deverges: it is the harmonic series

Almost sure converges to a constant


WMS Service Tilecache Python 403 error

Question: I´m trying to migrate a Webserver + Mapserver to a new Ubuntu 12.04 machine.
Everythings (apache2, mapserver 6.2.1 ) working so far, except a tilecached wms service (tilecache 2.11-2 is installed) which needs an extra authentification.
When I´m calling the cgi script  (which deals the request) directly I get following
error:
<code>    An error occurred: cannot identify image file
  File "/usr/lib/pymodules/python2.7/TileCache/Service.py", line 343, in cgiHandler
    format, image = service.dispatchRequest( params, path_info, req_method, host )
  File "/usr/lib/pymodules/python2.7/TileCache/Service.py", line 208, in dispatchRequest
    return self.renderTile(tile, params.has_key('FORCE'))
  File "/usr/lib/pymodules/python2.7/TileCache/Service.py", line 138, in renderTile
    data = layer.render(tile, force=force)
  File "/usr/lib/pymodules/python2.7/TileCache/Layer.py", line 436, in render
    image = self.renderMetaTile(metatile, tile)
  File "/usr/lib/pymodules/python2.7/TileCache/Layer.py", line 397, in renderMetaTile
    image = Image.open( StringIO.StringIO(data) )
  File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 1980, in open
    raise IOError("cannot identify image file")
</code>
I searched for hours, but cannot find a misconfiguration within the mapfiles or tilecache.cfg. All files should have correct permissions also. Unfortunately my access and error.log don´t tell me more about this.
My last guess is that something changed in python 2.7 f.e. different parameters (before we used python 2.53).
I know my question is a bit weak, but maybe someone had a similar situation. Or someone has a tip what else can be tested to find the error?
with kind regards,
Toni
Answer: OH no!
If anybody has the same problem,
check
<code>allow_url_fopen =
</code>
in your php.ini
I turned it of for security reasons. Of course the WMS couldn´t work!!

WMS Service Tilecache Python 403 error


How to check if input is a number

Question: Im trying to check if the input is a number and if not its going to say that the input is wrong.
int menu()
{
    int menyval;
    printf(" 1. Quit\n 2. Add question \n 3. Competitve \n 4. Show all questions\n");
    scanf_s("%d", &menyval);
    if (isdigit(menyval)==0)
    {
        system("cls");
        return menyval;
    }
    else
    {
        printf("That's not a number!");
    }
}

Answer: Check the result of scanf_s()
int menu()
{
    int menyval;
    printf(" 1. Quit\n 2. Add question \n 3. Competitive \n 4. Show all questions\n");
    if (1 == scanf_s("%d", &menyval)) {
        system("cls");
        return menyval;
    }
    else {
        printf("That's not a number!");
    }
}

scanf_s("%d",...) will return 0,1, (the count of successfully scanned fields) or EOF
1: A number was scanned.
0: Nothing saved `&menyval`, input is not a character representation of a number
   User input remains in `stdin`.
EOF:  End-of-file (or input error occurred).

Comment: Now I have another intressting question.. The first thing i enter it just ignors it...
Comment: For some reason i need to enter two times before it take my input, any ideas? @Henrik
Comment: @Petrus Lindblom please detail the key sequenced used when you say "enter two times".
Comment: When i run the code for my switch case and im about to enter a number or now also letters I need to enter a letter or a number two times before it actually happends something... im so confused about it
Comment: @Petrus Lindblom  There is no "switch case" in this post.  It appears you are asking about some other code.  Remember 1) that `stdin` is typically "line buffered".  That means `scanf_s()` will not see any input until a `'\n'` occurs. 2) If a letter is entered with `scanf_s("%d"...`, the function returns 0 and the input remains in `stdin`.
Comment: @Petrus Lindblom There are many approaches.  A robust approach is to read user input with `fgets()` and then use `sprintf()`, `strtol()`, etc to parse the buffer read.
Comment: lol! added fflush(stdin) before the scanf_S and problem solved. thank you!
Comment: the statement: fflush(stdin) is, per the standard, undefined behaviour.  so do not use it.  Most compilers will flag it as an error.
Comment: suggest put the prompt/input in a loop, that exits when a valid number (1..4) has been entered
Answer: scanf_s, like scanf is supposed to return the number of fields successfully converted and assigned. So look at the return value of scanf_s instead of calling isdigit.
isdigit checks if its argument is between '0' and '9', that is between 0x30 and 0x39 (48-57). Your integer menyval will at success probably be between 1 and 4 so isdigit will fail as isdigit is really intended for chars instead of integers.

How to check if input is a number


Is the Legendre symbol (9/8) the same as Legendre symbol $3^2/2$?

Question: Is the Legendre symbol (9/8) the same as Legendre symbol $3^2/2$? if so, by what property?
Comment: in the definition of Legendre symbol, the bottom number is prime
Comment: That isn't a Legendre symbol.
Answer: The question does not make sense as stated,
because, in the definition of Legendre symbol, the bottom number is an odd prime.


Cores aleatórias nos botões

Question: Gostaria que os meus botões alterassem a cor toda vez que a pagina for atualizada. Fiz um código em java script que não está dando certo e gostaria de ajuda para identificar o meu erro.

Essa seria a forma certa?

<!DOCTYPE html>

    <meta charset="UTF-8"/>
    <title>Menu inicial</title>

menu inicial

    <form>
            <button type="submit">Cadastro</button>
            <button type="submit">Consulta</button>
            <button type="submit">Relatorio</button>
        </form>

Answer: O problema é que document.button não contém todos os botões da tela, use document.querySelectorAll('tag') para isso, depois percorra o array modificando o estilo de cada elemento

<!DOCTYPE html>

  <meta charset="UTF-8" />
  <title>Menu inicial</title>

menu inicial

  <form>
    <button type="submit">Cadastro</button>
    <button type="submit">Consulta</button>
    <button type="submit">Relatorio</button>
  </form>

Além disso precisa que o código javascript carregue depois dos botões, pode colocar no final do html ou usar o atributo defer
Uma opção é criar as variáveis dentro do loop e os botões terão cores diferentes também:
let btns = document.querySelectorAll('button')
for(button of btns) {
    let r = Math.floor(Math.random() * 255),
        g = Math.floor(Math.random() * 255),
        b = Math.floor(Math.random() * 255);

  button.style.backgroundColor = `rgb(${r}, ${g}, ${b})`;
}

Nesse último também usei o template literal para interpolar variáveis e strings, mas é opcional
Answer: O problema está na forma de selecionar os botões. O document.button não existe.
Uma forma é usando document.querySelectorAll usando como seletor a tag button dentro de form, e depois fazer um laço para alterar todos:

<!DOCTYPE html>

    <meta charset="UTF-8"/>
    <title>Menu inicial</title>

menu inicial

<form>
   <button type="submit">Cadastro</button>
   <button type="submit">Consulta</button>
   <button type="submit">Relatorio</button>
</form>

Ainda incluí o evento DOMContentLoaded para que o script só seja
  executado quando o DOM for carregado.

Cores aleatórias nos botões


Warning: Cannot use a scalar value as an array

Question: function theme_test($form) {

  $output = '';

  foreach($form['field'] as $key => $val){

    $output .= '
';
    $output .= drupal_render($val['uid'. $key]);
    $output .= '
';
    unset($key,$val);
  }

  return $output;

}

When I run this code, I get the following warning message:

Warning: Cannot use a scalar value as an array in theme_test()

How do I resolve this, and what is the reason behind this warning?
Comment: You should add more information, especially why you expect `$val` to be an array. As it is, it's more a question about PHP, and not a question specific for Drupal. The meaning of the warning doesn't change, in Drupal.
Answer: There's somehting funky happening on this line:
$output .= drupal_render($val['uid'. $key]);

$val is not an array, you'll need to rethink your PHP code. Do a Google search for "Warning: Cannot use a scalar value as an array" and you'll see a bunch of cases where other users are dealing with the same issue. As an example:
PHP : Cannot use a scalar value as an array
EDIT:
Looking at your code again, this line looks suspect:
unset($key,$val);

You're in a loop that is using these values. Applying an unset could result in the issue in addition to the point I made above.
Comment: That is true: Using `unset($key,$val);` is completely useless; it would be like unsetting the local variables used in a function before it returns the control back to the caller function.


What is the best way to parse a xml file without xmlns?

Question: For reason beyond my control, I must parse a xml without xmlns tag. I believe that it is a bad practice because it miss namespace control. Anyway, I must program for such scenario. What could be the best way to face it? I try setNamespaceAware = false and it does work for file without xmlns tag but it seems that it doesn't work properly when reading xml with xmlns tag. Plus this, I guess that by setting any awareness configuration to false isn't a good practice. I read some article telling to add the xmlns to the file programmatically but I am in doubt if it might be a good option. Any comment will be appreciated.
javax.xml.parsers.DocumentBuilderFactory fac = new org.apache.xerces.jaxp.DocumentBuilderFactoryImpl();
fac.setNamespaceAware(true);
org.w3c.dom.Document d = null;
javax.xml.parsers.DocumentBuilder builder = fac.newDocumentBuilder();
d = builder.parse("C:/my_folder/my_file.xml");

<?xml version="1.0" encoding="UTF-8"?>
<c:de format="N" lengthField="0" maxLength="012" minLength="012" name="AMOUNT, TRANSACTION" number="004" subFields="00"/>

Answer: Here are the statements that I use to parse a XML file
DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
dfactory.setNamespaceAware(false);
dfactory.setValidating(false);
DocumentBuilder bldr = dfactory.newDocumentBuilder();
bldr.setErrorHandler(new ErrorHandler() {
    public void warning(SAXParseException exception) throws SAXException {
        // ignore warnings
    }

    public void error(SAXParseException exception) throws SAXException {
            // ignore parse validation errors
    }

    public void fatalError(SAXParseException exception) throws SAXException {
            throw exception;
    }
});
Document doc = bldr.parse(new InputSource(is));

I think you need to turn validation off if you turn namespace off.
There really is nothing wrong with using XML this way.  Namespace help with a specific kind of evolution of the schema, but not all kinds, and if you analyze it far enough, namespace only delays the problem, but does not actually solve the problem.  It depends on the specific XML, and some are managed in a way that requires the name space.  But have no guilt if the XML is not managed this way.
Comment: Thank you for your answer. Do you know the difference between " ... new org.apache.xerces.jaxp.DocumentBuilderFactoryImpl();" and " ... DocumentBuilderFactory.newInstance();"? there isn't such option "setNamespaceAware" in the code that I start to mantain because it is coded with xerces.
Answer: If a schema can be created for a file, create that schema (without targetNamespace attribute, that means, target namespace is ""), generate classes (for example with xjc/JAXB) and parse.
Comment: In such cases I sometimes create a schema WITH targetNamespace and fix XML before giving it to XML mapping library.
Comment: Thank you dor your ansewer but I didn't understand your suggestion. The application receives a lot of xml files from other application which I don't have control. Are you suggesting that I created a XSD file for each type of xml that I can receive? If so, what will this help me? I guess that I will have to edit the xml file anyway.


How to add 1 month to selected DateTimePicker

Question: I'm having an issue with DateTimePicker.
What I am currently trying to do is based off of what text is in lblPrevSem(Previous Semester), which is getting its selection from a drop down on a previous screen, i want to add a certain amount of time to the DateTimePicker.
Public Property CustomFormat As String
Dim SemesterMonths As Integer
Dim SemesterDays As Integer

Private Sub DeptCreatePrevSch_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim SemesterYear() As String = DeptPrevSch.CboSem.Text.Split(",")

    lblPrevSem.Text = SemesterYear(0)
    cboYear.Text = Date.Now.Year
    For i As Integer = 0 To 5
        cboYear.Items.Add(Date.Now.Year + i)
        cboYear.SelectedIndex = 0
    Next

    If InStr(lblPrevSem.Text, "Fall") Then
        SemesterMonths = 1
    ElseIf InStr(lblPrevSem.Text, "Spring") Then
        SemesterMonths = 1
    ElseIf InStr(lblPrevSem.Text, "Summer") Then
        SemesterDays = 14
    End If

    Call dtpStart_ValueChanged(sender, e)
End Sub

Private Sub dtpStart_ValueChanged(sender As Object, e As EventArgs) Handles dtpStart.ValueChanged

    Dim StartDate As Date
    Dim StartStringDate As String
    Dim EndDate As Date
    Dim EndStringDate As String

    dtpStart.Format = DateTimePickerFormat.Custom
    dtpStart.CustomFormat = "MMMM dd, yyyy  dddd"

    StartDate = dtpStart.Value.ToString
    StartStringDate = StartDate.ToString("MMMM dd, yyyy  dddd")
    lblRegStartDate.Text = StartStringDate

    EndDate = dtpStart.Value.AddMonths(SemesterMonths)
    EndDate = dtpStart.Value.AddDays(SemesterDays)
    EndStringDate = EndDate.ToString("MMMM dd, yyyy  dddd")
    lblRegEndDate.Text = EndStringDate

End Sub

I can get it to add in days just fine but when ever i try and add in 1 month, it doesn't seem to work at all.
I've tried multiple different ways to add in a 1 month but nothing so far has worked. The closet ive been was adding in 30 days but then that doesn't account for months that have 31 days.
Reg Start Date is what ever the DateTimePicker is and Reg End Date should be the added days based off of what lblPrevSem is
Both Reg Start/End Date are displayed as labels
(i.e. Fall = 1 Month, Spring = 1 Month, Summer = 2 Weeks)
Comment: First it is a really bad idea to call an event that way, events are supposed to indicate user interaction.  Put the code in a method can call it from whereever.  `Dim StartDate As Date ... = dtpStart.Value.ToString` makes me think Option Strict is not on.  Some of those dtp properties could be set in the designer once rather than over and over in a method
Comment: i didnt know these could be set in the designer?
Comment: And i completely forgot to set option strict on. Well damn all that work and for nothing....back to work then i guess....thanks for reminding me about that.
Comment: I was talking about the Format and CustomFormat - they really do not need to be set each time the value changes.  You can set Option Strict on as a permanent default: Tools -> Projects & Solutions -> VB Defaults.  To set it for this project: Project Properties -> Compile tab/page
Comment: thanks for that tip. Luckily i just need to redo this form. A lot of work for nothing....hate that
Comment: in the mean time im going to go cry in a corner
Answer: Your problem is that you are resetting the value for EndDate after adding the SemesterMonths value.  You should add the SemesterDays value to the EndDate variable, not reset the value of EndDate with dtpStart.Value.AddDays(SemesterDays):
EndDate = dtpStart.Value.AddMonths(SemesterMonths)
EndDate = EndDate.AddDays(SemesterDays)

Comment: thanks, ill look into that after i rewrite all this since i forgot to put option strict on like an idiot
Answer: Just get the datetimepicker value and put .AddYears(0) or .AddDays(0) or AddMonths(0) behind it.
But you can also use them all at the same time.
nextServiceDateTimePicker.Value.AddYears(0).AddDays(0).AddMonths(0);

Just replace the 0 with lets say i and give it the value you need it to be.


scale of variance in Gaussian process

Question: When performing Gaussian process regression, the variance at a prediction point is given by
$var[f_*] = k(x_*,x_*) - k_*^T(k+\sigma_n^2I)^{-1}k_*$ (Equation 2.26 from GPML)
The variance is not dependent on the observed targets, but only on the inputs. Does that mean that the targets need to be scaled? If so, what's the appropriate scaling? Otherwise, it seems wrong the relative variance changes depending on what units or scale are used for the targets.
Answer: The contradiction you arrived at makes sense. This sentence should be read with caution:

The variance is not dependent on the observed targets

The hyperparameters associated with the covariance function learnt during the training would depend on the observed targets.  That way the target values affect the prediction variance indirectly.  You can verify that by running a small demo in gpml.  Think about it ... The covariance function should consider most training inputs with similar target values similar and training inputs with dissimilar target values dissimilar.  This is achieved by learning appropriate hyperparameters associated with the covariance function.
Once the hyperparameters are learnt, the target values play no further role as equation 2.26 indicates.
Suppose another scenario where the hyperparameters of the covariance function are known a priori therefore they are not to be learnt during the training.  In such a scenario target values play no role at all.

scale of variance in Gaussian process


Expected no of Moves to get a Subregion Ai , from k subregions of a land with respective areas.

Question: Given $K$ regions on a land with subregions  of areas A1,A2,A3....Ak , a random sub region is given to a farmer one at a time , what is the expected no of moves that any farmer gets the land Ai or say A1.
Comment: What have you done so solve it?
Answer: Let $E_{i}$ be the probability that land $A_{1}$ is allotted in $i^{th}$ move. Observe that $E_{i}$ = $1 \over k$.
This is because we have to allocate $A_{1}$ in $i^{th}$ move, so the first $i-1$ moves should allocate any land other than $A_{1}$.
$$E_{i} = {k-1 \over k} {k-2 \over k-1}..{1 \over k-i+1} = {1 \over k}$$
$$E(E_{i}) = { 1.E_{1} + 2.E_{2}+ .. + k.E_{k}} = {k+1 \over 2}$$


Desenvolvimento C# Mobile precisa de Mac?

Question: Estava pesquisando sobre ferramentas para desenvolvimento mobile (iOS, Android) e me deparei com o Xamarin.
Achei interessante a proposta, ainda mais por trabalhar em conjunto com o Visual Studio. Fiz o download e configurei, porém, apesar de estar com uma maquina intermediaria (i3, 6GB de RAM) tive um tempo absurdo para executar aplicativos testes distribuídos como exemplo pelo Xamarin, além do aplicativo executar com lag extremo no meu celular emulado.
Pesquisei e me deparei com a informação de que para desenvolver para iOS, preciso de um mac os sendo executado em minha maquina, seja ela virtual ou um mac. Porém, se possuo lag em uma maquina regular, imagino em uma maquina virtual.
Existe algum modo de otimizar a performance de emulação? Não existe meios de trabalhar com o Xamarin para iOS sem rodar mac os?
Existe algum outro programa que trabalhe em conjunto com o Visual Studio para desenvolvimento mobile ou até mesmo que seja otimizado para C#?
Answer: A Microsoft além de abrir o .NET comprou a Xamarin e preparou o Visual Studio para atender o desenvolvimento nas diversas plataformas. Já nesta versão tem até emulador para Android. E incluiu o Xamarin até mesmo na versão Community. Há uma espécie de emulador para iOS no Visual Studio 2017 Enterprise.
Estou respondendo mais para não ficar sem resposta. Fique de olho nos acontecimentos, quem sabe o problema é resolvido com a nova postura. Mas não sei se há alguma coisa que possa de fato eliminar a necessidade do Mac, isto parece ser uma limitação da plataforma.
A Xamarin tem um serviço que ajuda nisto. Me parece ser a solução mais viável. Se não usar um serviço assim, precisa de um Mac para não incorrer em violação dos termos da Apple. Isto vale para qualquer tecnologia de desenvolvimento para iOS.
Coloquei no GitHub para referência futura.


I want to split string in text words and get first character on each string

Question: I have a text box with text like " Spring street" and i want split into two words and get first character of each word like
"SS"
i am beginner so please help me
Comment: Please take the [tour] and read [ask]. After that has been done, please edit your question accordingly
Comment: Show the code you've tried so far, and how / where it isn't working.
Comment: I think this was also ask in this thread. TY
[here](https://stackoverflow.com/questions/52829822/split-character-in-word)
Comment: `Dim output() As Char = input.Split().SelectMany(Function(c) c.Take(1)).ToArray()`
Answer: <code>' Split string based on spaces.
  Dim words As String() = s.Split(New Char() {" "c})

  Dim answer As string
  answer = answer(0).Substring(0, 1) + answer(1).Substring(0, 1)
</code>
Answer: welcome to stackoverflow.
Below is a piece of code that returns the requested
<code>    ' Define the string that needs to be splitted
    Dim texttosplit As String = "Spring street"

    ' Split the string into words
    Dim words As String() = texttosplit.Split(" ")

    ' Loop each word to compile a result string
    Dim resultstring As String = Nothing
    For Each word As String In words
        resultstring = resultstring & word.First
    Next
</code>


Area under parametric curve that loops back around itself

Question: I understand that the area under a parametric curve defined as $(x(t),y(t))$ from $a$ to $b$ can be found with $\int_a^b y(t) \space x'(t) \space dx$. What I don't understand is what happens to the area when the curve loops back around itself.
For example, I have a curve defined by $x(t) = \frac{\pi}{2} + t + cos(t)\cdot1.8$ and $y(t) = sin(t)+1$, and I want the area under this curve on $[-\frac{\pi}{2}, \frac{3\pi}{2}]$

When I try to find the area with this method, I get $0.2\pi$ If I tried to shade in the $0.2\pi$ on a drawing of this graph, where would I shade? What is the "area" that I am getting?
Also, if I replace the $1.8$ with a $2$, the area becomes $0$. Why is this?
Answer: The area that you compute is a closed self-intersecting shape (it is closed by a segment of the $x$ axis).
One of the parts is traversed clockwise and the other anticlockwise, so that the areas substract from one another, and the total can even vanish.
If you want the absolute area, you need to find the intersection point and compute the two areas separately.


Print module download pdf file name change characters into HTML entities

Question: I am using print module to generate pdf using dompdf library. I am facing issue with file name which node title have ampersand(&) sign, this character is converting into &.
For example- If file name is hello & drupal then the file name become hello & drupal - 2019-04-23
My filename filename configuration is as attached image.
Answer: I am not a specialist of dompdf, but having used fpdf, I think it's something you do in your print template or custom module that converts the fields in dompdf format.
You may need to set a php rule like this:
$title = mb_convert_encoding($title, 'HTML-ENTITIES', 'UTF-8');

Source: https://stackoverflow.com/questions/16384517/dompdf-character-encoding-utf-8
Or another one like this:
$titlePrintFriendly = preg_replace('#&#',chr(38),$title);

and then print $titlePrintFriendly
I used the second one in the past to trick printing some special chars.
The dompdf library should be loaded in the file you add this line.
I took the char number from https://github.com/dompdf/dompdf/blob/master/lib/fonts/Symbol.afm
Answer: A hook is available for this that is: Implements hook_print_pdf_filename_alter
/**
* Implements hook_print_pdf_filename_alter().
*/
function MY_MODULE_print_pdf_filename_alter(&$pdf_filename, &$path) {
  $pdf_filename = htmlspecialchars_decode($pdf_filename, ENT_NOQUOTES);
}


What method(s) should I use to construct the best-performing prediction model with only [k] predictors?

Question: I'm interested in doing prediction using the minimal number of predictors, as it will be relatively costly to collect each additional variable for prediction. I have a dataset with 100+ predictors and want to create the optimal model with no more than 5 predictors. How should I go about doing this?
I'm familiar with methods for reducing dimensionality and selecting features such as wrapper and filter methods. But I'm concerned that I could mislead myself by using any method that starts with the best-performing model with 100+ variables and works backwards. Who's to say the best 5 variables from the best-performing all-variable model are the best 5 variables period? Maybe a different model that performs worse with the full number of variables would actually perform better with just 5 variables? Is there a better way to go about doing this than starting with the best-performing model with all possible variables and then working backwards?
Answer: The LASSO is a standard way of doing variable selection. Generally, we would do cross-validation to determine the appropriate $\lambda$ and fit our model that way. Instead, you could rely on how the {glmnet} package in R fits a range of $\lambda$ values at once for you—and very speedily. You could then call coef() on your model to get a matrix of all coefficients by the different $\lambda$ values. I would look through the largest value of $\lambda$ that gives you exactly five variables—that is, it estimates the rest of the coefficients to zero.


Pegar primeiro item de cada objeto em uma resposta JSON

Question:
Estou obtendo um json através da seguinte URL: http://jsonplaceholder.typicode.com/photos (via GET)
Estou iterando sobre os objetos, mas queria pegar apenas o primeiro
item de cada objeto, que no caso seria  URL.
Como faço isso?
axios.get("http://jsonplaceholder.typicode.com/photos").then((response) => {
    var data = response.data;
    for(i in data){
        console.log(response.data[i])
    }
});

Comment: estava atualizando, amigo.
Answer:

      var data = [
      {
        "albumId": 1,
        "id": 1,
        "title": "accusamus beatae ad facilis cum similique qui sunt",
        "url": "https://via.placeholder.com/600/92c952",
        "thumbnailUrl": "https://via.placeholder.com/150/92c952"
      },
      {
        "albumId": 1,
        "id": 2,
        "title": "reprehenderit est deserunt velit ipsam",
        "url": "https://via.placeholder.com/600/771796",
        "thumbnailUrl": "https://via.placeholder.com/150/771796"
      },
      {
        "albumId": 1,
        "id": 3,
        "title": "officia porro iure quia iusto qui ipsa ut modi",
        "url": "https://via.placeholder.com/600/24f355",
        "thumbnailUrl": "https://via.placeholder.com/150/24f355"
      },
      {
        "albumId": 2,
        "id": 51,
        "title": "non sunt voluptatem placeat consequuntur rem incidunt",
        "url": "https://via.placeholder.com/600/8e973b",
        "thumbnailUrl": "https://via.placeholder.com/150/8e973b"
      },
      {
        "albumId": 2,
        "id": 52,
        "title": "eveniet pariatur quia nobis reiciendis laboriosam ea",
        "url": "https://via.placeholder.com/600/121fa4",
        "thumbnailUrl": "https://via.placeholder.com/150/121fa4"
      },
    ];

    var aux = ""

    for(i in data){
        if (data[i].albumId != aux){
            console.log(data[i].url)
            aux = data[i].albumId
        }

    }

Eu acredito que seria algo do tipo:
onde url pode ser qualquer atributo do JSON:

albumId
id
title
url
thumbnailUrl
Comment: Issooooo, exatamente.
Comment: No caso eu queria pegar a primeira url de cada albumId. Por ex: existem 5 fotos com o mesmo albumId. Quero pegar somente a primeira url dessas fotos.
Comment: por exemplo no Id 1 https://via.placeholder.com/600/92c952 e no 2 https://via.placeholder.com/600/8e973b ???
Comment: Pegar a primeira foto, de cada albumId
Comment: testa ai eu acho que colocando esse if já resolva seu problema
Comment: Qual if, amigo?
Comment: Esse : `if (data[i].albumId != aux)`
Comment: Aux se refere ao que?
Comment: Acho que seu navegador ta cacheando a pagina tenta recarregar com Ctrl + F5 e visualize minha resposta editada.
Comment: Não consegui :/
Comment: Não entendi muito bem esse lance do aux
Comment: Isso é uma função própria do javascript?
Comment: é uma variável auxiliar, por boas praticas escrevi aux para identificar ela melhor.
Answer: Você já passou o response pra variável data. Pode fazer assim, verificando se a variável é diferente do valor de albumId:

var data = [
  {
    "albumId": 1,
    "id": 1,
    "title": "accusamus beatae ad facilis cum similique qui sunt",
    "url": "https://via.placeholder.com/600/92c952",
    "thumbnailUrl": "https://via.placeholder.com/150/92c952"
  },
  {
    "albumId": 1,
    "id": 2,
    "title": "reprehenderit est deserunt velit ipsam",
    "url": "https://via.placeholder.com/600/771796",
    "thumbnailUrl": "https://via.placeholder.com/150/771796"
  },
  {
    "albumId": 1,
    "id": 3,
    "title": "officia porro iure quia iusto qui ipsa ut modi",
    "url": "https://via.placeholder.com/600/24f355",
    "thumbnailUrl": "https://via.placeholder.com/150/24f355"
  },
  {
    "albumId": 2,
    "id": 51,
    "title": "non sunt voluptatem placeat consequuntur rem incidunt",
    "url": "https://via.placeholder.com/600/8e973b",
    "thumbnailUrl": "https://via.placeholder.com/150/8e973b"
  },
  {
    "albumId": 2,
    "id": 52,
    "title": "eveniet pariatur quia nobis reiciendis laboriosam ea",
    "url": "https://via.placeholder.com/600/121fa4",
    "thumbnailUrl": "https://via.placeholder.com/150/121fa4"
  },
];

// variável de controle para não pegar o mesmo id
var albumId;

for(let i in data){
   // atribui o valor de albumId a variável id
   let id = data[i].albumId;
   // se for diferente, pega o valor da url
   if(albumId != id){
      // redefine o valor da variável com o valor atual
      albumId = id;
      console.log(data[i].url);
   }
}

De repente você pode criar uma array e ir adicionando as urls para depois fazer o que quiser com elas:

var data = [
  {
    "albumId": 1,
    "id": 1,
    "title": "accusamus beatae ad facilis cum similique qui sunt",
    "url": "https://via.placeholder.com/600/92c952",
    "thumbnailUrl": "https://via.placeholder.com/150/92c952"
  },
  {
    "albumId": 1,
    "id": 2,
    "title": "reprehenderit est deserunt velit ipsam",
    "url": "https://via.placeholder.com/600/771796",
    "thumbnailUrl": "https://via.placeholder.com/150/771796"
  },
  {
    "albumId": 1,
    "id": 3,
    "title": "officia porro iure quia iusto qui ipsa ut modi",
    "url": "https://via.placeholder.com/600/24f355",
    "thumbnailUrl": "https://via.placeholder.com/150/24f355"
  },
  {
    "albumId": 2,
    "id": 51,
    "title": "non sunt voluptatem placeat consequuntur rem incidunt",
    "url": "https://via.placeholder.com/600/8e973b",
    "thumbnailUrl": "https://via.placeholder.com/150/8e973b"
  },
  {
    "albumId": 2,
    "id": 52,
    "title": "eveniet pariatur quia nobis reiciendis laboriosam ea",
    "url": "https://via.placeholder.com/600/121fa4",
    "thumbnailUrl": "https://via.placeholder.com/150/121fa4"
  },
];

// cria a array
var urls = [];

// variável de controle para não pegar o mesmo id
var albumId;

for(let i in data){
   // atribui o valor de albumId a variável id
   let id = data[i].albumId;
   // se for diferente, pega o valor da url
   if(albumId != id){
      // redefine o valor da variável com o valor atual
      albumId = id;
      // adiciona as urls à array
      urls.push(data[i].url);
   }
}

// percorre a array
for(let url of urls){
   console.log(url);
}
Comment: Exatamente amigo. No entanto, preciso pegar a primeira url de cada albumId. Ex: Quando o albumId for igual a 1, eu pego a primeira url e pulo para o albumId 2.
Comment: Agora saquei...
Comment: Muito obrigado pela ajuda, perfeito a sua explicação!
Comment: o legal é que o cara fez a mesma logica que a minha
Comment: @Gunblades nem tinha visto a sua resposta.


Javascript : Dar .hide em tudo que estiver aberto

Question: Boa tarde. Gostaria de saber como fazer para ao invés de escrever:
  $("#removemirror3").click(function(){
  $("#mirror31").hide("slow");
  $("#mirror32").hide("slow");
  $("#mirror33").hide("slow");
  $("#add4mirror").hide("slow");

Escrever um hide geral que esconda tudo que estiver aberto.
Abraços.
Comment: Adicionar classes aos elementos é um dos usos mais comuns. Você pode também deixar um container por fora dos elementos e esconder apenas o cantainer. Há várias formas de fazer isso, depende da criatividade...
Comment: Você pode fazer tudo em uma linha: `$("#mirror31, #mirror32, #mirror33, #add4mirror").hide("slow");`
Comment: E não tem um jeito que não tenha que escrever todos?
Comment: renan e como eu faço para esconder toda a sequencia? dar um hide em foo[]?
Answer: Você pode usar um contexto para fazer a seleção dos elementos e dar um .hide()
Exemplo:

Utilizar um seleção por classe em comum.
Fazer a busca por atributo em específico.
Utilizar o elemento pai e utilizar o .find por elementos.

Crie um contexto para melhorar a sua seleção de elementos, ai a manipulação ficará mais simples.
Answer: @Guilherme, para tal você precisa de um elemento em comum entre todos os mirror. Por exemplo olhe o HTML abaixo:
HTML

CSS
.hidden { display: none; }

No caso acima, todos os mirror tem a propriedade data-mirror, então você pode usa-la para selecionar a todos eles.
Como você precisa apenas dos visiveis, você pode aplicar um filtro :visible
$("[data-mirror]:visible").hide("slow");

var btHidden = $("#btHidden");
btHidden.click(function () {
  var visibleMirror = $("[data-mirror]:visible");
  visibleMirror.hide("slow");
});
.hidden { display: none; }

.container {
  height: 120px;
}

.mirror {
  float: left;
  background-color: whitesmoke;
  width: 100px;
  height: 100px;
  box-shadow: 0px 0px 10px black;
  margin: 10px;
}

<button id="btHidden" >Esconder Tudo</button>
Answer: É possível selecionar elementos que contenham parte do id. Vale ressaltar que existem outras maneiras mais fáceis de fazer esta manipulação, conforme mencionado nas outras rspostas, mais veja um exemplo:

 $("button").click(function(){
     // seleciona todos os elementos que contenham mirror no id
     //$("[id*=mirror]").hide("slow");

     // seleciona todos os elementos que contenham mirror3 no id
     //$("[id*=mirror3]").hide("slow");

     // seleciona todos os elementos que contenham mirror3 no id, exceto botão
     $("[id*=mirror3]:not(button)").hide("slow");

 });

#mirror31

#mirror32

#mirror33

add4mirror

<button type="button" id="removemirror3">Remove</button>


What is the best choice to create a node through code?

Question: The scenario goes this way, I have a node type which has lot of Taxonomy term fields in it. It does also have other fields like text, date etc but 90% of it is a taxonomy field. I am aware that a node can be created programatically in two ways,

node_save() -  Creating a node object and saving it
<code>$node =  new stdClass();

$node->type = 'article';

$node->field_term[LANGUAGE_NONE][0]['tid'] = 3128 // term id of the term

node_save($node);
</code>
Form submit - creating a form array and submitting using drupal_form_submit
<code>$node[field_first]['und'] => chennai;

$node[field_second]['und'] => "iphone5";

$node['type'] = 'article';

$form_state['values'] = $node;

$form_state['values']['op'] = t('Save');

drupal_form_submit($node_type . '_node_form', $form_state, (object)$node);
</code>
with $node having the POST values.

Advantage of using form submit method is Drupal will take care of creating new terms in vocabulary (I am supposed to get more new terms). Form submit can follow form validations which is needed for creating a node.
Is there any method to create nodes faster in to Drupal system which supposed to get more terms in it?
If there is no other method than the above mentioned, what is the best one?
Comment: @DineshKumar 'Best' is too subjective a term, you might want to narrow that down to what you actually mean (e.g. most performant). Questions asking for the 'best' of something don't do so well on stack exchange sites. Besides that, the only real answer to this question comes from benchmarking the various methods in your current environment, which only you can do.
Comment: Your first approach is slightly faster but if your second approach is easier to maintain use the second one.
Comment: The Problem arises when i have more than 12 term fields and each fields having more than 10 values as terms, It is extremely slower and takes much of the resources
Comment: Then you might write 1 entity field query to find out which terms already exist, create all missing ones and in the end create the nodes like you showed in the first approach.
Comment: Yes, as said there are several methods to create a node, all i want is what is the best with a reason
Comment: @Clive you are right.
Answer: The safest method is to use drupal_form_submit(). If you take at look at the services module it does the same thing. Form validation should be important if you are creating nodes programmatically. Are you importing or creating multiple nodes at once? If this is the case and you are concerned about performance you can use Drupal's batch api or queue. Batch is great if you need user feedback but if you are creating nodes on cron and don't require a ui with feedback then queue is the way to go. In both cases they take care of memory management for you.
I wouldn't be to concerned about how long it takes to create one node as that is how long it would take with the ui. Unless the reason you are doing it through codes is to increase creation times.


AD - deploying printers to XP machines, pushprinterconnections.exe errror

Question: I'm a newbie in AD domain administration.
I'd like to deploy our printers to client workstations mostly running WXP.
Windows Server 2012, added Print Management feature, followed a tutorial on deploying printers using Group Policies. Printer is connected via a TCP/IP port.
Windows Server 2008/2012 do not contain pushprinterconnections.exe by default. Addded pushprinterconnections.exe from pmcmgmt.exe package from http://www.microsoft.com/en-us/download/details.aspx?id=7045#Overview and put it to a new group policy logon script.
When user log in, the error "_ftol2_sse entry point not found in dynamic library msvcrt.dll" is displayed. Printer is visible in Printers/Faxes but does not print (throwing the error above).
Fresh XP installation nor installing Visual C++ redistributable 2010 didn't help.
Thanks in advance for any help.
Comment: There are at least 3 methods to deploy printers via GP. How about telling us what method you're using. In addition, have you installed the GPP CSE for Windows XP on the Windows XP clients? - http://www.microsoft.com/en-us/download/details.aspx?id=3628
Comment: Thanks for the link! It helped me with another things (i.e. mapping shares without the script calling net use).
However pushprintconnections.exe error is still displayed.
I followed the tutorial http://www.youtube.com/watch?v=kff2kkPAQ94 - starting from 3:00 (related to Windows Server 2008) - in 2012 it was almost the same.
Comment: I'm thinking that you don't need to use pushprinterconnections.exe with GPP.
Comment: But without it the Printers and Faxes in XP are empty. (Tested now on a fresh AD user.)

The users who already ran pushprintconnections.exe have the printer installed but not working. (_ftol2_sse entry point... error when trying to print).

I'm going to google for other printer deploying methods. Thanks a lot.
Answer: There weren't additional 32bit printer drivers installed on the 64bit server.
This was obviously the cause of that strange error - pushprinterconnections.exe ran deployed to 32bit XP and tried to communicate with the printer...


Displaying images in GitHub documentation

Question: I have a GitHub repository, for which I have created a Wiki. In said Wiki, there are multiple pages, like this one that I tried putting images on. For some reason, those images aren't showing up.
My Markdown code to the page that I have pointed out looks like this :
<code># Getting started
* [Using protoype](#using-prototype)
* [Working on code](#working-on-code)
 * [Installation instructions](#installation-instructions)
 * [Front-end code](#front-end-code)
 * [Back-end code](#back-end-code)
 * [Database code](#database-code)

### Using prototype

1. Go [here](https://mikewarren.me/YALApp/test.html) for the prototype. It will take you to the login page, which should look like this: ![if you see this, it means you probably need to right-click this to open the image in a new tab](../blob/master/loginPage.png)
2. Click on blue bar labelled "Login" to select a sample profile.
3. Log in.

### Working on code

Comes in multiple parts: the installation instructions and the different layers of code. These are discussed below. When discussing the directories these are in, I shall use ~ to symbolize project root directory.

##### Installation instructions

This project is written in node.js and has a `package.json` file at ```~/home/ec2-user/GroupManagementAppServer```. You should be able to ```npm link``` the dependencies the project needs. The database connection is to a MySQL database, so I would recommend a MySQL database management system (I personally use phpMyAdmin) unless you plan on changing that to another (say, MongoDB to keep in the node.js spirit of things).

##### Front-end code

This can be accessed at ```~/var/www/html/YALApp```. JavaScript dependencies that are third-party libraries are one directory up from that.

##### Back-end code

This is written in JavaScript, and can be accessed at ```~/home/ec2-user/GroupManagementAppServer```. Main file is `appServer.js`, and if you are intending to use SSL/TLS, you will have to spell out the pathnames of `privateKey`, `certificate`, and/or `intermediate`. The application uses port number `8080`, and `8443` for https.

##### Database code

I don't have anything connected to the database yet, and thus had no real need to include the script here, but when I do, it will probably be in either ```~``` or ```~/home/ec2-user/GroupManagementAppServer/data```.
</code>
I don't know how else to link to the image, which can be found in the repository, besides <code>../blob/master/[pathToImage]</code>. How to resolve this?
Comment: Also, should I be putting all documentation information, including pages, in one directory in that repository? It kinda feels appropriate to put it in the main directory of the code being documented
Comment: Yes, isolating the doc in its doc folder is also a practice seen in GitHub pages for instance: see https://github.com/blog/2228-simpler-github-pages-publishing
Answer: Try and specify the full url of your repo instead of a relative path.
See "Linking to images in a repository"

You can link to an image in a repository on GitHub by copying the URL in your browser and using that as the path to the image.
  For example, embedding an image in your wiki using Markdown might look like this:

<code>[[https://github.com/username/repository/blob/master/img/octocat.png|alt=octocat]]
</code>
Comment: I agree, but this is what is currently and officially documented.


If $D$ is inside an acute triangle $ABC$ s.t. $\angle ADB=\angle ACB+\pi/2$ and $AC\cdot BD=AD\cdot BC$, then find $\frac{AB\cdot CD}{AC\cdot BD}$.

Question: Sources: IMO 1993, Problem 2, and also If $D$ is inside an acute triangle $ABC$ s.t. $\angle ADB=\angle ACB+\pi/2$ and $AC\cdot BD=AD\cdot BC$, then find $\frac{AB\cdot CD}{AC\cdot BD}.$.
Remark.  I think this question can remain closed, even if I have provided more context and made some modifications so the question is not quite the same as the old one.

Problem.  Let $ABC$ be a triangle such that $\angle ACB$ is acute.  Suppose that $D$ is an interior point of the triangle $ABC$ such that $$\measuredangle{ADB}=\measuredangle{ACB}+\frac{\pi}{2}$$
and $$AC \cdot BD=AD\cdot BC\,.$$
(a) Find $$\frac{AB \cdot CD}{AC \cdot BD}\,.$$
(b) Show that the tangents at $C$ to the circumcicle of the triangle $ACD$ and the circumcircle of the triangle $BCD$ are perpendicular.

We should use  $\measuredangle{ADB}=\measuredangle{ACB}+\frac{\pi}{2}$ somehow but I don't know how.  My first try was to use $\sin$ or $\cos$ law but they didn't work.  Any hints?
Solution Sketch of Part (b).
It is easy to show that the tangents at $D$ to the circumcircles of the triangles $ACD$ and $BCD$ are orthogonal to one another by angle chasing.  Then, by symmetry, the tangents at $C$ to the circumcircles of the triangles $ACD$ and $BCD$ are also orthogonal to one another.
Attempt of Part (a).
Although the assumption is that $ABC$ is an acute angle, if the answer is a constant number, then by continuity, the answer is the same if we suppose $\angle ACB=\dfrac{\pi}{2}$.  Therefore, $\angle ADB=\pi$, so $D$ lies on $AB$.  Let $x:=AC$, $y:=BC$, and $z:=AB$.  If $w:=BD$, then the condition $AC\cdot BD=AD\cdot BC$ means $$xw=y(z-w)\,.$$

Hence,
$$w=\frac{yz}{x+y}\,.$$
Consequently, $BD=\dfrac{yz}{x+y}$ and $$AD=AC-BD=z-\dfrac{yz}{x+y}=\dfrac{xz}{x+y}\,.$$
By Stewart's Theorem,
$$CA^2\cdot BD-CD^2\cdot AB+CB^2\cdot AD-BD\cdot AB\cdot AD=0\,.$$
Thus,
$$x^2\cdot\left(\frac{yz}{x+y}\right)-CD^2\cdot z+y^2\cdot \left(\frac{xz}{x+y}\right)-\left(\frac{yz}{x+y}\right)\cdot z\cdot\left(\frac{xz}{x+y}\right)=0\,.$$
This shows that
$$CD=\frac{\sqrt{xy\big((x+y)^2-z^2\big)}}{x+y}=\frac{\sqrt{xy\big(x^2+2xy+y^2-z^2\big)}}{x+y}\,.$$
By the Pythagorean Theorem, $x^2+y^2=z^2$, so
$$CD=\frac{\sqrt{xy\big(2xy+(x^2+y^2-z^2)\big)}}{x+y}=\frac{\sqrt{2}xy}{x+y}\,.$$
We then get
$$\frac{AB\cdot CD}{AC\cdot BD}=\frac{z\cdot\left(\frac{\sqrt{2}xy}{x+y}\right)}{x\cdot\left(\frac{yz}{x+y}\right)}=\sqrt{2}\,.$$
How to solve the problem without assuming $\angle ACB\neq \dfrac{\pi}{2}$?
Postscript.  The assumption that $ABC$ is acute in the original problem seems irrelevant.  As long as $\angle ACB$ is non-obtuse, the same conclusion holds.
Comment: Please consult the new [guidelines for adding context and rewriting](https://math.meta.stackexchange.com/questions/32402/).  In particular, please note that adding an "attempt" does not add sufficient context for a rewrite.  This question only duplicates that question, without significantly improving it.
Answer: Draw the perpendicular to $CB$ and then choose $E$ on it, s.t. $CB = CE$, as in the picture below. Now obviously $\angle ACE = \angle ADB$ and also from the condition:
$$\frac{AC}{CE} = \frac{AC}{BC} = \frac{AD}{DB}\,.$$

Therefore $\triangle ACE \sim \triangle ADB$. So in particular we have $\angle CAE = \angle DAB$. Also from the similarity of the triangles we have that $$\dfrac{AC}{AD} = \dfrac{AE}{AB}\,.$$ This gives us that $\triangle ACD \sim \triangle ABE$. So using that $BCE$ is a right isosceles triangle we have from $\triangle ACD \sim \triangle ABE$ that
$$CD \cdot AB = EB \cdot AD = \sqrt{2} BC \cdot AD = \sqrt{2} AC \cdot BD$$
Hence the ratio is $\sqrt{2}$.
Answer: Let's invert about $D$ eith arbitrary radius $r>0$. For any point $X$ in the plane let $X^{*}$ be the image of $X$ under the inversion. Then, we will rewrite all conditions in terms of $A^{*}$, $B^{*}$, $C^{*}$ and $D$.
Firstly, $\angle ACB=\angle ACD+\angle BCD=\angle DA^{*}C^{*}+\angle DB^{*}C^{*}$ and $\angle ADB=\angle A^{*}DB^{*}$, so we have
$$
\angle DA^{*}C^{*}+\angle DB^{*}C^{*}=\angle A^{*}DB^{*}.
$$
Hence, $\angle A^{*}C^{*}B^{*}=\frac{\pi}{2}$.
Secondly, recall that for any points $M$ and $N$ (other than $D$) we have
$$
M^{*}N^{*}=\frac{R^2}{DM\cdot DN}\cdot MN~\text{and}~DM^{*}=\frac{R^2}{DM},
$$
so the second equality can be rewritten as
$$
\frac{R^2}{DA^{*}\cdot DC^{*}}\cdot A^{*}C^{*}\cdot\frac{R^2}{DB^{*}}=\frac{R^2}{DB^{*}\cdot DC^{*}}\cdot B^{*}C^{*}\frac{R^2}{DA^{*}},
$$
or
$$
A^{*}C^{*}=B^{*}C^{*}.
$$
Thus, the triangle $A^{*}B^{*}C^{*}$ is isosceles and right-angled with $\angle A^{*}C^{*}B^{*}=\frac{\pi}{2}$.
Part (a):
Let's compute the fraction $\frac{AB\cdot CD}{AC\cdot BD}$ (in the similar way as above):
$$
\frac{AB\cdot CD}{AC\cdot BD}=\left(\frac{R^2}{DA^{*}\cdot DB^{*}}\cdot A^{*}B^{*}\cdot\frac{R^2}{DC^{*}}\right):\left(\frac{R^2}{DA^{*}\cdot DC^{*}}\cdot A^{*}C^{*}\cdot\frac{R^2}{DB^{*}}\right)=\frac{A^{*}B^{*}}{A^{*}C^{*}}=\sqrt{2}.
$$
Part (b):
Note that images of circumcircles of triangles $ACD$ and $BCD$ are lines $A^{*}C^{*}$ and $B^{*}C^{*}$, respectively. Images unfer the inversion of tangents to these circles at $C$ are circles $\omega_a$ and $\omega_b$ which are passing through $D$ and tangent lines $A^{*}C^{*}$ and $B^{*}C^{*}$ at point $C^{*}$. Since $A^{*}C^{*}\perp B^{*}C^{*}$ the circles $\omega_a$ and $\omega_b$ are orthogonal, so are preimages of $\omega_a$ and $\omega_b$.
Comment: This solution is very interesting.  Unexpected inversion!  I have no votes left to give today, so I shall return tomorrow.


Create an order as administrator user and let users continue with the checkout

Question: I am using Drupal 7 and the Drupal Commerce module. I need the ability to create an order as administrator user and let users continue with the checkout.
What I have tried:

Get the order ID and send the link to the user (for example,  http://example.com/checkout/1234/payment). It redirects to front page.
Use the Mail order link https://github.com/sjsam/Drupal-MOPL.
Use the module Commerce Checkout URL, which sends the link but doesn't work.

Do you have any idea?
Answer: Could you create a new "shopper" user for this customer, then assign the order to them? Make sure the role has proper permissions, workflow, etc. But then they will be the owner of the order and should be able to complete payment (and all the other checkout features like confirmation email).
Answer: The only way this can work by default is when you create an order for an existing user and ensure they login prior to attempting to access the form. However, I doubt you should be directing them to the payment page - that page has special logic attached to it that may not make it the ideal point of direction. Much better to send people to the checkout page that actually has the payment checkout pane on it.
If you want to link customers to the checkout form and ensure they're logged in, use a URL like:
https://www.example.com/user/login?destination=checkout/##
If the customer is already logged in, they will be redirected to the checkout form without any issues. If they aren't, they will be prompted to log in. The order ## must match an order that you have assigned to their user account in order for them to then view checkout for that order.
For a customer who does not yet exist in your system, you'll have to create an account for them first and ensure they can access it. There may be a contributed module out there that would let you include a token or something in the URL to grant anonymous access to the order, but I've never heard of it. It's theoretically possible through hooks Commerce offers, I've just never heard of anyone developing it.


Westworld theme piano fingering question

Question: I downloaded an app called MuseBook and I looked for sheet music for the Westworld theme. I found a couple and one seemed to be about my level so I've been studying it.
There is one section where I don't know what to do. The lines seem to overlap in weird ways. Here are three screenshots from my phone.

If you want you can also go to this link and have a look at the full PDF.
http://static.musescore.com/3105536/649dd8d12b/score.pdf
Measure 24 and 27 have the structure I'm unfamiliar with.
How do I play this? Why does it look like that?
Comment: It looks like that because whoever created it didn't know what they were doing. The staves are too close together, and the leger lines overlap. But if you sort that out, a computer can play things that humans can't reach! I suggest you keep looking till you find a better version.
Comment: @alephzero If you sort out the overlapping leger lines, it is very reachable, IMO. The seemingly three top notes on the first beat of the first screenshot are actually two Ds an octave apart which you can play with your right hand and the top note of the left hand on the first beat of the second screenshot is the same A as is in the right hand.
Answer: It looks like that because it's a awful transcription. In fact, it looks suspiciously like the result of a MIDI-to-score transformation.
I'd suggest either finding a better transcription, or editing it yourself to make it playable. The easy way to do that would be to drop the higher notes in the left hand entirely, and just keep the lowest octave (two notes).
Note that you might need to pay to get a decent version. Some of the transcriptions that float around on the internet can be of questionable accuracy. Of course, that might not matter. At the end of the day, if you're having fun and playing music, who really cares?
Comment: Thanks endorph. Yeah, I'm having fun playing it. I think you're right about the "MIDI-to-score transformation". I'll follow your suggestion with dropping the higher notes.