Mensagem de "Child vazio" em um Expandable ListView no Android

Question: Desejo criar uma indicação ao usuário informando que um Group de um Expansible ListView não contém nenhum Child (Que o group está vazio) conforme na imagem abaixo.

Pesquisando pela net, observei alguns métodos, mas achei muito confuso por está em outro idioma. Eu estou tentando isso no código abaixo, mas não estou conseguindo. Pois quando o grupo está vazio, meu expandable listview não infla o layout personalizado.
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

public class ExpandableListAdapter extends BaseExpandableListAdapter {

    private List<Construtor_Perfil_Usuario> modelList;
    private HashMap<Construtor_Perfil_Usuario,List<Construtor_Medicamentos>> listHashMap;
    private Context context;

    ExpandableListAdapter(Context context, List<Construtor_Perfil_Usuario> modelList, HashMap<Construtor_Perfil_Usuario, List<Construtor_Medicamentos>> listHashMap) {

        this.modelList = modelList;
        this.listHashMap = listHashMap;
        this.context = context;
    }

    @Override
    public int getGroupCount() {
        return modelList.size();
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    public int getChildrenCount(int i) {
        return Objects.requireNonNull(listHashMap.get(modelList.get(i))).size();
    }

    @Override
    public Object getGroup(int i) {
        return modelList.get(i);
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    public Object getChild(int i, int i1) {

        return Objects.requireNonNull(listHashMap.get(modelList.get(i))).get(i1);

    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    List<String> getValues(int groupPosition, int childPosition){

        List<String> listStrings = new ArrayList<>();
        listStrings.add(modelList.get(groupPosition).getNomeUsuario());
        listStrings.add(Objects.requireNonNull(listHashMap.get(modelList.get(groupPosition))).get(childPosition).getNome());
        listStrings.add(Objects.requireNonNull(listHashMap.get(modelList.get(groupPosition))).get(childPosition).getTipo());
        listStrings.add(Objects.requireNonNull(listHashMap.get(modelList.get(groupPosition))).get(childPosition).getStatus());
        listStrings.add(Objects.requireNonNull(listHashMap.get(modelList.get(groupPosition))).get(childPosition).getDosagem());
        listStrings.add(Objects.requireNonNull(listHashMap.get(modelList.get(groupPosition))).get(childPosition).getEstoque());
        listStrings.add(Objects.requireNonNull(listHashMap.get(modelList.get(groupPosition))).get(childPosition).getUso());
        listStrings.add(Objects.requireNonNull(listHashMap.get(modelList.get(groupPosition))).get(childPosition).getDataInicial());
        listStrings.add(Objects.requireNonNull(listHashMap.get(modelList.get(groupPosition))).get(childPosition).getDataFinal());
        listStrings.add(Objects.requireNonNull(listHashMap.get(modelList.get(groupPosition))).get(childPosition).getHoraInicial());
        listStrings.add(Objects.requireNonNull(listHashMap.get(modelList.get(groupPosition))).get(childPosition).getHoraIntervalo());

        return listStrings;
    }

    @Override
    public long getGroupId(int i) {
        return i;
    }

    @Override
    public long getChildId(int i, int i1) {
        return i1;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @SuppressLint("InflateParams")
    @Override
    public View getGroupView(int groupPosition, boolean b, View convertView, ViewGroup viewGroup) {

        String string = modelList.get(groupPosition).getNomeUsuario();

        if(convertView == null){
            LayoutInflater inflater = (LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = Objects.requireNonNull(inflater).inflate(R.layout.expansive_listview_group,null); }

        TextView textView = convertView.findViewById(R.id.lblListHeader);
        textView.setText(string);

        TextView textName = convertView.findViewById(R.id.textViewInfoSex);
        if (modelList.get(groupPosition).getSexoUsuario().contains("Feminino")){
            textName.setBackgroundResource(R.drawable.shape_oval_pink);
        }else{
            textName.setBackgroundResource(R.drawable.shape_oval_blue);
        }

        String subString = string.substring(0, 1);
        textName.setText(subString);

        return convertView;
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @SuppressLint("InflateParams")
    @Override
    public View getChildView(int groupPosition, int childPosition, boolean b, View convertView, ViewGroup viewGroup) {

        if (getChildrenCount(groupPosition) != 0) {

            String nomeMedicamento = Objects.requireNonNull(listHashMap.get(modelList.get(groupPosition))).get(childPosition).getNome();
            String statusMedicamento = Objects.requireNonNull(listHashMap.get(modelList.get(groupPosition))).get(childPosition).getStatus();
            String estoqueMedicamento = Objects.requireNonNull(listHashMap.get(modelList.get(groupPosition))).get(childPosition).getEstoque();
            String dosagemMedicamento = Objects.requireNonNull(listHashMap.get(modelList.get(groupPosition))).get(childPosition).getDosagem();

            if (convertView == null) {

                LayoutInflater inflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = Objects.requireNonNull(inflater).inflate(R.layout.expansive_listview_child, null);

            }

            TextView textView = convertView.findViewById(R.id.lblListItem);
            textView.setText(nomeMedicamento);

            ImageView imageView = convertView.findViewById(R.id.imageView_status_medicamento);

            if (statusMedicamento.equals("ATIVO")) {
                float result = Float.parseFloat(estoqueMedicamento) / Float.parseFloat(dosagemMedicamento);
                if (result <= 3 && result > 1) {
                    imageView.setBackgroundResource(R.drawable.ic_atencion_yellow);
                } else if (result <= 1 && result >= 0) {
                    imageView.setBackgroundResource(R.drawable.ic_atencion_red);
                } else {
                    imageView.setBackgroundResource(R.drawable.ic_alarm_on);
                }
            } else if (statusMedicamento.equals("DESATIVADO")) {
                imageView.setBackgroundResource(R.drawable.ic_alarm_off);
            }

        }else{

            if (convertView == null) {

                LayoutInflater inflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = Objects.requireNonNull(inflater).inflate(R.layout.expansive_listview_childempty, null);

            }

        }

        return convertView;
    }

    @Override
    public boolean isChildSelectable(int i, int i1) {
        return true;
    }

}

eu não entendo o que estou fazendo de errado.
Answer: Amigo no seu código esta quase pronto.
Veja, o método que cria os elementos chield é o getChildView, e nele você já verifica se o chield é diferente de zero (se não é vazio):
if (getChildrenCount(groupPosition) != 0) ...

Você até já tem o else para tratar quando não tiver chield, mas você parou por aí, só colocou o código para tratar quando a convertView for null (o que nesse caso não é, somente o chield que é vazio):
}else{
    if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = Objects.requireNonNull(inflater).inflate(R.layout.expansive_listview_childempty, null);
    }
}

Então o que pode ser feito é dentro deste else criar um chield com a mensagem "Chield Vazio" conforme você precisar, por exemplo, o código abaixo ficaria dentro doelse que esta no seu método getChieldView:
}else{
    if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = Objects.requireNonNull(inflater).inflate(R.layout.expansive_listview_childempty, null);
    }

    TextView textView = convertView.findViewById(R.id.lblListItem);
    textView.setText("Chield Vazio");
    ImageView imageView = convertView.findViewById(R.id.imageView_status_medicamento);
    imageView.setBackgroundResource(R.drawable.ic_alarm_off);
}

Editado
No teste que criei verifiquei que o app quebrava ao clicar em um group que não tinha child, e o problema não era no método getChildView mas sim no getChildrenCount. Este método retorna a quantidade de filhos que aquele grupo tem, se você passa um grupo que não tem filhos, ele não retorna 0, da erro, pois é a mesma coisa que pegar a posição maior que um vetor.
Segue abaixo o código de exemplo:
package com.example.myapplication;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;

public class ExpandableListViewAdapter extends BaseExpandableListAdapter {

    String groupNames[] = {"Aluno1","Aluno2","Aluno3"};

    String[][] chieldNames= {{"Chield do Aluno1"},{"Chiel do aluno2"}};

    Context context;

    public ExpandableListViewAdapter(Context context){
        this.context = context;
    }

    @Override
    public int getGroupCount() {
        return groupNames.length;
    }

    @Override
    public int getChildrenCount(int i) {
        if(i>chieldNames.length-1){
            //Se o group não tiver filho, retorne 1,
            // se retornar 0 o grupo vai aparecer mas não vai expandir
            return 1;
        }
        return chieldNames[i].length;
    }

    @Override
    public Object getGroup(int i) {
        return groupNames[i];
    }

    @Override
    public Object getChild(int i, int i1) {

        return chieldNames[1][i1];
    }

    @Override
    public long getGroupId(int i) {
        return i;
    }

    @Override
    public long getChildId(int i, int i1) {
        return i1;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }

    @Override
    public View getGroupView(int i, boolean b, View view, ViewGroup viewGroup) {
        TextView txtv = new TextView(context);
        txtv.setText(groupNames[i]);
        txtv.setPadding(100,0,0,0);
        txtv.setTextSize(50);
        return txtv;
    }

    @Override
    public View getChildView(int i, int i1, boolean b, View convertView, ViewGroup viewGroup) {

        TextView txtv = new TextView(context);

        //Repare que aqui, para pegar se o grupo não tem filho, não utilizei o método
        // getChildrenCount, pois editamos o mesmo para retornar 1 no lugar de 0
        if (!(i>chieldNames.length-1)) {
            txtv.setText(chieldNames[i][i1]);
            txtv.setPadding(100, 0, 0, 0);
            txtv.setTextSize(30);
        }else{

            //layout.chield_empty é só um linearlayout simples com um único textview dentro
            // escrito "chield vazio!!"
            LayoutInflater layoutInflater = (LayoutInflater) this.context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            convertView = layoutInflater.inflate(R.layout.chield_empty, null);

            //Infla e retorna o mesmo
            return convertView;
        }
        return txtv;
    }

    @Override
    public boolean isChildSelectable(int i, int i1) {
        return false;
    }
}

Comment: Desculpe amigo mas eu já tentei isso também... O grande problema que estou enfrentando é que quando não há filhos (childs) o meu "layout_personalizado_empty" não infla.
Comment: Dentro deste meu layout personalizado já existe um Textview personalizado com a mensagem = "Nada cadastrado para o usuário". Então para mim não é necessário fazer isto dinamicamente com setText()
Comment: O que é mais estranho para mim é que não infla de jeito nenhum. O layout com a mensagem de empty
Comment: @Andréalas entendi, mais a noite vou criar um teste para tentar reproduzir isso que está tentando fazer e te falo, pois eu nunca criei um layout só pra isso, eu geralmente retorno só um textview mesmo.
Comment: Perfeito meu amigo. Espero que você consiga me ajudar... vou ficar no seu aguardo....
Comment: Amigo se você puder dá um "UP" na questão por favor para mim ganhar um pouco de reputação vou agradecer muito pois gastei muito nesta pergunta. Considere também que esta questão pode não ser somente um problema para mim e outros também possam ter no futuro. Também perceba que não tem nenhuma questão parecida no StackOverFlow em português....
Comment: @Andréalas opa, beleza!!
Comment: @ Murilo Portugal Oi campeão conseguiu fazer fazer o projeto? Se você puder, me mandar o código funcionando..... Você pode fazer uma lista simples mesmo e me mandar. Daí eu comparo os código e vejo o que fiz de errado..... Se fizer isso pra mim eu te passo a recompensa.... vlw abraços
Comment: @Andréalas, consegui sim, vou editar a resposta e colocar o código!
Comment: Ótimo meu amigo vou ficar no aguardo...
Comment: @Andréalas, já postei o código e comentei pra ficar melhor para você entender
Comment: Ótimo meu amigo... vou verificar o código aqui. Mas por ter se interessado em me ajudar, vou te dar a recompensa..... Obrigado e bom trabalho. Vou introduzir a sua resposta em meu app e provavelmente amanhã te dou uma resposta.
Comment: Obrigado @Andréalas, e precisando é só chamar!


Relatório basico através de SQL

Question: Boa tarde, estou fazendo um sistema de questionários avaliativo, onde possui vários questionários com varias perguntas que fazem referencia a um questionário, que podem ser abertas ou fechadas.
Na tabela de respostas onde irei puxar os relatórios, funciona com os seguintes campos:
ID / ID_RESPONDENTE / RESPONDENTE / ID_PERGUNTA / PERGUNTA / QUESTIONARIO / TIPO / RESPOSTA
O que quero é o seguinte, pegar a quantidade de respostas com valor 'Muito bom', 'Bom', 'Ruim, 'Muito Ruim', Exemplo:
Pergunta / Resposta / Quantidade
Pergunta 1 - Muito bom - 3
Pergunta 1 - Bom - 4

Pergunta 2 -  Muito bom - 5
Pergunta 2 - Bom - 2
Comment: https://www.devmedia.com.br/10-dicas-para-classificar-agrupar-e-sumarizar-dados-em-sql/27555
Answer: Imagino que cada linha dessa tabela tenha uma resposta a uma pergunta para uma pessoa (tudo 1:1:1), e que esteja desnormalizada para (ID_PERGUNTA, PERGUNTA).
Caso seja este o caso, sua consulta SQL deve ser assim:
<code>SELECT Pergunta, Resposta, COUNT(*) AS Quantidade
FROM <tabela>
GROUP BY Pergunta, Resposta
ORDER BY 1, 2
</code>
Comment: obrigado, consegui entender

Relatório basico através de SQL


Using #states on an inline paragraph form

Question: I have a field on a custom content type which is a reference to a paragraph type, using the Paragraph (EXPERIMENTAL) widget. I'm trying to modify that widget to show and hide a field based on another field on the paragraph. Here is my widget alter code:
$field = 'field_supporter_form_fields';
$id_field = 'field_primary_custom';
$delta = $element['#delta'];
$id = sprintf('select[name="%s[%d][subform][%s]"]', $field, $delta, $id_field);
$element['subform']['field_field_type']['widget']['#states'] = [
  'visible' => [
    $id => ['value' => 'custom'],
  ],
];
$element['subform']['field_field_type']['widget']['#title'] = 'Blah!';

I know that I'm targeting the correct widget because I see the field title change to "Blah!", but the visibility of the field doesn't change.
Here's what the relevant part of the $element array looks like after the alter:
[#parents] => Array
    (
        [0] => field_supporter_form_fields
        [1] => 0
        [2] => subform
        [3] => field_field_type
    )

[#states] => Array
    (
        [visible] => Array
            (
                [select[name="field_supporter_form_fields[0][subform][field_primary_custom]"]] => Array
                    (
                        [value] => custom
                    )

            )

    )

The dependant field field_primary_custom is a pair of radio buttons with values of either primary or custom. The name of the element on the page is field_supporter_form_fields[0][subform][field_primary_custom] which matches what I have in my identifier.
Why isn't the visibility changing?
Answer: Turns out I needed to use input instead of select. Not entirely sure why, but it works!


SQL Server stored procedure

Question: I want it to count then if @intcount > 0 it should show data or else no data found, but when I execute it gives me 'no data found' regardless, what am I doing wrong?
@FiscalYear int,
@SchoolID int,
@Status int

AS
BEGIN

SET NOCOUNT ON;

declare @sqlstr varchar(2000)
declare @intCount int
set @intCount = 0

set @sqlstr = 'Select @intCount = Count(*)
              From PrivateSchool left outer join Attachment on  Attachment.PrivateSchoolID = PrivateSchool.PrivateSchoolID
              inner join FiscalYearPrivateSchool fp ON  fp.PrivateSchoolID = PrivateSchool.PrivateSchoolID
              Where (FiscalYear = '+convert(varchar, @FiscalYear)+') AND (PrivateSchool.IsActive = 1)'

 IF (@SchoolID != -1)
    SET @sqlstr = @sqlstr + ' AND SchoolID ='+ convert(varchar, @SchoolID)

 IF (@Status = -1)
    SET @sqlstr = @sqlstr + ' AND PrivateSchool.PrivateSchoolID = PrivateSchool.PrivateSchoolID'

 Else IF (@Status = 1)
    SET @sqlstr = @sqlstr + ' AND Attachment.PrivateSchoolID = PrivateSchool.PrivateSchoolID'
 Else
    SET @sqlstr = @sqlstr + ' AND Attachment.PrivateSchoolID is Null'

 If (@intCount > 0)
 BEGIN
 set @sqlstr=   'Select SchoolName as School,
 (Case when Attachment.PrivateSchoolID = PrivateSchool.PrivateSchoolID THEN ''Uploaded''
  ELSE ''Not Uploaded'' END) AS Status,
  COUNT(Attachment.PrivateSchoolID) AS [Count]
              From PrivateSchool left outer join Attachment on  Attachment.PrivateSchoolID = PrivateSchool.PrivateSchoolID
              inner join FiscalYearPrivateSchool fp ON  fp.PrivateSchoolID = PrivateSchool.PrivateSchoolID
              Where (FiscalYear = '+convert(varchar, @FiscalYear)+') AND (PrivateSchool.IsActive = 1)'

 IF (@SchoolID != -1)
    SET @sqlstr = @sqlstr + ' AND SchoolID ='+ convert(varchar, @SchoolID)

 IF (@Status = -1)
    SET @sqlstr = @sqlstr + ' AND PrivateSchool.PrivateSchoolID = PrivateSchool.PrivateSchoolID'

 Else IF (@Status = 1)
    SET @sqlstr = @sqlstr + ' AND Attachment.PrivateSchoolID = PrivateSchool.PrivateSchoolID'
 Else
    SET @sqlstr = @sqlstr + ' AND Attachment.PrivateSchoolID is Null'

    SET @sqlstr = @sqlstr + ' Group by SchoolName, Attachment.PrivateSchoolID, PrivateSchool.PrivateSchoolID'
    SET @sqlstr = @sqlstr + ' Order By SchoolName'
EXEC(@sqlstr)
 END
 ELSE
 Select 'No Data Found' as 'FileUpload'
 END

Comment: As an aside you really don't need to be building dynamic SQL here.
Comment: In addition to avoiding dynamic SQL when possible, I also have this big mindblock when it comes to executing the same query twice, once to see if there are rows, and then once to return rows. Why not just code the consumer to handle an empty result set gracefully, instead of changing the shape of the result and returning a row that says "no data"? This seems quite a lot more complex than it needs to be. In addition, it's also very inefficient to get a count if the actual value doesn't matter - you should look into EXISTS if you want to continue programming this way.
Comment: You do `set @intCount = 0` so `@intCount` will always be `0`.
Comment: It's a struct that *can* short-circuit. SQL Server knows it doesn't actually need to return data, and the seek/scan can be a lot cheaper if it doesn't have to inspect every single row, maintain a count, etc. http://msdn.microsoft.com/en-us/library/ms188336%28v=SQL.90%29.aspx
Answer: You need:
EXEC sp_executesql @sqlstr, N'@intCount INT OUTPUT', @intCount = @intCount OUTPUT;

IF (@intCount > 0)
BEGIN
    ....
END

You'll also need to make @sqlstr NVARCHAR(2000) and add set it to N'SELECT ...' as opposed to 'SELECT ...' - that leading N can be important.
Answer: The problem is:
declare @intCount int
set @intCount = 0
...

If (@intCount > 0)

It's always going to be 0.
Comment: so I should set @intCount equals to anything?
Comment: @paabobo - see Aaron's answer for a fix.  I was pointing out the logical fallacy in your script.
Answer: Your issue is one of scope. The EXEC(@sqlstr) command doesn't have access to the @intcount variable in your stored procedure. I would bet if you ran this code in a query window, it would tell you to declare @intcount.
Listen to YUCK and rewrite this to avoid dynamic SQL, and then your SELECT will be able to set the @intcount variable.
Comment: @paabobo: use Aaron's answer. I am right about the scoping problem (just tested it) but Aaron shows you a way to get around it.
Comment: @Aaron : Thank you for your help, im going to try it

SQL Server stored procedure


Using office 365, how can I replace diacritics with 'normal' letters with an efficient formula?

Question: I want to turn letters with diacritics into plain letters, so -
áàȧäǎāãåąⱥấầắằǡǻǟẫẵảȁȃẩẳạḁậặăâ =a
ḃƀɓḅḇ =b
ćċĉčçȼḉƈɔ =c
ḋďḑđɗḍḓḏðɖ =d
I'm using office 365, but need to achieve this without addins or VBA, using a formula. A lambda function is fine.
There's a solution here but

It's slow
It's hard to read
It needs a single string as the input - it won't work with (and produce) an array of words without the diacritics in
If a diacritic happens not to be listed, it won't be 'caught'

Re 2. & 4. the formula just lists some diacritics to be replaced - looking at Excel's character codes, there's no obvious pattern that can be used. So that might be the only way to do it.
I need a solution which doesn't use addins or VBA. Designed for Excel 2019, the solution below doesn't take advantage of LAMDA functions, which I can use.
=CONCAT(IFERROR(IF(EXACT(UPPER(MID(B1,ROW(A$1:INDEX(A:A,LEN(B1))),1)),MID(B1,ROW(A$1:INDEX(A:A,LEN(B1))),1)),UPPER(MID(CONCATENATE("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbcccccccccddddddddddeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeffggggggggghhhhhhhhhiiiiiiiiiiiiiiiiiiiijjjkkkkkkkklllllllllllll","mmmnnnnnnnnnnnnooooooooooooooooooooooooooooooooooooooooopppprrrrrrrrrrrrsssssssssttttttttttuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuvvwwwwwwxxyyyyyyyyyyyyzzzzzzz"),SEARCH(MID(B1,ROW(A$1:INDEX(A:A,LEN(B1))),1),CONCATENATE("áàȧäǎāãåąⱥấầắằǡǻǟẫẵảȁȃẩẳạḁậặăâḃƀɓḅḇćċĉčçȼḉƈɔḋďḑđɗḍḓḏðɖéèėêëěĕēẽęȩɇếềḗḕễḝẻȅȇểẹḙḛệéèêëḟƒǵġĝǧğḡģǥɠḣĥḧȟḩħḥḫⱨıíìïǐĭīĩįɨḯỉȉȋịḭíìïîȷĵǰḱǩķƙᶄḳḵⱪĺŀľɫⱡļƚłḷḽḻḹꝈ","ḿṁṃńǹṅňñņɲṇṋṉñŋóòȯôöǒŏōõǫőốồɵøṓṑṍȫỗṏǿȭǭỏȍȏơổọớờỡộởợóòôöõṕṗᵽƥʀŕṙřŗɍɽȑȓṛṟṝśṡŝšṥṧṣṩşṫťƭṭʈṱṯⱦţŧúùûüǔŭūũůųűʉǘǜṹṻủȕȗưụṳứừṷṵữửựúùûüṽṿẃẁẇŵẅẉẋẍýỳẏŷÿȳỹɏỷƴỵýźżẑžƶẓẕ")),1)),MID(CONCATENATE("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbcccccccccddddddddddeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeffggggggggghhhhhhhhhiiiiiiiiiiiiiiiiiiiijjjkkkkkkkklllllllllllll","mmmnnnnnnnnnnnnooooooooooooooooooooooooooooooooooooooooopppprrrrrrrrrrrrsssssssssttttttttttuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuvvwwwwwwxxyyyyyyyyyyyyzzzzzzz"),FIND(MID(B1,ROW(A$1:INDEX(A:A,LEN(B1))),1),CONCATENATE("áàȧäǎāãåąⱥấầắằǡǻǟẫẵảȁȃẩẳạḁậặăâḃƀɓḅḇćċĉčçȼḉƈɔḋďḑđɗḍḓḏðɖéèėêëěĕēẽęȩɇếềḗḕễḝẻȅȇểẹḙḛệéèêëḟƒǵġĝǧğḡģǥɠḣĥḧȟḩħḥḫⱨıíìïǐĭīĩįɨḯỉȉȋịḭíìïîȷĵǰḱǩķƙᶄḳḵⱪĺŀľɫⱡļƚłḷḽḻḹꝈ","ḿṁṃńǹṅňñņɲṇṋṉñŋóòȯôöǒŏōõǫőốồɵøṓṑṍȫỗṏǿȭǭỏȍȏơổọớờỡộởợóòôöõṕṗᵽƥʀŕṙřŗɍɽȑȓṛṟṝśṡŝšṥṧṣṩşṫťƭṭʈṱṯⱦţŧúùûüǔŭūũůųűʉǘǜṹṻủȕȗưụṳứừṷṵữửựúùûüṽṿẃẁẇŵẅẉẋẍýỳẏŷÿȳỹɏỷƴỵýźżẑžƶẓẕ")),1)),MID(B1,ROW(A$1:INDEX(A:A,LEN(B1))),1)))

Comment: I think you'll need to use a recursive lambda function - see https://www.ablebits.com/office-addins-blog/write-recursive-lambda-function-excel/#:~:text=Basically%2C%20a%20recursive%20function%20works,complex%20problems%20with%20no%20coding.
Answer: Here is a recursive LAMBDA function that works for your problem. You can define it in the Name Manager for example, or use Advanced Formula Environment Add-ins (formula 1):
CLEANCHARS = LAMBDA(txt,old,new, IF(old <>"",
 CLEANCHARS(SUBSTITUTE(txt,LEFT(old),new),RIGHT(old,LEN(old)-1),new),txt))

Now use it for your specific case, for example:
=CLEANCHARS(A1,"áàȧäǎāãåąⱥấầắằǡǻǟẫẵảȁȃẩẳạḁậặăâ","a")

or you can use REDUCE if you don't want to define a recursive function (formula 2):
=LET(x,A1, CLEANCHARS, LAMBDA(txt,old,new,
  REDUCE(txt,SEQUENCE(LEN(old)),LAMBDA(ac,i,SUBSTITUTE(ac, MID(old,i,1),new)))),
 CLEANCHARS(x, "áàȧäǎāãåąⱥấầắằǡǻǟẫẵảȁȃẩẳạḁậặăâ", "a"))

Note: Recursive functions are affected by current operand stack limit (check this link for more info). For CLEANCHARS would be 256 recursive replacements. If you consider you can reach it, then use formula 2:

...Furthermore, do note that the current operand stack limit in Excel is 1,024.  This should be borne in mind together with calculation times, as the current recursion limit is set as 1,024 divided by (number of lambda parameters + 1).

Here is the output (for recurse approach):

Now you can extend it for the general case, by doing all the clean up for an entire array. It spills out the entire array in just one call, no need to drag the formula down:
=LET(lk, A2:B3, BYROW(D2:D3, LAMBDA(x,REDUCE(x, SEQUENCE(ROWS(lk)),LAMBDA(ac,i,
  CLEANCHARS(ac, INDEX(lk,i,1), INDEX(lk,i,2)))))))

Note: In a similar way it can be addapted for using the non-recursive approach (formula 2).
Here is the output:


How to print list skipping one element each time in Python?

Question: samplelist = [100,101,102,103,104,105,106,107,108,109]

then I want output as below:
[100,[101,102,103,104,105,106,107,108,109]]
[101,[100,102,103,104,105,106,107,108,109]]
[102,[100,101,103,104,105,106,107,108,109]]

With help of others here I was able to generate
[101, 102, 103, 104, 105, 106, 107, 108, 109]
[100, 102, 103, 104, 105, 106, 107, 108, 109]
[100, 101, 103, 104, 105, 106, 107, 108, 109]
[100, 101, 102, 104, 105, 106, 107, 108, 109]

with following code:
[[el for el in samplelist if el is not i] for i in samplelist]

but I want that number skipped also in front as shown above.
Please suggest changes to that code.
Comment: Link to earlier question http://stackoverflow.com/questions/35194974/how-to-print-list-skipping-one-element-each-time-in-python-without-numpy
Comment: Why did you ask the same question 3 hours apart? If the first question wasn't getting good answers, you should edit the question to make it clearer, not post an identical question.
Answer: You can create a nested list with a list comprehension too:
>>> samplelist = [100, 101, 102, 103, 104, 105, 106, 107, 108, 109]
>>> newlist = [[item, [el for el in samplelist if el != item]] for item in samplelist]
>>> for item in newlist:
...     print(item)
...
[100, [101, 102, 103, 104, 105, 106, 107, 108, 109]]
[101, [100, 102, 103, 104, 105, 106, 107, 108, 109]]
[102, [100, 101, 103, 104, 105, 106, 107, 108, 109]]
[103, [100, 101, 102, 104, 105, 106, 107, 108, 109]]
[104, [100, 101, 102, 103, 105, 106, 107, 108, 109]]
[105, [100, 101, 102, 103, 104, 106, 107, 108, 109]]
[106, [100, 101, 102, 103, 104, 105, 107, 108, 109]]
[107, [100, 101, 102, 103, 104, 105, 106, 108, 109]]
[108, [100, 101, 102, 103, 104, 105, 106, 107, 109]]
[109, [100, 101, 102, 103, 104, 105, 106, 107, 108]]

BTW, you should use == for comparing values, not is. The latter is used for checking object's identity. In fact, your code only works because Python caches small integers, which is an implementation detail.
Answer: Using your code, just add the element 'i':
>>> import pprint
>>> x = [[i,[el for el in samplelist if el is not i]] for i in samplelist]
>>> pprint.pprint(x)
[[100, [101, 102, 103, 104, 105, 106, 107, 108, 109]],
[101, [100, 102, 103, 104, 105, 106, 107, 108, 109]],
[102, [100, 101, 103, 104, 105, 106, 107, 108, 109]],
[103, [100, 101, 102, 104, 105, 106, 107, 108, 109]],
[104, [100, 101, 102, 103, 105, 106, 107, 108, 109]],
[105, [100, 101, 102, 103, 104, 106, 107, 108, 109]],
[106, [100, 101, 102, 103, 104, 105, 107, 108, 109]],
[107, [100, 101, 102, 103, 104, 105, 106, 108, 109]],
[108, [100, 101, 102, 103, 104, 105, 106, 107, 109]],
[109, [100, 101, 102, 103, 104, 105, 106, 107, 108]]]

Answer: print [[i]+[el for el in samplelist if el is not i] for i in samplelist]

works?


Retirar valores duplicados em uma lista e imprimí-los

Question: Tenho um arquivo chamado arq1.txt e o outro arq2.txt.
Valores dentro do arq1:
2
5
1
10
21
7
8
8
3

Valores do arq2:
1,2,3

Nesse caso, meu trabalho é fazer a comparação entre os valores presentes nos 2 arquivos e criar um novo arquivo fazendo com que o texto escrito nele seja o valor de arq1 - arq2.
No caso, iria retirar os valores 1, 2 e 3 do arq1, ficando da seguinte forma (no caso o código criaria um 3° arquivo e armazenaria esse valor nele):
arq3.txt:
5
10
21
7
8
8

Até o momento consegui isso:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class App {

  public static void main(final String[] args) throws IOException {
    final List<String> linhasA = Files.readAllLines(Paths.get("C:\\q\\arq1.txt"));
    final List<String> linhasB = Files.readAllLines(Paths.get("C:\\q\\arq2.txt"));

    linhasB.forEach(linhaB -> {
       linhasA.forEach(linhaA -> {
           final String []valoresLinhaB = linhaB.split("\\,");
           final String []valoresLinhaA = linhaA.split("\\,");

           final List<String> duplicados = new ArrayList<>(Arrays.asList(valoresLinhaB));
           duplicados.retainAll(Arrays.asList(valoresLinhaA));

           if(duplicados.size() > 0){

             System.out.println(duplicados);
              }

         });
        });
    }
}

Dessa forma o valor retornado é:
[2]
[1]
[3]

Que no caso o código basicamente fez a comparação entre os 2 arquivos e verificou os dados duplicados.
Agora tô com uma fucking imensa dificuldade em fazer com que seja printado na tela o valor do arq1 retirando os valores duplicados.
Já tentei fazer uns comparativos mas não funcionaram(sou novo em java), algo como:
for(int i=0; i<10; i++){
if(valoresLinhaA[i] != duplicados){
   System.out.println(valoreslinhaA[i]);
 }
}

Porém o grande erro é que o valoresLinhaA[i] é uma string e não tem como fazer comparação dessa forma (ao menos a IDE me diz isso).
Alguma outra forma de comparar os valores e imprimir apenas o valor sem duplicação?
Sobre a criação do arquivo, acredito que consigo me virar após pegar o resultado sem os valores duplicados.
Answer: No seu caso, o mais simples parece ser usar o método removeAll. Primeiro você lê todos os valores de cada um dos arquivos, e depois faz a "subtração":
// método auxiliar para ler todos os valores do arquivo e retornar uma lista com esses valores
static List<String> getValuesFromFile(String filename) throws IOException {
    List<String> valores = new ArrayList<String>();

    for (String linha : Files.readAllLines(Paths.get(filename))) {
        for (String valor : linha.split(",")) {
            valores.add(valor);
        }
    }
    return valores;
}

// ler valores de cada arquivo
List<String> valoresArq1 = getValuesFromFile("arq1.txt");
List<String> valoresArq2 = getValuesFromFile("arq2.txt");

// remover de arq1 todos os valores que estão em arq2
valoresArq1.removeAll(valoresArq2);

// escrever o resultado no arquivo arq3.txt (cada elemento da lista ficará em uma linha)
Files.write(Paths.get("arq3.txt"), valoresArq1, Charset.defaultCharset());

Só isso. removeAll remove todos os elementos de valoresArq2 que estão em valoresArq1. Não importa se há repetidos ou se algum valor de arq2 não existe em arq1, o método já cuida de tudo isso.

Um ponto que não ficou claro é se os valores de arq1 estão um em cada linha, ou se é possível ter linhas como 10,20,30 (já que você faz split em ambos os arquivos).
Nesse caso, se arq1 tiver uma linha como 10,20,30 (e supondo que esses valores não estão em arq2), o resultado final terá os números 10, 20 e 30 separados, um em cada linha.

Sobre comparação de strings, em Java deve-se usar equals em vez dos operadores == e !=.


IOS NSData constructor VS NSMutableData for real time using purpose

Question: I have void* buffer...
I need to encapsulate it as fast as possible in a NSData structure (NSData or NSMutableData)
I'm guessing using only one NSMutableData (defined in the class) with
- (void)resetBytesInRange:(NSRange)range
- (void)appendBytes:(const void *)bytes length:(NSUInteger)length

or even
- (void)replaceBytesInRange:(NSRange)range withBytes:(const void *)bytes

will be much faster than using [NSData dataWithData:] every function call...
This is for audio process, so it needs to be the fastest it can be.
Does anyone can confirm that i'll be faster to use NSMutableData instead of NSData constructor ?
EDIT :
the buffer is always the same size, the NSMutableData won't need to re-allocate memory...
Answer: If you just want to replace the contents of an (already initialized) NSMutableData *data object with new data from buffer of the same length, then the fastest method is probably
void *mutableBytes = [data mutableBytes];
memcpy(mutableBytes, buffer, length);

because no range check and no (re-)allocation is done. See also the examples in Working With Mutable Binary Data.
But of course, as it is often said in this forum, you should profile your app with Instruments to find out where to optimize the program.
Comment: Are you sure, that if the length parameter is the same as the previous data size held in NSMutableData, a (re-)allocation will be done ? Isn't it more "clever" ?
Comment: @TheSquad: I do not understand the question. `[data mutableBytes]` has no length parameter. According to the documentation it "returns a pointer to the object's internal bytes". `memcpy` does not know anything about the `NSData` object. So it is in your responsibility that you do not copy more bytes than the `NSData` object was created for.
Comment: I meant on the method [NSMutableData appendBytes: length:]
Comment: Even with [NSMutableData replaceBytesInRange: withBytes:] since the length is a value of the NSRange, if the length is the same, does NSMutableData does (re-)allocate... This is just out of curiosity, I think I'll use your way, with memcpy... Thanks by the way.
Comment: @TheSquad: I assume that `replaceBytesInRange` will not (re-)allocate if not necessary. With my method you just save the range check. Probably not a big difference.


mysqli in class not working

Question: I am new to classes in PHP.
class metacountry
{
  public $mysqli;
  function metacountry()
  {

    global $config;
    $mysqli=new mysqli($config['DBHostName'],$config['DBUserName'],$config['DBPassword'],$config['DBName']);
   $mysqli->set_charset("utf8");
   if (mysqli_connect_errno()) {

      printf("Connect failed: %s\n", mysqli_connect_error());
      exit();

    }

  }

  function InsertCountry()
  {

    $stmt=$mysqli->prepare("insert into tbl_metacountry values(?,?,?,?,?)");
    $stmt->bind_param('sssss', $country, $meta_title, $meta_keywords, $meta_description, $active);
    $country=addslashes(addcslashes($mysqli->real_escape_string($_POST['country'], "%_")));
    $meta_title=addslashes(addcslashes($mysqli->real_escape_string($_POST['meta_title'], "%_")));
    $meta_keywords=addslashes(addcslashes($mysqli->real_escape_string($_POST['meta_keywords'], "%_")));
    $meta_description=addslashes(addcslashes($mysqli->real_escape_string($_POST['meta_description'], "%_")));
    $meta_active=addslashes(addcslashes($mysqli->real_escape_string($_POST['active'], "%_")));
    $stmt->execute();
    $stmt->close();

  }

 }

It throws an error:

Fatal error: Call to a member function prepare() on null in /var/www/html/country.php
Answer: You have to use $this to refer to class properties.
Your connection:
$mysqli=new mysqli($config['DBHostName'],$config['DBUserName'],$config['DBPassword'],$config['DBName']);

Should be,
$this->mysqli[...]

Additional Information
Instead of using global you should define the database settings within the class to make it more OO.
Reading Material
Class Properties
Comment: thanks, Actually I am new to classes Actually I want to create a mysqli object in the constructor method and use it in other methods in the class. and if you could edit my question and post here that will be very help ful
Comment: @SugumarVenkatesan then I think you should start from the beginning, don't jump in to database classes. Learn about classes in general and use trial & error to get used to the features involved in classes. Please accept the answer if it helped you.
Comment: I keep getting "Class 'CronClass\mysqli' not found" when using either method.
Comment: @user2924019 In the future you should ask a new question however, before `new mysqli` put a backslash so `new \mysqli(...);`, that will check the global namespace for the mysqli class instead of your class's namespace.
Comment: My hero! I was going to create a new question but the anxiety of getting downvoted and my account closed from asking questions people think already have answers is too much. The \ worked, I'm confused as to why all the examples I found including on this question don't seem to need the \. Thanks.
Comment: In your class you will have used `namespace blah` or something along those lines, therefore your class is no longer in the global namespace, all the classes defined without the `namespace` keyword are in the global namespace to by knowledge.
Comment: @user2924019 BTW, I typed in Google '*class mysqli not found'* and found [this](https://stackoverflow.com/questions/666811/fatal-error-class-mysqli-not-found) question and if you scroll down, someone mentioned the namespace issue. Google is your friend.
Comment: @Script47 I did see that question, but I didn't see the answer about the namespace issue.
Answer: I hope the following makes sense - it's not tested but looks more or less correct. The db connection is created in the public constructor function and is referenced using $this->conn for clarity - though you could of course rename that to whatever you wanted.
<?php
    class metacountry{
        private $conn;
        private $config;

        public function __construct($config=array()){
            /* initialise actual values at runtime */
            $this->config=(object)array_merge(array(
                'DBHostName'    =>  false,
                'DBUserName'    =>  false,
                'DBPassword'    =>  false,
                'DBName'        =>  false
            ),$config);

            $this->conn=new mysqli( $this->config->DBHostName, $this->config->DBUserName, $this->config->DBPassword, $this->config->DBName );
            $this->conn->set_charset("utf8");

            if( $this->conn->connect_errno ) {
                printf( "Connect failed: %s\n", $this->conn->connect_error );
                exit();
            }
        }

        function InsertCountry(){
            $stmt=$this->conn->prepare("insert into `tbl_metacountry` values (?,?,?,?,?)");
            $stmt->bind_param('sssss', $country, $meta_title, $meta_keywords, $meta_description, $active );

            $country=addslashes( addcslashes( $this->conn->real_escape_string( $_POST['country'], "%_" ) ) );
            $meta_title=addslashes( addcslashes( $this->conn->real_escape_string( $_POST['meta_title'], "%_" ) ) );
            $meta_keywords=addslashes( addcslashes( $this->conn->real_escape_string( $_POST['meta_keywords'], "%_" ) ) );
            $meta_description=addslashes( addcslashes( $this->conn->real_escape_string( $_POST['meta_description'], "%_" ) ) );
            $meta_active=addslashes( addcslashes( $this->conn->real_escape_string( $_POST['active'], "%_" ) ) );

            $stmt->execute();
            $stmt->close();
        }
    }

    /* example */
    $config=array(
        'DBHostName'=>'localhost',
        'DBUserName'=>'root',
        'DBPassword'=>'password',
        'DBName'    =>'mydb'
    );
    $meta=new metacountry( $config );
    if( $_SERVER['REQUEST_METHOD']=='POST' ) $meta->InsertCountry();
    $meta=null;
?>

Comment: I keep getting "MyClass\mysqli' not found".

mysqli in class not working


How do I output one node as XML

Question: I am creating a page flip for a drupal site using pdf_to_imagefield module to export PDf to JPG and then I need to have the list of JPG files as XML to use them in Dynaimc page flip.
The PDF and all JPOG files for each PDF page are stored in the same node of a certaine content type. How do I output this node as XML where I can control XML tags??
I have tried to create node-content-type.tpl.php but it comes as HTML.
Answer: I would recommend that you use views as your source for the list of jpegs to output your XML file from. Using Views for example, I was able to make list of event images and make a custom XML file used to display the images in the Cub3r Flash plugin (I thought it was a bad idea but the client really wanted a Flash slideshow). I used the Views Bonus Pack export module, that gave me a style 'XML file'. I had only the image field, that was set to output the full image URL, the label I set it to was used as the custom tag. I then did an override of the XML template that came with the module and customized it to my needs (adding config parameters to cub3r).
Hopefully this will help you out. I also saw that the export module now has a fork that uses the batch API. Make sure you also checkout the Views data source module.
Comment: yes that's really helping..thks
Answer: You can make a hook_menu entry for your XML URL w/ a callback function.
The callback function can do a
drupal_set_header("Content-Type: text/xml; charset=utf-8");

// stuff to make the xml;

print $xml;

exit;

You can also do it with views, but I forget the steps to do this.  There are a bunch of tutorials on the net, though, that outline this method, and likely some questions/answers on the main SO site.
Answer: I have solved it by creating a module, which generates an xml-file when you update your node. I used hook_update to hook into the update progress, check if the images have been updated and create / update the config.xml which I store in the directory of the images.  this way you dont need to generate the xml file each time a user views the node.
You have to create a template for generating the xml-files, passing your image-datasetting the configurations and than save the themed content into the config.xml.
hope I could help
Comment: This would mean that the XML file would bypass any permissions that may be in place on the node.
Comment: you wont parse the XML file if the node is not being viewed. but if there is need to protect the cfg-file you can still save the file in the private folder, create a path for xmlfile generation in your module where you can check the permissions and embed this generation path with the parameters you need (node, user etc)

How do I output one node as XML


Is there a way to pause and resume activity during a Espresso test?

Question: What i want to do is very simple, i just want to test my IllegalState (during fragment commit) logic behind my activities.
I want to pause the activity, try to commit a fragment and then asserts that i'm handling this right.
But it seems to be not possible to actually pause and then resume activity during Espresso tests. Is there a way to do this without launching another activity?
Answer: Quintin is correct in his answer to point you to the ActivityScenario.moveToState(newState:) method but he is missing some details which I hope to fill here.
First of all, note that the ActivityScenario.launch(activityClass:) method not only launches the activity but waits for its lifecycle state transitions to be complete. So, unless you're calling Activity.finish() in your activity's lifecycle event methods, you can assume that it is in a RESUMED state by the time the ActivityScenario.launch(activityClass:) method returns.
Secondly, once your activity is launched and in a RESUMED state, then moving it back to the STARTED state will actually cause your activity's onPause() method to be called. Likewise, moving the activity back to the CREATED state, will cause both its onPause() and onStop() methods to be called.
Thirdly, once you've moved the activity back to the CREATED or STARTED state, you have to move it forward to the RESUMED state before you can perform view assertions and view actions on it, or otherwise your test method will throw a NoActivityResumedException.
All of the above is summarised in the following test method:
@Test
fun moving_activity_back_to_started_state_and_then_forward_to_resumed_state() {
    val activityScenario = ActivityScenario.launch(MyActivity::class.java)

    // the activity's onCreate, onStart and onResume methods have been called at this point

    activityScenario.moveToState(Lifecycle.State.STARTED)

    // the activity's onPause method has been called at this point

    activityScenario.moveToState(Lifecycle.State.RESUMED)

    // the activity's onResume method has been called at this point
}

To see this in action, refer to this sample application and this test class in particular.
Answer: You could try the ActivityScenario, but they do not include Pause as a State. You might get away with the recreate() method, but that is Pausing and Resuming.
    //possibly:
    // @get:Rule var activityScenarioRule = activityScenarioRule<MyActivity>()

    val scenario = ActivityScenario.launch(MyActivity::class.java)
    scenario.moveToState(Lifecycle.State.RESUMED)
    //...
    scenario.recreate()
    //...

I would suggest having some interface / abstract handler that you can unit test outside of Android context.


Prove that topologically equivalent metrics have the same open and closed sets.

Question: My textbook for Real Analysis gives a pretty vague and not-so-straightforward definition of the notion of topologically equivalent metrics via open balls.
Could someone tell me what topological equivalency really means in perhaps more simple terms so I can grasp the meaning?
Comment: Are you somewhat familiar with how a metric induces a topology? Two metrics being topologically equivalent means they induce the same topology.
Comment: One simple way to say it is that two metrics $d$ and $d'$ on a space $X$ are topologically equivalent provided that the identity map $Id \colon (X,d) \to (X,d')$ is a homeomorphism.  In other words, every open set for $d$ is an open set for $d'$ and vice-versa.
Comment: You should perhaps provide your text's definition of "topologically equivalent metrics".
Comment: Unfortunately, we didn't learn how a metric induces a topology.
Comment: It's easy, just take balls of positive radius as neighborhoods of the center.
Comment: I guess his definition is something like balls in one metric contain a ball of the other and vice versa.
Comment: @user2345215, that was really the definition provided in the textbook. They used open balls involving s = s(r,x) > 0, where r > 0.
Comment: I can't figure out a way to prove this problem fully. For open sets, the proof seems simpler because the definition only uses open balls as subsets of other open balls.
Answer: A simple definition of topologically equivalent metrics is that the topologies they induce are equal. That just means a set is open in one metric if and only if it's open in the other metric.
The topology induced by a metric $\mu$ is simple, you call a set $G$ open if and only if $(\forall x\in G)(\exists B_\mu(x,r))\ B_\mu(x,r)\subseteq G$. That is, for every point in the set there's an open ball contained in the set.
Suppose you have a set $G$ open in $\mu$, then for every $x\in G$ there exists a ball $B_\mu(x,r_x)\subseteq G$. This implies that $G=\bigcup\limits_{x\in G}B_\mu(x,r_x)$. So it's a union of open balls around its every point.
If metrics $\mu_0$ and $\mu_1$ are topologically equivalent by your definition then for any set $G$ open in $\mu_0$ we have $G=\bigcup\limits_{x\in G}B_{\mu_0}(x,r_x)\supseteq\bigcup\limits_{x\in G}B_{\mu_1}(x,s_x)\supseteq G$, so $G=\bigcup\limits_{x\in G}B_{\mu_1}(x,s_x)$ and even in $\mu_1$ there's an open ball contained in $G$ around every point of $G$ which means $G$ is open in $u_1$.
The same argument shows every set open in $\mu_1$ is also open in $\mu_0$.


Dynamically adding items to WPF listbox

Question: I'm trying to build an application that the user points to a folder of PDF files.
of Invoices, the program then parses the PDF files to find out which ones contains an email address and which ones don't. and this Is Where I'm stuck:
I then want to add the file names to either the Listbox for print or the Listbox for email.
I got all the other bits working, choosing the folder and parsing the PDF and adding the folder path to a textbox object.
I then run a function:
private void listFiles(string selectedPath)
        {
            string[] fileEntries = Directory.GetFiles(selectedPath);
            foreach (string files in fileEntries)
            {

                try
                {
                    ITextExtractionStrategy its = new iTextSharp.text.pdf.parser.LocationTextExtractionStrategy();
                    using (PdfReader reader = new PdfReader(files))
                    {
                        string thePage = PdfTextExtractor.GetTextFromPage(reader, 1, its);
                        string[] theLines = thePage.Split('\n');
                        if (theLines[1].Contains("@"))
                        {
                           // System.Windows.MessageBox.Show("denne fil kan sendes som email til " + theLines[1], "Email!");

                        }
                        else
                        {
                            System.Windows.MessageBox.Show("denne fil skal Printes da " + theLines[1] + " ikke er en email", "PRINT!");
                        }
                    }
                }
                catch (Exception exc)
                {
                    System.Windows.MessageBox.Show("FEJL!", exc.Message);
                }

            }
        }

And it is in this function I want to be able to add the files to either Listbox.
My XAML looks like this:
<Grid.Resources>
        <local:ListofPrint x:Key="listofprint"/>
</Grid.Resources>

<ListBox x:Name="lbxPrint" ItemsSource="{StaticResource listofprint}" HorizontalAlignment="Left" Height="140" Margin="24.231,111.757,0,0" VerticalAlignment="Top" Width="230"/>

But I get the error: The name "ListofPrint" does not exist in the namespace "clr-namespace:test_app".
the ListofPrint is here:
public class ListofPrint : ObservableCollection<PDFtoPrint>
    {
        public ListofPrint(string xfile)
        {
            Add(new PDFtoPrint(xfile));
        }
    }

I've been trying to get the hang of the documentation on MSDN and have read 10 different similar Questions on this site, but I guess my problem is that I don't know exactly what my problem is. first of it's a data binding problem but I basically copied the sample from the documentation to play with but that is what is giving me the trouble.
Hopefully, someone here can explain to me the basics of data binding and how it corresponds to my ObservableCollection.
Answer: You need to create an instance of your collection class and bind the ListBox to it.
The most simple thing is setting its DataContext to this. I wrote an example:
Window:
public class MyWindow : Window
{
    // must be a property! This is your instance...
    public YourCollection MyObjects {get; } = new YourCollection();

    public MyWindow()
    {
        // set datacontext to the window's instance.
        this.DataContext = this;
        InitializeComponent();
    }

    public void Button_Click(object sender, EventArgs e)
    {
        // add an object to your collection (instead of directly to the listbox)
        MyObjects.AddTitle("Hi There");
    }
}

Your notifyObject collection:
public class YourCollection : ObservableCollection<MyObject>
{
    // some wrapper functions for example:
    public void Add(string title)
    {
       this.Add(new MyObject { Title = title });
    }
}

Item class:
// by implementing the INotifyPropertyChanged, changes to properties
// will update the listbox on-the-fly
public class MyObject : INotifyPropertyChanged
{
     private string _title;

     // a property.
     public string Title
     {
         get { return _title;}
         set
         {
             if(_title!= value)
             {
                 _title = value;
                 PropertyChanged?.Invoke(this, new PropertyChangedEventArgs( nameof(Title)));
             }
         }
     }
     public event PropertyChangedEventHandler PropertyChanged;
}

Xaml:
<ListBox ItemsSource="{Binding MyObjects}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Title}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Dynamically adding items to WPF listbox


How to calculate the R-square with the following figure?

Question:
The answer is 33033/80265= 0.4115?
Comment: Welcome to Cross Validated! The model and error sums of squares should add up to the total sum of squares, yet they are unequal. It could be worth asking your professor about this.
Comment: By definition, $R^2 = 1 - SSE/SST = SSR/SST = 33033/80265$.
Answer: There are many equivalent ways of thinking about $R^2$. The one that makes the most sense to me is comparing the performance of your model to the performance of some baseline model that always predicts the same value: the pooled mean of the response variable $y$.
If we measure model performance by considering the sum of squares, the the "model" sum of squares in the table is the performance of our model.
Then we need the performance of our baseline model. Using the terminology of your table, that comes from the "corrected total" sum of squares. This "total" sum of squares is related to the overall variance of $y$, and this is what leads to $R^2$ being described as the "proportion of variance explained".
Then we take the ratio to get the $\frac{33033}{80265}$ that you know is the solution.
(Note that it would be more common to use the equivalent definition $R^2=1-\frac{47231}{80265}$, except that the error and model sums of squares do not add up to the total sum of squares. I am convinced that this is a rounding issue.)


Where can I find org.apache.common libraries

Question: I need library for org.apache.commons.math3.stat.descriptive.DescriptiveStatistics
and that means I need org.apache.common libraries. Where can I find or download the libraries?
Comment: [Questions asking us to recommend or find a book, tool, **software library**, tutorial or other off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.](https://stackoverflow.com/help/on-topic)
Comment: @Turing85 Does that apply here? The OP is not giving us requirements and asking, "_here's my requirements now what libraries exist to do this?_". Rather, the OP _knows_ what library s/he needs and is asking where they can go to download them. Or does the "find" part of the rule cover this case? (p.s. I'm genuinely curious if this rule applies here).
Comment: @Slaw Well... it is as written: No questions finding a software library. OP is looking for a (specific) software library, thus s/he asks us to find it. The vote to close was in my opinion the "lesser evil". The alternative would have been a downvote for no research. This is just my interpretation of the rule.
Answer: You can download binaries from the Apache Commons Math project:
http://commons.apache.org/proper/commons-math/
http://commons.apache.org/proper/commons-math/download_math.cgi
Another way is to convert the project to Maven and add Maven dependency in pom.xml.
Maven link:
https://mvnrepository.com/artifact/org.apache.commons/commons-math3/3.0
<code><!-- https://mvnrepository.com/artifact/org.apache.commons/commons-math3 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-math3</artifactId>
    <version>3.0</version>
</dependency>
</code>
Maven will find it for you in the repositories and download automatically.
You can search for open-source libraries at https://mvnrepository.com. If you find the artifact there, you will have a link to the author website and license terms.
Answer: take a look at this site: findjar.com.


What's this type of content actually called?

Question: I think I've been getting the terminology wrong.
When I open a Panel and go to the Content region and click the gear icon, then Add Content a modal appears.
On the left of this modal are categories housing various site components - gallerys, forms, HTML, etc
What are these things collectively actually called?
Answer: I think those are called site content (but I don't know if you'll find a name for all of them written somewhere, as you said).


How could one estimate $Y = X\beta \times \epsilon$ with $\epsilon \sim \text{Beta}(a,b)$?

Question: Suppose the data generating process is $$Y_i=f(X_i)M_i.$$
where $M_i$~$Beta(a,b)$ and $f$ linear, for example,$f(X_i)=\alpha_0+\alpha_1X_i$. This is equivalent to
$$M_i=Y_i/f(X_i).$$
I'm trying to think of someway to estimate $a,b$ and the $\alpha'$s. Do you have any suggestion?
I don't know if I have to go through Bayesian estimation.
Thanks in advance!
Comment: I imagine you could find the maximum likelihood by a computational method, where you can use as a starting point an initial least-squares fit and the moments of the residuals to come up with initial estimates.
Comment: @MartijnWeterings It is Beta distributed. I will remove this comment. You suggested me to estimate $f(X_i)$  with some method and then use it to estimate $a,b$? I just read the title you put. It is exactly what I wanted to ask.
Comment: I suggest using maximum likelihood to compute all four $a$, $b$, $\alpha_0$ and $\alpha_i$, but use a linear model to obtain initial estimates of $a$, $b$, $\alpha_0$ and $\alpha_i$ (where $a$ and $b$ are to be estimated based on the higher moments of $Y_i/\hat{f}(X_i)$). This linear model can be a regular least squares fit or if you like (not sure it is needed) something where you take heteroscedasticity into account (but I do not know your typical range of $X$, $\alpha_0$, $\alpha_i$ in order to say how you could do this, a GLM with a quasi link function to scale variance might work).
Comment: You seem to be confident on the maximum likelihood. Could you please give me a more detailed answer? I still don't get how exactly I could calculate the likelihood function. Can you describe what you are suggesting as an answer below?
Comment: I have added a code which works quite well. Note by the way that it is not exactly the same as beta-regression. However it is related to it. Beta-regression is, I believe, solved by using the maximum likelihood (at least that is how the R package `betareg` does it). It does not allow a simplification like solving it with an iterative reweighted least squares as in GLM (see https://stats.stackexchange.com/questions/304538/why-beta-dirichlet-regression-are-not-considered-generalized-linear-models).
Answer:
You might try to use find parameters by maximizing the likelihood function computationally (after finding some initial estimate for the parameters).

linear model estimate

compute parameters based on linear estimates and residuals
In the code below I do this different and I assume $a=b$ and make use of $Y/f \sim Beta$. This has a problem that these values may not need to be limited in the range $(0,1)$. You could advance this step by making computations of the moments of the residuals and relate those to $a$ and $b$ (You should do this in order to make the convergence in the next step work better. I didn't do it because it involves annoying equations.)

perform computational optimization.

The code below shows a rough start for how this could work.
There are several issues:

Values $Y_i/f(X_i)$ may reach outside the range $(0,1)$.
The algorithm may not always converge well (With adaptations you can make it work well. The code before the edit used scaling of parameters. But more stable is the code after the edit, which uses segregated steps and solves the the problem as two nested optimizing functions).
The error in the parameters is correlated. You can simultaneously increase the linear part $f(X)$ and decrease the mean of $M_i$, and this will give a roughly similar result. So while you can approximate the distribution well, the parameters may not be very meaningful and have a large error. (although when you test the model a few times the result does seem to turn out very close each time)

Quantile regression might be another angle to tackle this problem.
Furthermore, you can use various rough estimates instead of this computation. For instance a simple GLM model, not with a beta distribution but with some other distribution, might be sufficient for you to estimate the linear function $f$. How far these kind of approximations/simplifications can be made and whether they are sufficient for you, depends on the details of your problem.
example results:
True model
a = 2     b = 1      alpha_0 = 10     alpha_1 = 1

Fit
a = 1.82  b = 0.93   alpha_0 = 10.02  alpha_1 = 1.00

example code:
library(betareg)
set.seed(1)

# create modelled data
n <- 10^3
x <- runif(n,0,100)
m <- rbeta(n,2,1)
X <- cbind(rep(1,n),x,x^2)
f <- X %*% c(10,1,-0.005)
y <- f*m
colnames(X) <- c("1","x","x^2")

# likelihood to optimize
loglik <- function(par,dat=dat) {
  # linear model pars
  #bt0 <- par[1]
  #bt1 <- par[2]

  # ratio Y/f(X) which should relate to beta distributed var
  f <- dat[,-1] %*% par
  yf <- dat[,1] / f

  #to prevent values outside (0,1) or values condensing in one point
  neg_penalty <- which(abs(yf-0.5) < 0.4999)

  # fit beta distribution to Y/f(x)
  # note under the hood betareg is a call to optim
  modfit <- betareg(yf[neg_penalty] ~ 1, link ="log")
  a <-    exp(modfit$coefficients$mean)  * modfit$coefficients$precision
  b <- (1-exp(modfit$coefficients$mean)) * modfit$coefficients$precision

  # return loglikelihood or penalty
  penalty_size <- length(dat[-neg_penalty,1])
  if (penalty_size == 0) {
    result <- -modfit$loglik + sum(log(f))
        # the sum(log(f)) term is because we actually do not wish the
        # probability for yf but instead the probability for y which relates
        # to a scaled beta distribution and this scaling factor occurs in the density as log(f)
  } else {
    result <- penalty_size*10^6
  }
  result
}

# data
dat <- cbind(y,X)

# start condition
mod <- lm(y ~ 0+X)
par <- c(2*mod$coefficients)  # we assume that the starting line is twice the mean

# optimize
p <- optim(par, loglik, dat=dat, control = list(trace=2, maxit=10^3))
p

# outcome
p$par
loglik(par,dat)
loglik(p$par,dat)

yf <- dat[,1] / (X %*% p$par)
modfit <- betareg(yf ~ 1, link ="log")
parfin <- c(exp(modfit$coefficients$mean)*modfit$coefficients$precision,
         (1-exp(modfit$coefficients$mean))*modfit$coefficients$precision,
         p$par)

# view result
plot(x, y,
     pch=21, col=rgb(0,0,0,0.1),bg=rgb(0,0,0,0.1))

sig <- 0.02
brks <- seq(0,1,sig)
hist(yf, breaks = brks,sig,xlim=c(min(hf),max(hf)),xlab = "Y/f(X)",main="")
lines(brks,dbeta(brks, parfin[1],parfin[2])*n*sig,col=2)

parfin

Comment: My reasoning is that when you scale a variable then $$f_{aX}(X) = \frac{1}{a} f_{X}(X/a)$$ So one can compute the likelihood for $f_X$ and then multiply/divide with this factor (or add/subtract when working with logarithms)
Comment: Thanks! I have to say that your estimates are quite good in your example. I need some time to understand precisely what you did. Specially, I need to learn how this function "optim" works. Again, thank you very much.
Comment: `optim` is an algorithm that finds the coefficients that optimize (maximizes or minimizes) the function. It can use different iterative methods (iterative : making step-wise improvements of the solution).
Comment: I see that you calculate $a$ and $b$  by taking the exponential of the mean estimate and multiply by the precision estimate. Why is that? As far as I understand, you are modelling $g(\mu)=log(\beta_0)$  and $h(\phi)=\gamma_0$ where $yf$~$Beta(\mu,\phi)$, and then construct a log-likelihood based on this. What are exactly the values that betareg estimates?
Comment: I take the exponential because the betareg uses a log link function $\mu = exp (\eta) $. The precision parameter corresponds to $\phi =a+b $. Then $\mu = a/(a+b) $ turns into $$exp(\eta) = a/\phi$$
Comment: It's not $g (\mu) = log (\beta_0) $ but instead $g (\mu) = log (\mu) = \beta_0$. The link function is the function that linearizes the mean, when you apply the link function to the mean than it becomes a linear relation like $g (\mu)=\eta = X\beta $ (and you can describe it in the *other direction*, when you apply the *inverse* of the link function to a linear expression $\eta = X\beta $ then it becomes the mean $\mu = g^{-1}(\eta) $). Think about taking the log(Y) to linearize an exponential relationship y=a exp(bx).
Comment: Oh, so given that $y$~$Beta(a,b)$, you transformed the parameters so that $\mu=a/(a+b), \phi=a+b$ . These imply $a=\mu\phi$ and $b=(1-\mu)\phi$. You linearize $\mu$ choosing the log link ($log(\mu)=\eta$) and $\phi$ choosing the identity link ($\phi=\phi$).
Comment: In the function loglik you  took the negative of the value of the log-likelihood function and added the sum(log(f)), so vanish with the scaling factor of $yf$. Can you confirm if the log-likelihood function is $\sum_i l_i (\mu_i,\phi)=\sum_i log\Gamma(\phi)-log\Gamma(\mu_i\phi)-log\Gamma((1-\mu_i)\phi)+(\mu_i\phi-1)log y_i+[(1-\mu_i)\phi-1]log(1-y_i)$. Because then by adding $\sum_i log(f)$ doesn't provide exactly the log-likelihood associated with $y$. Am I wrong?
Comment: I just tried a code for the case when $f(x)=b_1 x^2+b_2 x$, and obtained good estimates for $b_1$ and $b_2$ but poor estimates for the beta parameters $a,b$. Do you see any issues for this case, specially when $f$ is concave?
Comment: I will look into the quadratic curve. The other aspect that you mention the log(f) term in the likelihood is because the optimization model may start to model very large f(x) such that y/f(x) is very close to zero and then with a beta distribution centered near zero you would get very high density values and an unrealistic high likelihood. The multiplication of the probability by $f(x)$ corresponds to modelling $y \sim Beta_{f(x)}(a,b)$ where the subscript $f(x)$ refers to the idea that the beta distribution is scales (stretched).
Comment: I have no issues with a quadratic function. If the $\alpha_i$ are well estimated, then there should be little problem with the estimates for the beta distribution parameters, $a$ and $b$, because you are using a $y/f(x)$ that should be a correct representation of $m_i$
Comment: Can you show your code in your example box of your answer? I would like to see what I did wrong.
Comment: I have now updated the code such that it allows more linear models. See the revisions for an easy comparison https://stats.stackexchange.com/posts/428770/revisions
Comment: Ideally this 1/f factor for the density should actually be a weight for the betareg function.
Comment: Thank you for the complete answer. I undestand the result on scaled density function.  The log-likelihood function that R calculates is $\sum_i l(\mu_i,\phi;y/f(x))=\sum_i log(f_{Y/f(X)}(y/f(x))\neq \sum_i log(f_{Y/f(X)}(y/f(x)^2))$ isn't it? Following your argument above, I think you are assuming $f_{aX}(x)=1/a f_X(x)$ instead of $f_{aX}(x)=1/a f_X(x/a)$.
Comment: I should have written $f_{aX}(ax) = 1/a f_X (x) $
Comment: now, all makes sense :)


Some Topological Properties of Starlike Sets!

Question: A subset $E$ of $\mathbb R^n$ is starlike if it contains a point $p_0$ (called a center for $E$) such that for each $q\in E$, the segment between $p_0$ and $q$ lies in $E$. For more information please visit here .
My question is:

Suppose that $E\subset\mathbb R^n$ is open, bounded, and starlike, and $p_0$ is a center for $E$.
  (a):Is it true or false that all points $p_1$ in a small enough neighborhood of $p_0$ are also centers for $E$ ?
  (b):Can it consist of a single point?

Refrence: Real Mathematical Analysis-Charles Chapman Pugh .
Answer: (a) false; (b) true. I give an example in two dimensions; you can generalize it for $n>2$.
$$E = \{(x,y)  : |x|<2, |y|<2\}\setminus \left[\{(x,0): |x|\ge 1\}\cup \{(0,y): |y|\ge 1\} \right] $$
The only center of $E$ is $(0,0)$.


All vs One non-parametric test?

Question: I am currently analyzing several repeated measures with several treatments. That is: 33 individuals and 4 different conditions. The box plots that are shown from left to right indicate the treatments in the following order: control, first treatment, second treatment, and third treatment.

Before adding more treatments to the analysis, I was obtaining statistical significant differences using a non-parametric Wilcoxon test between the control and the second treatment. Now, I am using a Friedman test for verifying differences in all treatments. The current obtained p value is 0.48, and I can't reject H0.

Is there a non-parametric test for comparing several treatments versus a control (control vs treatment1, control vs treament2, and control vs treament3) disregarding other comparisons? I think the reason Friedman can't visualize my previous difference between control and the second treatment is because of low statistical power.
Regards,
Ignacio
Answer: The box plots seem to tell an interesting story: Assuming they are in order, there are some complex things going on. I don't think any single test is going to tell the whole story. Wilcoxon was significant between the first two, but that seems solely due to higher highs - the medians are almost identical.
Therefore, I suggest quantile regression on a range of quantiles, with "group" as a categorical predictor.
Comment: I am sorry. The treatment I was talking in the description is the third one (third box plot), and not the second one. There are median differences between control and 3. However, between control and 2 wilcoxon does not reject H0.
Comment: Oh. You should perhaps edit your question saying which box is which.
Comment: Done! The theory I have found until now tells me that I can obtain p-values using Quantile regression. I will give it a try. Thanks for the answer!

All vs One non-parametric test?


How do I prove: if f(a) = f(b) = 0, then there is a greatest lower bound c and least upper bound d such that f(c) = f(d) = 0

Question: I'm having trouble proving this one question from Calculus, 4th Edition, by Spivak. The full problem is:
Suppose that f is continuous on [a, b] and that f(a) = f(b) = 0. Suppose also that f(x₀) > 0 for some x₀ in [a, b]. Prove that there are numbers c and d with a ≤ c < x₀ < d ≤ b such that f(c) = f(d) = 0, but f(x) > 0 for all x in (c, d).
My proof outline is this: There is a set A such that A = {x: f(x) = 0}. I need to prove, for set A, that c is the greatest lower bound, and d is the least upper bound. To do this, I want to show that f(c) = f(d) = 0. However, I'm not sure if I'm headed in the right direction; I don't think it's rigorous enough, and I don't know if my approach even makes sense.
Any advice on how to at least get started is appreciated.
Comment: If $f(x_0)>0$, there is a neighborhood I=[$x_0-\epsilon,x_0+\epsilon$] , such  that $f(x_0)>0$ for all $x\in I$
Comment: Why not take $c:=\sup\{x\in[a,x_0):f(x)=0\}$?
Comment: Thanks for the advice everyone. John Dawkins, I used your idea, and I changed it a little so that my proof is more like this:

A = { x∈[a, x₀]: f(x)  = 0}. The least upper bound property states that, "if A is a set of real numbers, A is not empty, and A is bounded above, then A has a least upper bound." In this case, A is bounded above by x₀, therefore A has a least upper bound, namely c. I will use similar reasoning to show that d is also the least upper bound of [x₀, b].
Answer: Since $f$ is continuous, $f(a) = f(b) = 0$, and $f(x_0) > 0$, it must be that there exists some interval $(x_0 - \alpha, x_0 + \alpha)$ such that for all $\beta \in (x_0 - \alpha, x_0 + \alpha), f(\beta) > 0$.
(You can prove that this is true if you feel the need: consider the intervals $(x_0 - \alpha, x_0)$ and $(x_0, x_0+\alpha)$: for every point in each interval, apply the intermediate value theorem.)
Anyway, then you can let $c$ be the point right before the interval $(x_0-\alpha, x_0+\alpha)$, and $d$ the point directly after. Constructing something like $c = \inf \{\alpha | f(x_0 - \alpha) \neq 0\}$ should work, and $d = \sup \{\alpha | f(x_0 + \alpha) \neq 0\}$.


Factoring Trigonometric Equations

Question: And so begins another day in my quest to pass Calculus I.
I have a question about factoring trigonometric expressions. I'm sorry I can't be more accurate than that, but I'm not sure of the names of the operations I need to perform.
I have a problem:
$$ -2(cos(x) – cos(2x)) = 0 $$
I divide both sides by -2:
$$cos(x) – cos(2x) = 0$$
And then transform the left hand side into a polynomial using the double angle formula:
$$1 + cos(x) – 2cos^2(x) = 0$$
However this is where I get stuck. According to Wolfram Alpha I am now supposed to factor the expression to get $-((cos(x) – 1)(1 + 2cos(x))) = 0$
Maybe I am missing something but I don't understand how to factor for that step. Could somebody explain it or link me to the names of the concepts I need to Google? Thanks.
Comment: Let $t=\cos(x)$. Could you factor $1+t-2t^2$?
Comment: Please be patient with me. I just refreshed myself on factoring by grouping. But it looks like for this situation I need two variables that multiplied together equal $-2cos^2x$ and added together equal $cosx$. Should I be approaching this from a different angle, like the quadratic formula?
Answer: You've gotten to $1+\cos(x)-2\cos^2(x)=0$ or, equivalently
$$
2(\cos(x))^2-\cos(x)-1=0
$$
Now, to make things easier to see, let $t=\cos(x)$. If you do, your equation now looks like
$$
2t^2-t-1=0
$$
which factors as
$$
(2t+1)(t-1) = 0
$$
This can only hold if either $2t=-1$ or $t=1$.
Now "unsubstitute" to get two possibilities:
$$
\begin{align}
2\cos(x) &= -1&\text{or}\\
\cos(x)&=1
\end{align}
$$
so, finally you need to find all $x$ for which $\cos(x)=1/2$ or $\cos(x)=1$. I'll leave that to you.
Comment: Thank you. I didn't realize I came to the same conclusion by substituting cosx with t but I didn't realize I could just substitute cosx back and get the right answer.

Factoring Trigonometric Equations


Achar ip dentro da rede

Question: Olá, estou tentando uma solução para achar um computador especifico dentro de uma rede por uma aplicação android, para conectar a um webservice em c#... mas o problema está em achar este computador, com o ip trocando de vez em quando. O que eu poderia fazer em relação a isso?
Comment: Se o IP muda, por que não usar o hostname?
Comment: mas no ksoap2 (plugin que estou usando para conexão) eu devo colocar o ip, acho que uma solução seria achar o ip pelo hostname e depois fazer a conexão por esse ip... mas como achar ele pelo hostname? (me corrijam se eu estiver errado...)
Answer: Tem uma classe chamada InetAddress que pode te ajudar:
InetAddress endereco = InetAddress.getByName("hostname");
String ip = endereco.getHostAddress();

Referência: https://docs.oracle.com/javase/7/docs/api/java/net/InetAddress.html
Comment: funcionou :) obrigado

Achar ip dentro da rede


Why does Clang think these types in Cairo conflict?

Question: I am building cairo from source using Clang. I get the following error:
src/cairo-quartz-font.c:368:1: error: conflicting types for 'cairo_quartz_font_face_create_for_cgfont'
cairo_quartz_font_face_create_for_cgfont (CGFontRef font)
^

src/cairo-quartz-font.c:247:18: note: previous implicit declaration is here
*font_face = cairo_quartz_font_face_create_for_cgfont (cgFont);

However, looking at the source, I find these definitions:
247:
CGFontRef cgFont = NULL;
// ...
*font_face = cairo_quartz_font_face_create_for_cgfont (cgFont);
CGFontRelease (cgFont);

368:
cairo_font_face_t *
cairo_quartz_font_face_create_for_cgfont (CGFontRef font)
{
    cairo_quartz_font_face_t *font_face;
    // ...

The full source is mirrored here.
What is the type conflict here?
Answer: When you use the function cairo_quartz_font_face_create_for_cgfont at line 247, it is undeclared (you should get a warning about that unless you fail to use -Wall). So the compiler fills in an assumed return type of int.
When you finally declare the function, its return type is not int. So that's a type conflict.
Normally this sort of problem would be avoided by #includeing a header with the function prototypes.
Comment: Alternatively, when you are calling a function that is defined in the same translation unit, as in this case, it suffices for the definition to appear before any of the calls.  Also, and especially for static functions and others not called from other translation units, it may be more appropriate to put a declaration of the function directly into the source file, before any calls to it.
Comment: Yes, it was a missing declaration. In the header file the function is only declared if the flag `CAIRO_HAS_QUARTZ_FONT` is set. Passing this to the compiler at the command line solved the problem.


Questions about variable selection for classification, and different classification techniques

Question: I have a question concerning feature selection and classification. I will be working with R. I should start by saying that I am not very familiar with data mining techniques, aside from a brief glimpse provided by an undergraduate course on multivariate analysis, so forgive me if I am lacking in details regarding my question. I will try my best to describe my problem.
First, a little about my project:
I am working on an image cytometry project, and the dataset is composed of over 100 quantitative features of histological images of cellular nuclei. All of the variables are continuous variables describing features of the nucleus, such as size, DNA amount, etc. There is currently a manual process and an automatic process for obtaining these cellular images. The manual process is (very) slow, but is done by a technician and yields only images that are usable for further analysis. The automatic process is very fast, but introduces too many unusable images - only about 5% of the images are suitable for further analysis, and there are thousands of nuclear images per sample. As it turns out, cleaning the data obtained from the automatic process is actually more time consuming than the manual process.
My goal is to train a classification method, using R, to discriminate between good objects and bad objects from the data obtained from the automatic process. I have an already classified training set that was obtained from the automatic process. It consists of 150,000 rows, of which ~5% are good objects and ~95% are bad objects.
My first question deals with feature selection. There are over 100 continuous explanatory features, and I would like possibly get rid of noise variables to (hopefully) help with the classification. What methods are there for dimensionality reduction with the goal of improving classification? I understand that the need for variable reduction may vary depending on the classification technique used.
Which leads to my second question. I have been reading about different classification techniques, but I feel that I cannot adequately determine the most suitable method for my problem. My main concerns are having a low misclassification rate of good objects over bad objects, and the fact that the prior probability of the good objects is much lower than the prior probability of the bad objects. Having a bad object classified as good is less of a hassle than recovering a good object from the pool of bad objects, but it would be nice if not too many bad objects were classified as being good.
I have read this post and I am currently considering Random Forests as per chl's answer. I would like to explore other methods as well, and I would like to collect the suggestions of the good people here at CV. I also welcome any readings on the subject of classification that may be helpful, and suggestions for R packages to use.
Please ask for more details if my post is lacking in details.
Comment: I forgot to mention, I am currently exploring the caret package in R.
Comment: @veol caret has a feature selection routine called rfe that you might find useful.  You can read more here, but be careful not to use it on algorythms (such as glmnet) that have built-in feature selection. http://cran.r-project.org/web/packages/caret/vignettes/caretSelection.pdf
Comment: Do you have much of a budget to explore this problem? Is your dataset one that you can publicly share?
Comment: @Zach Thanks for the link. As for the second comment, I was actually hired to work on this project (I'm a university co-op student), so I have ample time to work on this problem. As for the dataset, I am not allowed to share it, but I may be able to link to some articles that are publicly available concerning the type of analysis we do on the data if you want to read about it.
Comment: @veol Oh, I see.  It should be a good learning experience for you then.  It sounded like an interesting analysis, I'd love to see one of the articles.
Comment: @Zach Unfortunately, I could not find free versions of the papers I was given to read. Here is a paper concerning the imaging of the cells and calculating numerical features, it is close to the type of data I am dealing with: [Link](http://www.ncbi.nlm.nih.gov/pubmed/8570289).
Answer: Feature selection does not necessarily improve the performance of modern classifier systems, and quite frequently makes performance worse.  Unless finding out which features are the most important is an objective of the analysis, it is often better not even to try and to use regularisation to avoid over-fitting (select regularisation parameters by e.g. cross-validation).
The reason that feature selection is difficult is that it involves an optimisation problem with many degrees of freedom (essentially one per feature) where the criterion depends on a finite sample of data.  This means you can over-fit the feature selection criterion and end up with a set of features that works well for that particular sample of data, but not for any other (i.e. it generalises poorly).  Regularisation on the other hand, while also optimising a criterion based on a finite sample of data, involves fewer degrees of freedom (typically one), which means that over-fitting the criterion is more difficult.
It seems to me that the "feature selection gives better performance" idea has rather passed its sell by date.  For simple linear unregularised classifiers (e.g. logistic regression), the complexity of the model (VC dimension) grows with the number of features.  Once you bring in regularisation, the complexity of the model depends on the value of the regularisation parameter rather than the number of parameters.  That means that regularised classifiers are resistant to over-fitting (provided you tune the regularisation parameter properly) even in very high dimensional spaces.  In fact that is the basis of why the support vector machine works, use a kernel to tranform the data into a high (possibly infinite) dimensional space, and then use regularisation to control the complexity of the model and hence avoid over-fitting.
Having said which, there are no free lunches; your problem may be one where feature selection works well, and the only way to find out is to try it.  However, whatever you do, make sure you use something like nested cross-validation to get an unbiased estimate of performance.  The outer cross-validation is used for performance evaluation, but in each fold repeat every step in fitting the model (including feature selection) again independently.  A common error is to perform feature selection using all of the data and then cross-validate to estimate performance using the features identified.  IT should be obvious why that is not the right thing to do, but many have done it as the correct approach is computationally expensive.
My suggestion is to try SVMs or kernel logistic regression or LS-SVM etc. with various kernels, but no feature selection.  If nothing else it will give you a meaningfull baseline.
Comment: @veol A linear SVM is a good place to start, but don't just use the default settings, the key to getting good performance from an SVM lies in choosing a good kernel and in carefully optimising the hyper-parameters (the regularisation parameter and any kernel parameters).  This can be done by minimising the cross-validation error or a bound on generalisation performance (e.g. the "radius-margin" or "span" bounds.  I don't use R, but any decent SVM package should automate this procedure via gradient descent or grid search.
Comment: @veol As to sources of information, as well as the two key papers on SVMs (Boser Guyon and Vapnik and Cortes and Vapnik), there are many good textbooks that cover this sort of thing, such as "learning with kernels" by Scholkopf and Smola, "kernel methods for pattern recognition" by Shawe-Taylor and Christianini or "pattern recognition and machine learning" by Bishop.  Best of luck with your project!
Comment: Thank you for your detailed answer. I am not familiar with support vector machines, but I am eager to try it. After a quick read on wikipedia, I am trying linear SVM with the default settings in R on a random subset of my data (it was taking a while with the whole dataset). Do you recommend any good articles or readings for me to familiarize myself with SVMs?
Comment: (+1) nice explanation of the basics. Again where a moment where I'd like to add an answer to my favorites (instead of the whole question).
Comment: Thanks for the great answer, I learned a lot.  How do I do kernel logistic regression in R?
Answer: On dimensionality reduction, a good first choice might be principal components analysis.
Apart from that, i don't have too much to add, except that if you have any interest in data mining, I strongly recommend you read the elements of statistical learning. Its both rigorous and clear, and although I haven't finished it, it would probably give you much insight into the right way to approach your problem. Chapter 4, linear classifiers would almost certainly enough to get you started.
Comment: There's a PDF copy available for download at the link above if that helps.
Comment: Alas, PCA was the first thing I attempted to reduce the dimensionality of the data. It did not provide meaningful results, and I was told to be wary of creating transformations that may only be applicable to the training set and not to the future data. Thank you for the book recommendation - though I am familiar with LDA, there are other methods that may prove to be useful. I will see if there is a copy in my building, or at the university library.
Comment: Ah, hadn't noticed that. I went straight to the table of contents. Reading this feels like a good place to start.


Hosting mail for domain separately - using Godaddy/Plesk/MediaTemple/Heroku

Question: So currently I have a domain name managed through godaddy.
Its hosted on Heroku, and I use custom DNS zones through godaddy, as heroku doesn't host email.
I have a mediatemple account, which I'd like to use to host the email for this domain.
Is this possible?
Answer: Yes. GoDaddy will have help or contact information to get your MX record pointed correctly.


If $x \in (b, \infty)$ Show there exists a natural number $n_0$ such that $x > b + \frac{1}{n_0}$

Question: Assume $\displaystyle \lim_{n \to \infty} \frac{1}{n} =0$ and for $b \in \mathbb{R}$, $\displaystyle \lim_{n \to \infty} b = b$. WITHOUT using the Archimedean postulate, show that if $x \in (b, \infty)$, then there exists a natural number $n_0$ such that $x > b + \frac{1}{n_0}$
Can someone please explain to me how I can show it without using the Archimedean postulate, since that is the only way I know how to answer this question ...
Answer: Since $x-b>0$ there is $n_1$ such that for $n>n_1$ we have $\left|\frac{1}{n}-0\right|<x-b$. This is the definition of $\lim_{n\to\infty}\frac{1}{n}=0$ particularized for $\epsilon=x-b$.
Therefore $b+\frac{1}{n_0}<x$, for $n_0=n_1+1$.
Comment: So basically, we're using the definition of the limit? :). Thank you!
Answer: As x>b and suppose there is natural no. n where :
x <= b + 1/n
So, x-b <= 1/n
Now, 1/n <= 1 (1/n can't be more than 1, it can be only equal and less than 1).
So, x-b <= 1/n <= 1
=> x-b <= 1 for all x.
But as we can see, x can be in the range (b,∞) :
So, what if x>b+1
than x-b > b+1-b
=> x-b > 1
which contradicts the assumed statement So, there must exist a natural no. n0 where x-b > 1/n0
=> x> b+ 1/n0.
Comment: Thank you! :). Can you please type this in LaTeX? :) . It's a bit hard to read this way, since I am using my cellphone. :)
Comment: The $x$ in the problem is given and therefore fixed. Maybe they gave you an $x>b$ such that $x-b<1$.


Find conditional density $f\left(x_1,\cdots,x_n\mid x_{(n)}\right)$

Question: Assume $X_1,\cdots,X_n$ are iid random variables from a uniform distribution on $(-a,a)$. Let $X_{(n)}$ be the $\max_{i=1,\cdots,n} X_i$. How do I find the conditional density
$$f\left(x_1,\cdots,x_n\mid x_{(n)}\right)\,?$$
Ultimately I would like to compute something like
$$\mathbb{P}\left\{ \left(X_1,\cdots,X_n\right)\in A \mid X_{(n)} = c\right\}$$
I know how to find density for $X_{(n)}$, but I don't know how to find density for $\left(X_1,\cdots,X_n, X_{(n)}\right)$. The problem is that $X_{(n)}$ is not independent from the rest.
Answer:
The problem is that $X_{(n)}$ is not independent from the rest.

That's not a problem.  It simply asserts that the density is zero unless at least one of the samples equals the largest order statistic, and further the other samples may not exceed it (since it is the largest).   That defines the conditional function's support.
$f(x_1,\ldots x_n\mid x_{(n)}) =\begin{cases} ?/? &:& (\exists^{=k} j\in\Bbb N{\cap}[1;n]: x_j=x_{(n)}), (\forall j\in\Bbb N{\cap}[1;n]: x_j\leq x_n)\\0 &:& \text{otherwise}\end{cases}$
$~$

$\exists^{=k}$ is the counting existential quantifier: "there exists exactly $k$"


Timestamp atualizar automáticamente com data atual

Question: Gostaria de saber se é possível, quando for feito um INSERT em uma determinada tabela, atualizar automaticamente o valor de uma outra coluna do tipo TIMESTAMP chamada data com a data e hora atual, similar a função NOW() do MySQL?
Comment: @bfavaretto, depende da versão do MySQL e de como foi instalado o MySQL. Se for uma versão atual, e utilizada uma instalação *standard*, você está certo.
Comment: pode utilizar normalmente a função `NOW()` do MySQL na sua instrução do PHP. Se estiver utilizando `bind_param`, basta que não passe o parâmetro `$data` no INSERT, deixando o SGBD com essa responsabilidade.
Comment: Coloque o código que está tendo problemas.
Comment: Vocês não entenderam o problema do OP...
Comment: Colunas tipo `TIMESTAMP` (e não `DATETIME`) não fazem isso automaticamente?
Answer: galera consegui com o simples comando sql abaixo. obrigado á todos
ALTER TABLE `grade_edt` CHANGE `data_ultima_mod`
`data_ultima_mod` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP;

Comment: @FellipeSoares porque pouco usual? É tão relevante assim estar no domínio da aplicação a última alteração do registro?
Comment: Alteração de hardware ou versão do MySQL não irão influenciar na constraint da tabela. Única preocupação é se o sistema for sofrer uma troca de Sgdb ou precise rodar em vários bancos. Estou escrevendo uma resposta para explicar melhor isso. Mas se o sgbd nunca for mudar do mysql, acho o uso da constraint até melhor que gerenciar isso na aplicação
Comment: É uma alternativa pouco usual. O mais comum é deixar essas configurações de responsabilidade da aplicação, mas, funciona.
Comment: @gmsantos, se porventura houverem alterações no hardware do banco de dados, alteração de versão do SGBD ou mesmo a troca do SGBD, poderá ser necessário remodelar a estrutura da tabela, quando que se a responsabilidade fosse da aplicação, você não teria essa preocupação. É mais uma questão de pensamento no ciclo de desenvolvimento. Talvez "usual" não seja a palavra correta a expressar.
Comment: Entendo. Como a pergunta não foi a respeito de um cenário específico, uma resposta levando em conta uma possível troca de SGBD pode ser o mais ideal, visto que esta costuma ser uma dúvida frequente. Já tive problemas também com servidor de aplicação em UTC diferente do servidor de banco de dados, por exemplo.


Convert PHP HTTP request to Guzzle

Question: I currently have an old PHP page which carries out a post request to an external API but i am wanting to convert this to Guzzle to tidy it up but im not sure if im on the right lines with this.
PHP POST
 function http_post($server, $port, $url, $vars)
    {
        // get urlencoded vesion of $vars array
        $urlencoded = "";
        foreach ($vars as $Index => $Value)
            $urlencoded .= urlencode($Index) . "=" . urlencode($Value) . "&";
        $urlencoded = substr($urlencoded, 0, -1);

        $headers = "POST $url HTTP/1.0\r\n";
        $headers .= "Content-Type: application/x-www-form-urlencoded\r\n";
        $headers .= "Host: secure.test.com\r\n";
        $headers .= "Content-Length: " . strlen($urlencoded)

        $fp = fsockopen($server, $port, $errno, $errstr, 20);  // returns file pointer
        if (!$fp) return "ERROR: fsockopen failed.\r\nError no: $errno - $errstr";  // if cannot open socket then display error message

        fputs($fp, $headers);

        fputs($fp, $urlencoded);

        $ret = "";
        while (!feof($fp)) $ret .= fgets($fp, 1024);
        fclose($fp);
        return $ret;
    }

Retrieve PHP response
Below is how you retrieved the response where you could make use of the $_POST fields
 $response = http_post("https://secure.test", 443, "/callback/test.php", $_POST);

Guzzle Attempt POST
$client = new Client();

$request = $client->request('POST','https://secure.test.com/callback/test.php', [
    // not sure how to pass the $vars from the PHP file
    'headers' => [
        'Content-Type' => 'application/x-www-form-urlencoded',
        'Host' => 'secure.test.com'
    ]
]);

$request->getBody()->getContents();

Guzzle Attempt GET
$client = new Client();

    $request = $client->get('https://secure.test.com/callback/test.php');

    $request->getBody()->getContents();

How would i then grab specific fields from the response?
From my attempts above am i on the right lines?
Answer: If you want to send $vars as a body of POST request, you need to set up body property.
$client = new Client();

// get urlencoded vesion of $vars array
$urlencoded = "";
foreach ($vars as $Index => $Value)
    $urlencoded .= urlencode($Index) . "=" . urlencode($Value) . "&";
$urlencoded = substr($urlencoded, 0, -1);

$response = $client->request('POST','https://secure.test.com/callback/test.php', [
    'headers' => [
        'Content-Type' => 'application/x-www-form-urlencoded',
        'Host' => 'secure.test.com'
    ],
    'body' => $urlencoded,
]);

Guzzle can URLencode $vars for you if you use form_params instead of body.
$response = $client->request('POST','https://secure.test.com/callback/test.php', [
    'headers' => [
        'Content-Type' => 'application/x-www-form-urlencoded',
        'Host' => 'secure.test.com'
    ],
    'form_params' => $vars,
]);

To read server's response you need to call getBody on the $response and cast it to string. You will have there exactly the same as return value from your original http_post function.
$resultFromServer = (string) $response->getBody();

Comment: With the form_params solution do I still need to write the encoding above? where would the $vars variable come from if this isn't present.  $urlencoded = "";
foreach ($vars as $Index => $Value)
    $urlencoded .= urlencode($Index) . "=" . urlencode($Value) . "&";
$urlencoded = substr($urlencoded, 0, -1);
Comment: No, with form_params you just assign array with variables that you want to sent to form_params key and Guzzle does encoding. I used $vars as this was the name of the variable used in original function.

Convert PHP HTTP request to Guzzle