Model Selection with Competing risks in Cox regression

Question: When doing cox proportional hazards regression one often has competing risks. The typical approach for this is to fit separate cox proportional hazards models for each risk, censoring the competing risk.
How do you do model selection in this scenario? Should the two models be the same? Do I build a model based on one of the risks and use the same model for the other risk? Do I build a model based off a completely different response (e.g. overall survival)?
Comment: The entire field of model selection is full of false promises.  Please read elsewhere on this site about the many pitfalls and high probability of getting a misleading result.  Or just look at http://www.stata.com/support/faqs/statistics/stepwise-regression-problems/
Comment: You need to define what "build a model" means.  If it means estimating regression coefficients then your approach to fit a series of models with different target outcomes seems sound.  If you mean "variable selection" then you have to question why you would spend time doing variable selection and not using subject matter expertise to specify the model.
Comment: BIC will underfit.  AIC works well if you have say 3 competing models to choose from.  AIC is just a (smarter) restatement of $P$-values so doesn't solve the fundamental problem if the number of competing models exceeds a few.
Comment: @FrankHarrell I was referring to variable selection. This is for a project in school on a real dataset and we don't have access to the "subject matter experts". However, I think "you should only consult the experts" is kind of a cop out answer because that belittles the entire field of model selection.
Comment: I didn't suggest stepwise procedures either, but rather AIC/BIC type of criteria, but you have a valid argument and I can appreciate your experience. Happy Thanksgiving :)
Answer: As you say, one approach is to use cause-specific hazard functions, treating the observations experiencing a competing events as censored. The problem with such approach is that it doesn't have a direct interpretation in terms of survival probabilities, that are  obviously reduced by the the other risk: you are basically diseregarding the information about the events due to it. However, such approach replies to an important etiological question, i.e. how each risk contributes to non-survival: it is epidemiologically interesting because it's based on real probabilities, i.e., in each moment, the one of dying among people that may actually die.
However, you wondered whether you should consider overall survival in modeling competing events. This is another approach, based on Fine and Gray (1999) cause-specific ${subdistribution}$ (i.e. the cumulative incidence function). Here, the drawback is that they consider in the risk set for a given event also individuals that may not have the event itself (because the competing one has already occurred previously), thus, their estimates are not based on probability in a proper sense. However, their approach has a direct interpretation in terms of survival probabilities: it allows to calculate the probability of each event. For example, a Fine and Gray approach may lead us to conclude that, in a given sample, with a given covariate pattern, $25\%$ of patients will die for cardiological reasons, $20\%$ of patients for other reasons, and $55\%$ will survive until the end of the follow-up.
Fine, J. P., & Gray, R.J. 1999.  A proportional hazards model for the subdistribution of a competing risk. Journal of the American Statistical Association,94(446), 496–509.


Salvar Modelos Relacionados (One to One) - Laravel 5.1

Question: Tenho um Model Info e um Model Complemento que estão relacionados um pra um.
Os relacionamentos já estão funcionando corretamente, consigo puxar os dados e tal, mas preciso fazer um update e não sei como.
Atualmente eu recebo todos os dados no request, mas apenas faço o update da tabela infos, como eu faria pra atualizar também os dados da tabela complementos de acordo com a info a qual ela pertence?
Answer: Consegui solucionar essa questão da seguinte forma:
$complemento = Complemento::firstOrNew(['id_info' => $id]);

//requests...

$complemento->save();

ficou até melhor já que tive a necessidade de também criar o complemento caso não existisse.
Answer: Tenho quase certeza que você pode fazer assim:
 $info = Info::findOrFail($id);

 $info->complemento->fill($request->all())->save();

Comment: ola @WallaceMaxters, até tentei fazer dessa forma agora, mas não consegui. De qualquer forma acabei arrumando uma solução melhor para minha necessidade com o firstOrNew


PHP - Shorten Sentence in a String If a Certain Word in an Array is Found

Question: I am working on a PHP script which gets a METAR report and clears it up.  I need to shorten the METAR by deleting everything that follows if certain words are used.
For example, I need to delete everything after BECMG including the space in front of TEMPO in the following string as it is not needed:
$metars = "2013/12/24 07:30 NZOH 240730Z 31011G21KT 280V340 5000 -SHRA FEW020 BKN048 19/14 Q1006 BECMG 20KM TEMPO 6000 RA BKN012 SPECI COR NZOH 240730Z 31011G21KT 280V340 5000 -SHRA FEW020 BKN048 19/14 Q1006 BECMG 20KM TEMPO 6000 RA BKN012";

$comments = array ("BECMG", "RMK", "TEMPO");

$metar = ???

I need $metar to be:
$metar = "2013/12/24 07:30 NZOH 240730Z 31011G21KT 280V340 5000 -SHRA FEW020 BKN048 19/14 Q1006";

There lies the problem.  I can't use length numbers as the length can change.  How can I delete everything after a certain word is found out of an array of words including the space in front of the word to shorten the string?
Also, $metars includes BECMG and TEMPO.  How can I avoid having $metar include BECMG if it is shortened after another word is found?  In other words, I want ot avoid this from happening:
$metar = "2013/12/24 07:30 NZOH 240730Z 31011G21KT 280V340 5000 -SHRA FEW020 BKN048 19/14 Q1006 BECMG 20KM";

I want it to be:
$metar = "2013/12/24 07:30 NZOH 240730Z 31011G21KT 280V340 5000 -SHRA FEW020 BKN048 19/14 Q1006";

Comment: A preg_replace() would help you here. Don't ask me for RegEx though as I'm clueless when it comes to that! Haha  http://php.net/preg_replace
Comment: `strpos` with `foreach` also good enough
Answer: You may use a foreach loop and string functions like strpos and substr to achieve what you need:
$metar = "2013/12/24 07:30 NZOH 240730Z 31011G21KT 280V340 5000 -SHRA FEW020 BKN048 19/14 Q1006 BECMG 20KM TEMPO 6000 RA BKN012 SPECI COR NZOH 240730Z 31011G21KT 280V340 5000 -SHRA FEW020 BKN048 19/14 Q1006 BECMG 20KM TEMPO 6000 RA BKN012";
$comments = array ("BECMG", "RMK", "TEMPO");
foreach($comments as $comment){
$pos = strpos($metar, " ".$comment);
if($pos !== false)
$metar = substr($metar, 0, $pos);
}
// Now $metar is "2013/12/24 07:30 NZOH 240730Z 31011G21KT 280V340 5000 -SHRA FEW020 BKN048 19/14 Q1006"

Comment: Warning: Wrong parameter count for strstr()

I am not sure what is causing that in the code.
Comment: I've modified my answer. You're probably using a PHP version before 5.3.0 when [strstr](http://php.net/strstr) didn't have the optional "before_needle" parameter. Nevertheless, [substr](http://php.net/substr) will be good enough for your purpose.


Como adicionar um valor que calculei a partir de um dado informado aparecer num novo TextView?

Question: Preciso calcular a frequência cardíaca máxima a partir da idade informada pelo usuário (fcm = 220 - idade). Criei os campos para capturar o nome e a idade, mas não consigo fazer com que a fcm calculada apareça na tela. As informações de nome e fcm devem aparecer numa lista rolável. Já fiz tantas alterações que criei algum erro em que o app fecha ao clicar no botão... Enfim, em uma classe Atleta peguei a idade, converti para int e calculei fcm. No Main, não sei como pegar a fcm calculada e lançar no método que processa o clique. Mesma coisa no meu adapter: como fcm não é um TextView, não sei como tratar isso.
public class MainActivity extends AppCompatActivity {
    TextView txtNome, txtIdade;
    Button bt;
    ListView listAtletas;
    List<Atleta> atletas = new ArrayList<>();
    AtletaAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txtNome = findViewById(R.id.txtNome);
        txtIdade = findViewById(R.id.txtIdade);
        bt = findViewById(R.id.bt);
        bt.setOnClickListener(btClickListener);
        listAtletas = findViewById(R.id.listAtleta);
        adapter = new AtletaAdapter(atletas, getBaseContext());
        listAtletas.setAdapter(adapter);
    }

    public void processarClique(View v) {
        Atleta a = new Atleta();
        a.setNome((txtNome.getText().toString()));
        ??????????????????

        atletas.add(a);
        adapter.notifyDataSetChanged();
    }

    View.OnClickListener btClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            processarClique(v);
        }
    };
}

public class Atleta {
    private String nome;
    TextView txtIdade;

    private int idade = Integer.parseInt(txtIdade.getText().toString());
    private int fcm = 220 - idade;

    public void setNome(String nome){
        this.nome = nome;
    }
    public void setFcm(int fcm){
        this.fcm = fcm;
    }
    public String getNome() {
        return nome;
    }
    public int getFcm(){
        return fcm;
    }
}

public class AtletaAdapter extends BaseAdapter {
    LayoutInflater inflater;
    List<Atleta> atletas;

    public AtletaAdapter(List<Atleta> atletas, Context ctx){
        this.atletas = atletas;
        inflater = LayoutInflater.from(ctx);
    }

    @Override
    public int getCount() {
        return atletas.size();
    }

    @Override
    public Object getItem(int position) {
        return atletas.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = inflater.inflate(R.layout.atleta_item, null);
        TextView txtNome = v.findViewById(R.id.txtNomeItem);
        ??????????????

        Atleta a = atletas.get(position);
        txtNome.setText(a.getNome());
        ??????????????????
        return v;
    }
}

Answer: Aqui está sua resposta. Tende entender tudo que eu fiz.
MVC CHORA AO VER ISTO O que é mvc.
public class MainActivity extends Activity {
EditText txtNome, txtIdade, txtFrequenciaCardiaca;
Button bt;
ListView listAtletas;
List<Atleta> atletas = new ArrayList<>();
AtletaAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    txtNome = findViewById(R.id.txtNome);
    txtIdade = findViewById(R.id.txtIdade);
    txtFrequenciaCardiaca = findViewById(R.id.txtFrequenciaCardiaca);

    bt = findViewById(R.id.bt);
    bt.setOnClickListener(btClickListener);
    listAtletas = findViewById(R.id.listAtleta);
    adapter = new AtletaAdapter(atletas, this);
    listAtletas.setAdapter(adapter);
}

View.OnClickListener btClickListener = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Atleta a = new Atleta();
        a.setNome((txtNome.getText().toString()));

        String idade = txtIdade.getText().toString();

        if (idade.equals("")) {
            //ele nao pode deixar sem idade
            return;
        }

        a.setIdade(Integer.parseInt(idade));

        String fcm = txtFrequenciaCardiaca.getText().toString();

        if (fcm.equals("")) {
            //ele nao pode deixar sem frequencia cardiaca atual
            return;
        }

        a.setFcm(Integer.parseInt(fcm));

        atletas.add(a);
        adapter.notifyDataSetChanged();

        //para limpar os campos
        txtNome.setText("");
        txtIdade.setText("");
        txtFrequenciaCardiaca.setText("");
    }
};
}

class Atleta {
private String nome;
private int idade;
private int fcm;

public void setNome(String nome) {
    this.nome = nome;
}

public String getNome() {
    return nome;
}

public int getIdade() {
    return idade;
}

public void setIdade(int idade) {
    this.idade = idade;
}

public int getFcm() {
    return fcm;
}

public void setFcm(int fcm) {
    this.fcm = fcm;
}

public int frequenciaMaximaCardiaca() {
    return 200 - idade;
}

public String resultadoFrequencia() {
    if (getFcm() > frequenciaMaximaCardiaca()) {
        return "Cuidado frequencia cardiaca muito alta";
    } else {
        return "Faça ele correr mais";
    }
}
}

class AtletaAdapter extends BaseAdapter {
LayoutInflater inflater;
//os dados serao obtidos pela lista e nao direto ao edittext
List<Atleta> atletas;
//tem que criar separados
TextView txtNomeItem, txtIdadeItem, txtFrequenciaItem, txtFrequenciaMaximaItem, txtResultadoItem;

public AtletaAdapter(List<Atleta> atletas, Context ctx) {
    this.atletas = atletas;
    inflater = LayoutInflater.from(ctx);
}

@Override
public int getCount() {
    return atletas.size();
}

@Override
public Object getItem(int position) {
    return atletas.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View v = inflater.inflate(R.layout.atleta_item, null);
    txtNomeItem = v.findViewById(R.id.txtNomeItem);
    txtIdadeItem = v.findViewById(R.id.txtIdadeItem);
    txtFrequenciaItem = v.findViewById(R.id.txtFrequenciaAtualItem);
    txtFrequenciaMaximaItem = v.findViewById(R.id.txtFrequenciaMaximaItem);
    txtResultadoItem = v.findViewById(R.id.txtResultado);

    Atleta atleta = atletas.get(position);

    txtNomeItem.setText(atleta.getNome());
    //se torna obrigado a converter em string porque se nao ele achara que é um objeto da memoria
    txtIdadeItem.setText(String.valueOf(atleta.getIdade()));
    txtFrequenciaItem.setText(String.valueOf(atleta.getFcm()));
    txtResultadoItem.setText(atleta.resultadoFrequencia());

    return v;
}
}

Layout main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="16dp"
android:orientation="vertical">

<EditText
    android:id="@+id/txtNome"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="Nome:"
    android:textColor="@color/black" />

<EditText
    android:id="@+id/txtIdade"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="Idade:"
    android:inputType="number"
    android:textColor="@color/black" />

<EditText
    android:id="@+id/txtFrequenciaCardiaca"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="Frequencia cardiaca:"
    android:inputType="number"
    android:textColor="@color/black" />

<Button
    android:id="@+id/bt"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:text="Calcular"
    android:textColor="@color/black" />

<ListView
    android:id="@+id/listAtleta"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>
</LinearLayout>

Layout alteta_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_marginBottom="16dp"
android:layout_marginRight="16dp"
android:layout_marginLeft="16dp">

<TextView
    android:layout_marginTop="8dp"
    android:id="@+id/txtNomeItem"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textColor="@color/black" />
<TextView
    android:id="@+id/txtIdadeItem"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textColor="@color/black" />
<TextView
    android:id="@+id/txtFrequenciaMaximaItem"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textColor="@color/black" />
<TextView
    android:id="@+id/txtFrequenciaAtualItem"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textColor="@color/black" />
<TextView
    android:id="@+id/txtResultado"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textColor="@color/black"
    android:layout_marginBottom="8dp"/>
</LinearLayout>


Hide url in subdirectory install?

Question: in my site I use version 7 of Drupal and Linux OS on the server, and need to hide the subdirectory of the installation when access by LINK ...
explaining better:
Current link: www.site.com/folder
I want to change for only:
www.site.com
I searched in various forums, websites and how is an old subject, I believe that there was a change in the code to hide / delete the symbolic url paste ...
In the folder / root .htaccess I created left like this:
Options + FollowSymlinks
RewriteEngine On
RewriteRule ^ (. *) $ Folder / $ 1 [L]
Thus, to access the site, only the index remains without the folder ... I want the whole site be without referencing the subfolder where it was installed ... How do I do this? thank you
Answer: Add this rewrite rule in your .htaccess file:
RewriteEngine On
RewriteRule ^/subfolder/(.*)$ http://www.example.com/$1 [L,R=301]

Change subfolder and www.example.com.
Also, you can try with this:
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ http://%1%{REQUEST_URI} [NE,R=301,L]

RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$
RewriteRule !^subfolder/ /subfolder%{REQUEST_URI}  [L]

Again change you domain and subfolder name.
Comment: This dont work... i try in too many ways and not work, just the first access from link appears without a subfolder....
Comment: mixerowsky, This actually worked for me, except, all of my links are still including the subfolder. How do I gave ALL links to string out the subfolder?
I should also say that I can nav to the links without the "subfolder" part, but naturally I want that part gone/hidden.

Hide url in subdirectory install?


How can we use as input only one row for each node-cell of a dense layer?

Question: I will like to ask: How can we use as input only one row of a dataset for each node-cell of a dense layer?
Answer: The extended version about how to manage multiple inputs and outputs in keras-models:
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import numpy as np
import time

#Examples...in case of input size of one row only...
input_vector_1=[1,2,3]
input_vector_2=[4,5,6]
input_vector_3=[7,8,9]

#Examples in case of 3000 rows of input...
input_matrix_1=np.random.uniform(0,1,size=(3000,3))
input_matrix_2=np.random.uniform(0,1,size=(3000,3))
input_matrix_3=np.random.uniform(0,1,size=(3000,3))

#Inputs...according to decided input shape...
syote_1=keras.Input(shape=(3000,3))
syote_2=keras.Input(shape=(3000,3))
syote_3=keras.Input(shape=(3000,3))

#Let's make next layer for the network...
valikerros_1=layers.Dense(1)
valikerros_2=layers.Dense(1)
valikerros_3=layers.Dense(1)

#And attach input to this layer...
x1=valikerros_1(syote_1)
x2=valikerros_2(syote_2)
x3=valikerros_3(syote_3)

#Let's make the neural network...
kolmen_syotteen_malli=keras.Model(inputs=[syote_1,syote_2,syote_3],outputs=[x1,x2,x3],name="Special neural network model with three inputs and three outputs")

#And show its strutuce
kolmen_syotteen_malli.summary()

#Also save as a picture...for clearness...
keras.utils.plot_model(kolmen_syotteen_malli,'structure.png',show_dtype=True)

#And let's demonstrate the output:
input_1_in_testing=tf.reshape(input_matrix_1,[1,3000,3])
input_2_in_testing=tf.reshape(input_matrix_2,[1,3000,3])
input_3_in_testing=tf.reshape(input_matrix_3,[1,3000,3])

test_output=kolmen_syotteen_malli([input_1_in_testing, input_2_in_testing, input_3_in_testing])

print("Test output with index 0 for the your testing inputs has a shape: ",test_output[0].shape)
print("Test output with index 1 for the your testing inputs has a shape: ",test_output[1].shape)
print("Test output with index 2 for the your testing inputs has a shape: ",test_output[2].shape)

Comment: the number of syote layers (which are 3 ) is based on what?
Comment: Your input has a shape of (n,3) but the input of TimeDistributed should be at least 3D, thus in principle not. But - if you are interested about TimeDistributed, please carefully check is it possible to formulate your data (your problem definition...) to a format where there is e.g. RGB-images with several time-steps. If yes, then, after appropriate modification of your model it is possible to use the TimeDistributed layer, too.
Comment: Answer also to my first comment pls
Comment: the number of syote layers (which are 3 ) is based on what? ---> answer is that the first number in this definition is the number of rows of input_matrix_1 and the second number is number of columns in the input_matrix_1. Change those numbers if your input shape changes - accordingly.
Answer: This way:
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import numpy as np
import time

#Examples...
input_vector_1=[1,2,3]
input_vector_2=[4,5,6]
input_vector_3=[7,8,9]

#Inputs...
syote_1=keras.Input(shape=(1,3))
syote_2=keras.Input(shape=(1,3))
syote_3=keras.Input(shape=(1,3))

#Let's make next layer for the network...
valikerros_1=layers.Dense(1)
valikerros_2=layers.Dense(1)
valikerros_3=layers.Dense(1)

#And attach input to this layer...
x1=valikerros_1(syote_1)
x2=valikerros_2(syote_2)
x3=valikerros_3(syote_3)

#Let's make the neural network...
kolmen_syotteen_malli=keras.Model(inputs=[syote_1,syote_2,syote_3],outputs=[x1,x2,x3],name="Special neural network model with three inputs and three outputs")

#And show its strutuce
kolmen_syotteen_malli.summary()

#Also save as a picture...for clearness...
keras.utils.plot_model(kolmen_syotteen_malli,'structure.png',show_dtype=True)

...you will get a structure like this:

...you can easily change structure - also test and try - and see the effects by monitoring the corresponding result network structure picture.
Comment: what if i have 3000 rows? i will have to initialize 3000 X { syote_1=keras.Input(shape=(1,3)) } this?
Comment: increase 1 to 3000 in the shape
Comment: in Dense layer or input layer?
Comment: In Input layer.
Comment: I'll add another answer, including clarification about the required shapes.


MDX get total for details

Question: how to get total along with the detail based on this query? It is similar to this but more complex. ssas 2005 mdx get total
    select

    {
    [Measures].[Promo sold value]
    ,[Measures].[Promo units]
    ,[Measures].[Promo baskets]
    ,[Measures].[Promo ATV]
    ,[Measures].[Promo AUT]
    ,[Measures].[Promo discount]
    } ON COLUMNS

    ,
    non empty
    [Branch].[Branch].[Branch]
    *[Branch].[Branch Code].[Branch Code]
    *[Time].[Finacial year].[Finacial year]
    *{
    [Time].[Finacial week no].&[27]&[12]
    ,[Time].[Finacial week no].&[28]&[12]
    ,[Time].[Finacial week no].&[29]&[12]
    ,[Time].[Finacial week no].&[30]&[12]
    ,[Time].[Finacial week no].&[31]&[12]
    }
    *{
        [Promotions].[Promotion].[a]
        ,[Promotions].[Promotion].[b]
    }

    on rows
    from [Rmis]

Answer: You can get that similar to the query referenced by you:
WITH set [weeks] as
    {
    [Time].[Finacial week no].&[27]&[12]
    ,[Time].[Finacial week no].&[28]&[12]
    ,[Time].[Finacial week no].&[29]&[12]
    ,[Time].[Finacial week no].&[30]&[12]
    ,[Time].[Finacial week no].&[31]&[12]
    }
    set [promos] as
    {
    [Promotions].[Promotion].[a]
    ,[Promotions].[Promotion].[b]
    }
    member [Time].[Finacial week no].[Total] as
    Aggregate([weeks])
    member [Promotions].[Promotion].[Total] as
    Aggregate([promos])
SELECT
{
[Measures].[Promo sold value]
,[Measures].[Promo units]
,[Measures].[Promo baskets]
,[Measures].[Promo ATV]
,[Measures].[Promo AUT]
,[Measures].[Promo discount]
} ON COLUMNS
,
non empty
{(
 [Branch].[Branch].[All],
 [Branch].[Branch Code].[All],
 [Time].[Finacial year].[All],
 [Time].[Finacial week no].[Total],
 [Promotions].[Promotion].[Total]
)}
+
(
[Branch].[Branch].[Branch]
*[Branch].[Branch Code].[Branch Code]
*[Time].[Finacial year].[Finacial year]
*[weeks]
*[promos]
)
on rows
from [Rmis]

Depending on your dimension configuration, you may have to adapt the names of the All members.
Comment: This is excellent, I need more practice on MDX. Can you recommend a good resource?
Comment: A good book is "MDX Solutions with Microsoft SQL Server Analysis Services 2005 and Hyperion Essbase" by five different authors. But of course, there are other sources as well.

MDX get total for details


Static library, bundle and IB Designable

Question: I'm trying to use the IB Designable and IB Inspectable in my UIButton but seems there are some errors.
In the Issue Navigator, the bundle file:

Storyboard :
  IB Designables : Failed to update auto layout status: Failed to load designabled from path (null)

So I wonder if there are any configurations to do to use it in a static lib or something like that ?
This is
#import <UIKit/UIKit.h>

IB_DESIGNABLE

@interface CustomUIButton : UIButton

@property (nonatomic) IBInspectable int cornerRadius;

@end

My custom button I want to live render is inside a view controller
Answer: Unfortunately it isn't possible to use IBDesignables with static libraries (or static frameworks).
This isn't a great answer but I want to give some context on why.
It seems that the way Interface Builder loads classes to be shown as designables is by actually dynamically loading the dynamic framework that you create (and not your app's binary), and using the classes directly (after changing them using the Objective-C runtime quite a bit).
You can see that Interface Builder isn't loading your app, and just the individual frameworks with these steps:

Create a new Xcode project
Create a new framework target in the project
Add a class that is IBDesignable
In the storyboard from your app create a view and set its class to your framework's IBDesignable class
Click "Refresh All Views" in the "Editor" menu
In your DerivedData folder for the project, in the IBDesignables directory, you can see that only your framework target has been built.

Interface builder actually loads your framework using dlopen manually. You can also see that to facilitate this when building your framework, Interface Builder actually adds 2 RPATHs to your binary, so the dependencies can be found in the custom paths (you can view this with otool -L frameworkbinary). This method of loading your binary isn't possible with static libraries.
For what it's worth I think the best workaround for this is to build dynamic frameworks, instead of static libraries, but only for IBDesignable builds. You'll have to do some configuration work to do this, and it isn't easy to work around Xcode to have this work, but if you try it, you can use either the build path, or the environment, to differentiate IBDesignable builds vs "normal" builds.
Comment: How would you make separate configurations for "normal" and ```IBDesignable``` builds? I'd like to use ```IBDesignable``` UI elements but I can't switch to dynamic libraries.
Comment: You can do this by overriding the undocumented `LD` build setting, which replaces the default ld executable, and change the settings based on the build directory, which includes IBDesginables for these builds only. See https://github.com/keith/swift-staticlibs for an example of using this build setting, and parsing the arguments passed to ld.
Answer: EDIT: IB Designable and IB Inspectable do not seem to work with static libraries, so if you're using a static library, either consider using a dynamic framework (iOS 8 only) or move your component outside the static library, if possible.
For issues related with Cocoapods, use the following solution:
This is related to this question.
Here's the solution:
1) Install Cocoapods (0.36.0.beta.1) or newer;
2) Add use_frameworks! to your Podfile
See more here.
Comment: He didn't specified that he was using CocoaPods. This problem seems to affect IB_DESIGNABLES that reside on a static library and are used on storyboards or xibs from another project.
The use_frameworks! directive seems to tell CocoaPods to import frameworks instead of static libraries.


Issues with a form validate hook

Question: I'm encountering an issue tying in a #validate hook into the Drupal registration form. In a custom module, I have a call to the User Register form (the form that is used on Account Creation) and an addition to #validate that should run an outside validation function.
/**
 * Implements hook_form_FORM_ID_alter()
 * Form ID: user_register_form
 */
function mymodule_form_user_register_form_alter($form, &$form_state) {
  $form['#validate'][] = "mymodule_validate_register_form";
}

function mymodule_validate_register_form($form, &$form_state) {
  //validation code
}

And on running a dpm of the Register Form, the validate statement is in place. However, it appears that the functions is never being run.
When I look at the #validate array, its the last option, predated by user_account_form_validate, user_validate_picture, and user_register_validate. Is it possible that its never being run due to the order of the other validate statements, or is there something wrong in my logic? Are there other approaches to validating the data during User Registration over the hook_form_FORMID_alter function?
Answer: This:
function mymodule_form_user_register_form_alter($form, &$form_state) {

needs to be this:
function mymodule_form_user_register_form_alter(&$form, &$form_state) {

Notice $form is by reference in the second snippet.

Issues with a form validate hook


Custom form password validation / strength enforcement

Question: I have a custom form that would create user. The form is rendered with Form API and is using PasswordConfirm element, but it doesn't seem to validate the password against the default password rules (e.g. number of characters, combinations of characters).
How do I apply the default Drupal password rules to my custom form's password confirm field in the form validation method?
Comment: I don't think Drupal does have password rules by default? It lists some recommendations, but they're just recommendations AFAIK.
Comment: You're right. I just started to realize this.
Answer: Built in is only recommendation. But there are several contrib modules like https://www.drupal.org/project/password_policy
Use such a module.
If you have created your own custom form, just use the usual

public function validateForm(array &$form, FormStateInterface
$form_state)

method to implement your rules.
Comment: Thanks for the answer. I played with the module for a while, but there are issues with it. I'm using the "password_policy.validator" (`Drupal\password_policy\PasswordPolicyValidator`) to validate the password. While it works to provide a bool result, it does not tell you what is wrong when the test fail. That is certainly a problem.
Comment: I just extended the class to make things work for me. Thanks for the suggestion.


I can't filter list term under admin/content

Question: I can't filter list term under admin/content.
There is not filter option for list term, just the types (taxonomy)
This is Drupal 7, ther is no category option.

This is Drupal 6, it can filter category.

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Installed Admin Views and add the following settings to /admin/structure/views/view/admin_views_node/edit

But term list still not appearing.
Answer: admin/content page doesn't list taxonomy terms, it shows content nodes. Those options in the select list are actually Content Types you can filter by.
To view taxonomy terms, the link is admin/structure/taxonomy.
Anyway, in the remote case you do want to have better filtering options for nodes, I recommend the module Admin Views.
After enabling Admin Views module, you can go to /admin/structure/views/view/admin_views_node/edit to edit the view that's responsible for displaying the admin node list. Here you can add as many exposed filters you need, in your case, the term reference field.
Admin Views also requires Views Bulk Operations module which allows you to execute operations on multiple nodes at once.
Edit: Your taxonomy vocabulary filter needs to be exposed to appear in the form (click on the filter, then click on 'Expose this filter to visitors, to allow them to change it'). Then all vocabularies should appear in the filter form.
Comment: Drupal 6 can filter the term but Drupal 7 can't. I just want to delete articles in bulk.
Comment: Just updated my question
Comment: Drupal 7 doesn't support this out of the box, but if you install Admin Views, you will have access to the admin node list view and you can add any custom exposed filter you need, including the term reference field.
Comment: Thanks. I have installed the module and added term list but still won't come out. Question has been edited.
Comment: I have edited my answer, you need to expose your new filter(s).
Comment: The settings is already in it. The filter just can filter the vocabulary not term. https://i.stack.imgur.com/VlMSP.jpg
Answer: One alternate way:
->You need to create a separate view for this.
->Add a expose filter for taxonomy term field.
->Add Views Bulk Operations (VBO) module.
->Delete the articles in bulk.
If you need more details for this process let me know.


How do I Make a double jump Script that makes the power of the second Jump the Value of the players leader stat value

Question: I made this code thinking it would allow the player to jump Twice and the second Jump be the power of its leader stat but Instead it doesn't even allow the player to Jump a second time.
local UIS = game:GetService("UserInputService")
local player = game.Players.LocalPlayer
local character
local humanoid

local canDoubleJump = false
local hasDoubleJumped = false
local oldPower
local time_delay = 0.2
local jump_multiplier = player.leaderstats.JumpBoost.Value

function onJumpRequest()
    if not character or not humanoid or not
character:IsDescendantOf(workspace) or humanoid:GetState() ==
Enum.HumanoidStateType.Dead then
        return
    end

    if canDoubleJump and not hasDoubleJumped then
        hasDoubleJumped = true
        humanoid.JumpPower = oldPower * jump_multiplier
        humanoid:ChangeState(Enum.HumanoidStateType.Jumping)
    end
end

local function characterAdded(new)
    character = new
    humanoid = new:WaitForChild("Humanoid")
    hasDoubleJumped = false
    canDoubleJump = false
    oldPower = humanoid.JumpPower

    humanoid.StateChanged:connect(function(old, new)
        if new == Enum.HumanoidStateType.Landed then
            canDoubleJump = false
            hasDoubleJumped = false
            humanoid.JumpPower = oldPower
        elseif new == Enum.HumanoidStateType.Freefall then
            wait(time_delay)
            canDoubleJump = true
        end
    end)
end

if player.Character then
    characterAdded(player.Character)
end

player.CharacterAdded:connect(characterAdded)
UIS.JumpRequest:connect(onJumpRequest)

I expected the player to Jump Twice with the second Jump having the power of the leader stat(I only put that and this because it says it wants more detail)
Comment: I see your use of game.Players.LocalPlayer, so I would assume this code is in a LocalScript. Just to clarify, though, is this code in a Script or a LocalScript, and where is the script located?
Comment: Local script and in workspace
Answer: LocalScripts do not execute in game.Workspace: they only run on clients, hence the term 'local'; Scripts, on the other hand, are server-side.
You could use a Script to place your double-jump script--a LocalScript--into incoming players' character models.
-- Server-side Script
local players = game:GetService("Players")
local jumpScript = script:WaitForChild("JumpScript") -- Assume the double-jump script is a LocalScript called 'JumpScript'.

players.PlayerAdded:Connect(function(player)
    player.CharacterAdded:Connect(function(char)
        -- Check to make sure the character model does not already contain the double-jump script, just in case.
        local clone = char:FindFirstChild("JumpScript")
        if (not clone) then
            clone = jumpScript:Clone()
            clone.Parent = char
        end
    end)
end)

As a note, it is good practice to put server-side scripts like this into ServerScriptStorage instead of workspace or Lighting. (You can read about the safety of ServerScriptStoragehere.)
Comment: If you're just going to clone it into the character, why not put the LocalScript in StarterCharacterScripts? That would do this automatically.


O que é Resource acquisition is initialization (RAII)?

Question: Vejo eventualmente em respostas aqui do site o termo "RAII" sendo usado, mas não sei exatamente o que isso significa. Resource acquisition is initialization me parece meio vago.

Mas o que, de fato, significa RAII? O que ele é?
Quais são as motivações por trás dele e que tipos de problema ele procura resolver?

Vejo esse termo sendo frequentemente utilizado no contexto de C++, mas sei que Rust também tem mecanismo similar. Por conta disso não associarei esta pergunta a nenhuma linguagem em específico.
Answer: A sigla já está na pergunta. Esta é uma técnica usada para facilitar o gerenciamento de recursos que um objeto usa vinculando o tempo de vida do recurso (que não deixa de ser um outro objeto) ao tempo de vida do objeto que ele está contido. Assim quando o objeto é criado o recurso é adquirido, e quando o objeto é descartado pela aplicação por qualquer motivo o recurso é liberado junto.
A técnica é considerada um idioma, ou seja, é uma forma especifica de escrever algo, é muito parecido com um padrão de projeto, mas é mais simples e livre. Em alguns casos pode ter algum mecanismo na linguagem ou biblioteca que facilite isso, e costuma ser preciso de fato de auxílio do compilador para obter o resultado desejado.
Em geral a técnica exige que se escreva um código ou use algo pronto da biblioteca, se a operação for muito padronizada, para que o recurso seja adquirido na construção do objeto e depois liberado na destruição do objeto.
Geralmente a técnica é associada à linguagens que possuem gerenciamento de memória determinística, assim o objeto é liberado tão logo ele não esteja mais em uso, liberando assim o recurso de forma sincronizada. Linguagens não determinísticas (Java, C#, etc.) nesse aspecto têm dificuldade porque o objeto demora para ser liberado e geralmente você precisa da liberado do recurso logo, até porque é comum que o recurso seja algo pesado e externo à aplicação, assim exige um outro mecanismo. E por isso vê muito em C++ e Rust.
C tem dificuldade para usar porque a linguagem não controla o tempo de vida dos objetos de nenhuma forma, então dá para fazer, mas é problema do programador gerenciar isso, não é tão bom, robusto e fácil ou ainda portável, e pode criar algum overhead, comparando com as linguagens citadas antes.
Com sua adoção você tem menos dificuldade para gerenciar o tempo de vida dos recursos, caso contrário terá sempre que lembrar que o recurso precisa ser liberado quando o objeto é destruído.
Note que o objeto pode estar em qualquer área da memória, só o tempo de vida dele é conta. Algumas linguagens não determinísticas possuem técnica que ajuda quando o objeto está na pilha, mas as linguagens com RAII real controlam o tempo de vida em qualquer situação, pelo menos se feito da maneira correta. Pode haver o controle em cascata. Então um objeto que está na pilha destruído será o gatilho para destruição de todos objetos associados que usam o RAII, mesmo os que estão fora da pilha, apenas o gatilho inicial precisa estar na pilha.
Mais detalhes.
Documentação C++.
Exemplo Rust.
Relacionado. E também.
Coloquei no GitHub para referência futura.
Answer: É uma técnica que equipara a criação de um objeto na pilha com a alocação de um recurso dinâmico (memória na heap, arquivo aberto, etc.). Quando o objeto sai de escopo, o recurso é automaticamente desalocado.
O objeto é sempre manipulado por valor, não por ponteiro, assim a checagem de escopo normal do compilador garante que o recurso associado vai ser alocado e desalocado na hora certa.
Evitando-se a alocação explícita, evita-se os problemas comuns em C/C++ de vazamento de recursos, ponteiros inválidos sendo usados depois de caírem fora de escopo, etc.
A programação da classe desse objeto não é necessariamente mais complexa, pois basta alocar os recursos dinâmicos na construção, e desalocar na destruição, que o compilador garante que serão feitas.
Um outro caso em que o RAII tem desempenho excepcional é no tratamento de exceções. Quando ocorre uma exceção e o controle do programa volta muitos escopos (digamos, A() chama B() que chama C() que chama D(), ocorre uma exceção que é capturada por A()) o compilador garante que todos os objetos criados ao longo do caminho são devidamente destruídos. Porém, isto não acontece com os objetos em ponteiros, criados com new.
Então, se seu programa usa exceções, provavelmente tem de usar RAII.
Os "smart pointers" são uma ferramenta para lidar com aqueles objetos que têm de ser criados com new, permitindo que o RAII também se aplique a itens alocados dinamicamente.
Com "smart pointers", você pode escrever o programa inteiro sem precisar usar "delete" lugar nenhum, pois os objetos são deletados automaticamente quando o smart pointer cai fora do escopo, e também quando acontecem exceções.


Thread-safe collection for rotating number reading

Question: I'm wondering if there's an inbuilt collection (or any way to make a custom one) in C# that can be used to emit numbers in a rotating/cyclic fashion (see example below), and is thread-safe (so each thread gets the next number in the collection).
Collection with 5 sequential numbers:

Thread 1 read: return value 1
Thread 2 read: return value 2
Thread 3 read: return value 3
Thread 4 read: return value 4
Thread 5 read: return value 5
Thread 6 read: return value 1
Thread 7 read: return value 2
Thread 8 read: return value 3

and so on.
Basically, the next number emitted by the collection (when read by a thread) should be one after the previous one, and it should restart from the beginning at the end of the number set.
Comment: Interlocked.Increment together with modulo?
Comment: What will the threads *do* with these numbers. Is it possible that you're trying to reinvent some kind of partitioning mechanism?
Comment: @Damien_The_Unbeliever Good point. Think of the numbers as IP addresses. Threads will just use the numbers for allocating IP addresses in rotation, reducing random over-allocation to any one IP.
Comment: Built-in? No. "Any way"? Yes, of course. There are countless possible ways you _could_ make one. What have you tried? What did it do? Why did that not meet your goal?
Comment: Thanks @muzzlator, `Interlocked.Increment` is what I was looking for to achieve a round-robin mechanism.
Answer: You can greate a method, that will return infinate enumerable:
    private object _lock = new object();
    private int i = 0;
    private int max = 6;

    public IEnumerable<int> GetNumbers()
    {
        while (true)
        {
            lock (_lock)
            {
                i++;
                if (i == max)
                    i = 1;
                yield return i;
            }
        }

    }

And get them:
var numbers = GetNumbers().Take(1000).ToArray();


Sistema Multi-tenant com possibilidade de "personalização"

Question: Estou levantando conhecimentos para a criação de um sistema multi-tenant. Já andei dando uma olhada em algumas referências do MSDN, do SOEN e do SOPT, assim como de alguns sites diversos.
Apesar de ler as referências, mesmo esclarecendo muitas dúvidas, ainda restam algumas questões que ainda não são totalmente claras para mim. Por isso decidi vir aqui para ver se conseguiria elucidá-las.
Nas referências que eu li, os dois modelos para trabalhar com multi-tenant que mais me chamaram atenção foram:
Sistemas isolados
Esta abordagem tem algumas vantagens, como a facilidade de criar o código e não se preocupar tanto com questões relacionadas à segurança. Porém, acredito que seja uma facilidade ilusória, e, como dito, somente para o desenvolvimento da aplicação, pois a manutenção do sistema tornaria-se onerosa a medida que o número de clientes aumentasse.
Utilizando esta abordagem também permitiria a possibilidade da customização ou personalização do sistema para as necessidades específicas do cliente. E esta possibilidade é importante para este sistema.
Sistema compartilhado
Esta abordagem dificulta o desenvolvimento da aplicação tendo em vista que a segurança deve ser mais bem elaborada para evitar acesso não autorizado à dados que não pertencem ao tenant. Porém a manutenção do sistema seria refletida para todos os clientes. Mas isto não é necessariamente um ponto positivo, pois pode ser que algum cliente não deseje atualizar o seu sistema.
Para fazer personalização neste modelo eu planejava usar MEF para fazer um load dinâmico de plugins para extender as funcionalidades do sistema para o tenant. E para a personalização das views pensei em utilizar uma estrutura assim: {tenant}/Views/.... Caso não existisse a view na pasta do cliente utilizaria uma view padrão do sistema mesmo.
Mais algumas considerações
O tenant acessará o sistema e poderá ter um site vinculado. Ex: acessando o site www.meusite.com.br ele poderá ver o "resultado" das informações que ele adicionou no sistema.
Nesse site o cliente do tenant poderá acessar uma área restrita. Os clientes do tenant dividem-se em 2 perfis: A e B.
Um exemplo para esclarecer melhor:

Os tenants serão donos de concessionárias que poderão pegar carros usados para venda consignada. O tenant adiciona o carro no sistema e logo ele fica visível no site para o cliente com o perfil 'Cliente'. Este perfil pode ter uma 'lista de desejos' por exemplo. E o cliente com perfil 'Proprietário' também pode acessar o site em uma área restrita para poder ver como estão as questões relacionadas ao seu veículo.

Explicado a situação as dúvidas restantes são a seguinte:

Utilizando o modelo isolado o SGBD ficaria com muitas bases de dados. Quais seriam as possíveis implicações disto?
Utilizando o modelo compartilhado, as operações no banco de dados não teriam uma perda de performance devido ao filtros necessários para garantir o acesso à somente aos dados do tenant?
Ainda no modelo compartilhado, o crescente número de registros na tabela seria mais um empecilho para a performance?
Em relação à escalabilidade de uma aplicação com esta estrutura, o que seria possível fazer para evitar problemas de performance?
Seria uma boa ideia utilizar MEF para carregar extensões para controllers com a finalidade de adicionar funcionalidades?
Seria possível fazer que o site do tenant seja redirecionado para o conteúdo 'público' do sistema?
Como poderia automatizar a criação desses tenants para reduzir a interação humana?
Seria ainda possível disponibilizar caixas de e-mail personalizadas para estes tenants. Ex: firstname.lastname@example.com.
Comment: Você poderia detalhar melhor as 3 últimas perguntas? Não ficou claro o que seria o conteúdo "público", o que você entende como automatizar a criação de tenants e sua dificuldade específica com as caixas de e-mail.
Comment: Essa resposta vai ficar enorme. Vou levar um tempo pra digitar tudo.
Comment: @Dherik o conteúdo público é como no exemplo da conceissionário. Tem a visão administrativa do sistema e uma visão como um site, onde seria como um mostruário dos veículos cadastrados, com opção de filtros pré-definidos. Em relação a automatização seria algo como: O tenant faz o pagamento on-line e a criação da base de dados e das demais informações necessárias para ele utilizar o sistema são geradas sem a necessidade de interação humana.
Answer: Utilizando o modelo isolado o SGBD ficaria com muitas bases de dados. Quais seriam as possíveis implicações disto?
Seria necessário uma publicação por cliente. Daria um pouco de trabalho, mas com um script é possível automatizar.
Utilizando o modelo compartilhado, as operações no banco de dados não teriam uma perda de performance devido ao filtros necessários para garantir o acesso à somente aos dados do tenant?
Teriam, naturalmente. Você estaria lidando o tempo todo com um identificador de cliente. É uma coluna a mais e, portanto, mais um ônus para a performance. Com uma boa arquitetura, esse problema não é sentido.
Ainda no modelo compartilhado, o crescente número de registros na tabela seria mais um empecilho para a performance?
Se sua arquitetura não estiver de acordo, sim.
Em relação à escalabilidade de uma aplicação com esta estrutura, o que seria possível fazer para evitar problemas de performance?
Depende da tecnologia de banco de dados, mas como dito acima, se sua aplicação tem uma boa arquitetura os problemas são mitigados naturalmente.
Para bancos de dados relacionais, seria interessante estudar a performance das consultas. Há um estudo intenso de planos de consulta neste artigo. Outra alternativa seria usar o Dapper juntamente com o Entity Framework para cache de consultas.
Seria uma boa ideia utilizar MEF para carregar extensões para controllers com a finalidade de adicionar funcionalidades?
Se a aplicação não for gigantesca, não.
MEF é recomendado para sistemas enormes e extensíveis. Caso seu sistema não tenha este requisito (o que, sinceramente, não acho que seja o caso), não há necessidade de usar.
Seria possível fazer que o site do tenant seja redirecionado para o conteúdo 'público' do sistema?
Sim. Tudo depende do padrão de design que será usado para a aplicação tenente.
Como poderia automatizar a criação desses tenants para reduzir a interação humana?
Seria ainda possível disponibilizar caixas de e-mail personalizadas para estes tenants. Ex: email@example.com.
Fica mais a título de sugestão: evite chaves primárias numéricas e sequenciais. É sabido que o uso de Guids penaliza a aplicação em pelo menos 10% de overhead, mas o ganho em implementação compensa o ônus, como por exemplo a possibilidade de unir as bases sem se preocupar com as chaves.
Já a questão das caixas de entrada é um problema mais amplo: você teria que ter um mecanismo de sincronia de DNS, de endereços SMTP, IMAP, POP... Possível é, mas não seria algo simples.
Comment: Levando em consideração a sua experiência, por qual opção você optaria, pela compartilhada ou pela isolada?
Comment: Além disso, você teria alguma sugestão para a modelagem desta arquitetura ou uma referência para eu me basear?
Outra questão é: o uso de ORM's não adiciona um overhead para a realização das consultas?
Comment: Eu faria a isolada por motivos de coesão e simplicidade de base. Um bom começo [seria este artigo](http://www.codeproject.com/Articles/848111/Multi-Tenancy-System-With-Separate-Databases-in-MV). O uso de ORM's adiciona overheads sempre, mas é um ônus quase imperceptível dada a facilidade de construir a aplicação.
Answer: Utilizando o modelo isolado o SGBD ficaria com muitas bases de dados. Quais seriam as possíveis implicações disto?
Você teria uma dificuldade maior na manutenção do banco, pois os scripts SQL teriam que ser aplicados várias vezes ao invés de uma única vez e teria que monitorar vários bancos (nada que uma boa ferramenta não resolva). Mas, fora isto, este é o melhor cenário na minha opinião, pois: já garante que um tenant não verá dados de outro, diminui o risco de um problema de corrupção afetar todos tenant, possibilidade mover um banco específico para outro ambiente, aplicar soluções específicas para determinados perfis de consulta ao banco, etc.
Utilizando o modelo compartilhado, as operações no banco de dados não teriam uma perda de performance devido ao filtros necessários para garantir o acesso à somente aos dados do tenant?
Haverá, mas não seria tão significativa. Este problema em específico seria o menor dos seus problemas em uma aplicação assim, ao meu ver. Me preocuparia mais com a próxima pergunta na questão de performance.
Ainda no modelo compartilhado, o crescente número de registros na tabela seria mais um empecilho para a performance?
Se esta aplicação prevê muitos registros em algumas tabelas, você provavelmente terá problemas de performance, uma vez que terá uma única base os dados para todos os tenant. E este problema afetará na mesma magnitude mesmo os tenants que tem poucos registros.
Em relação à escalabilidade de uma aplicação com esta estrutura, o que seria possível fazer para evitar problemas de performance?
WebApi: uso de http cache.
Entity Framework: uso de cache de segundo nível.
Banco de dados: assumindo que todas as FKs já tem índice, seria acompanhar de perto as consultas mais comuns no banco de dados e criar índices para os dados que elas acessam também. Estas consultas podem ser identificadas por ferramentas de terceiros próprias para isto ou acompanhando a performance do sistema por alguma outra ferramenta de monitoramento geral, como o NewRelic, atuando pontualmente nas consultas que mais estão causando problemas de lentidão. De qualquer modo, recomendo que um DBA experiente possa acompanhar isto e ajudar.
Seria uma boa ideia utilizar MEF para carregar extensões para controllers com a finalidade de adicionar funcionalidades?
Vou ficar devendo esta resposta agora, vou ler antes sobre MEF :).
Mas depende do grau de customização que planeja ter entre os tenant. Algumas customizações creio que poderiam ser estendidas para todos os tenant. É importante avaliar isto para facilitar não só a sua vida, mas para deixar todos tenant mais felizes.
Agora, se as customizações são realmente particulares, você também pode se interessar de ler sobre External Assembly.
De todo modo, seria importante detalhar qual grau de customização você espera por tenant, pois cada caso pode ser resolvido de maneira diferente: eles terão apenas regras de negócio distintas para a mesma funcionalidade? As telas são iguais para todos mas com validações diferentes? Existem muitas telas particulares para os tenants? Haverá funcionalidades inteiras presentes apenas em um dos tenants?
Seria possível fazer que o site do tenant seja redirecionado para o conteúdo 'público' do sistema?
Na aplicação, não vejo problemas particulares de um sistema multi-tenant para resolver isto. Você poderá controlar sem problemas os diferentes tipos de perfil dos usuário de cada tenant e qual parte do site ele vai acessar, pois a lógica estará no perfil (que é comum a todos tenant, pois o perfil "Proprietário" existirá em todos).
Como poderia automatizar a criação desses tenants para reduzir a interação humana?
Se fala de criar um novo tenant assim que surgir um novo, a melhor maneira será por scripts que preparam isto para você. Como a plataforma é Microsoft, seria com PowerShell. Por tudo o que me falou, deverá ser feito:

Criação do banco de dados. O script em PowerShell conectaria-se ao banco de dados e criaria o banco (sim, é possível).
Criação das tabelas e preenchimento das tabelas de domínio. Imaginando que usará algum mecanismo de migração de banco (como o FluentMigrator), bastaria executar ele para popular o banco recém criado.
População das informações particulares do tenant. Configuração de SMTP, caminho para o logo do tenant, conta de superusuário do tenant, e-mail dele, etc. Seria todas as configurações que pertencem somente a cada tenant e que, na minha opinião, poderiam estar no banco de dados de cada tenant para este tipo de aplicação.
(opcional) Criação de novos diretórios na aplicação. Imaginando que seguirá com a ideia de {tenant}/Views, o script criará este diretórios que são unicamente dos tenant. Mas acho que é isto será necessário apenas quando o tenant realmente precisar destes diretórios, que pelo que entendi seria nos momentos que o tenant teria uma tela própria ou algo do gênero.

Seria ainda possível disponibilizar caixas de e-mail personalizadas para estes tenants. Ex: firstname.lastname@example.com.
Creio que a pergunta anterior responda esta. Você deixaria estas configurações no banco de dados do tenant.
Comment: Muito obrigado pela sua resposta, assim como a do @CiganoMorrisonMendes esclareceram muitas das minhas dúvidas. Pelo que entendi, você optaria pelo modelo isolado, correto? Como você faria para controlar a questão de versionamento de cada tenant assim como as customizações realizadas para eles?
Comment: Sim, modo isolado. Se fala do versionamento de cada tenant no controle de versionamento (Git, Svn, etc), eu tentaria manter todos na mesma branch. Se criar uma branch para cada tenant, as chances da branch de cada tenant virarem uma "nova aplicação" e você perder o controle (mesmo fazendo rebase/merge) é alta. As customizações podem ser de diferentes níveis podendo ter diferentes soluções. Infelizmente, acho difícil existir uma resposta "matadora" que resolverá todos os casos de customização. Se quiser, dê mais detalhes na pergunta do grau de customização que espera ter na aplicação.


How to use query result text as another query's where condition at once?

Question: In those 2 tables
Table A [id, items]
        [1, "a,b,c"]

Table B [id , contents]
        ["a", apple]
        ["b", banana]

I want to get result as [apple, banana] at once like query
select contents from B where B.id in ("a","b","c")

or like
select contents from B where B.id in (select A.items from A where id = 1)

Comment: Normalize your schema. See ["Is storing a delimited list in a database column really that bad?"](https://stackoverflow.com/questions/3653462/is-storing-a-delimited-list-in-a-database-column-really-that-bad) (Spoiler: Yes, it is.).
Answer: You can join the two tables with the find_in_set function:
SELECT contents
FROM   b
JOIN   a ON FIND_IN_SET(b.id, a.items) > 0
WHERE  a.id = 1

Comment: Thank you for quick response.


using decision tree to describe high dimensional data

Question: I have a dataset with 6 numeric columns and one dichotomous factor contain yes and no. I would like to understand when yes is more likely given the 6 numeric columns.
I intend to use a decision tree (e.g. rpart in R) and wonder if I have to watch out for over-fitting in this descriptive rather than predictive scenario?
I would simply search for good hyper-parameters using AUC as performance metric but restrict the size of the tree to keep it consumable.
What do you think?
Comment: How many is your data? You could consider the pre-prunning or post-prunning process. Refer to http://www.saedsayad.com/decision_tree_overfitting.htm for a more detail of the process. As for your question, you could also refer to the link https://datascience.stackexchange.com/questions/323/how-can-we-calculate-auc-for-a-simple-decision-tree as it explain to you the ROC but I do think that with your current way could be applied.
Answer: Yes, you have to watch out for overfitting, if your goal is interpretation. Specifically, if you are going to use R and rpart, once you build your model, the output will show you a table with cp values, these are used to prune the tree and reduce it's size (and overfitting). Normally you would choose the cp value which returns the minimal error. Once you've chosen the desired value you rerun your model with the additional cp argument to prune the tree.
Comment: @MUK Yes, you can have multiple splits (nodes) on the same variable in the same tree.
Comment: Can you use decision tree for one dimensional data ?


Usar ArrayList ou LinkedList

Question: A interface List tem varias implementações, entre elas ArrayList e LinkedList. Geralmente venho utilizando somente ArrayList, mas gostaria de saber em quais cenários é recomendado utilizar a implementação LinkedList em vez ArrayList e se há algum ganho nessa mudança.
Comment: Dê uma olhada nesse link: https://www.devmedia.com.br/diferenca-entre-arraylist-vector-e-linkedlist-em-java/29162
Answer:
Em quais cenários é recomendado utilizar a implementação LinkedList em vez ArrayList

Se não puder justificar o uso de uma LinkedList use ArrayList. Ela deve ser o padrão por ser simples e rápida. Lista ligada não pode acessar um elemento qualquer com complexidade de tempo constante (O(1)), precisa ser, na média, meio linear (O(n/2)), o que pode ser de um pouco a extremamente mais lento, conforme o tamanho.
Quando precisa inserir ou remover itens no meio da lista, e em alguns casos mesmo no fim (quase sempre dá para resolver ou aceitar os casos ruins no fim), aí a lista ligada pode ser um pouco mais útil. Mas só é em alguns casos também, porque para inserir você precisa saber onde está e isto tem um custo semelhante à inserção/remoção em um ArrayList, então o ganho se perde em grande parte das operações, se não em todas.
Geralmente quando precisa de muita inserção/remoção uma árvore costuma ser melhor que uma lista, então ambas são escolhas ruins. Lista ligada hoje em dia é usado em bem poucos casos, onde realmente o acesso segue um padrão de lista ligada e não de outra estrutura.

Há algum ganho nessa mudança?

Em várias operações o ganho é brutal.
Coloquei no GitHub para referência futura.

Usar ArrayList ou LinkedList


Issue training pytorch model on gpu

Question: I am trying to implement the discriminator of a basic MNIST GAN in PyTorch. When I run training on the CPU, it works without any issue giving the desired output. However, when I run it on the GPU it shows a runtime error. I am pasting the code for my model as well as my training below along with the modifications I made to try and run training on the GPU.
dev = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")

def preprocess(x):
    return x.view(-1,1,28,28).to(dev)

discriminator = nn.Sequential(
    Lambda(preprocess),
    nn.Conv2d(1,64,3,stride=2,padding=1),
    nn.LeakyReLU(negative_slope=0.2),
    nn.Dropout(0.4),
    nn.Conv2d(64,64,3,stride=2,padding=1),
    nn.LeakyReLU(negative_slope=0.2),
    nn.Dropout(0.4),
    Lambda(lambda x:x.view(x.size(0),-1)),
    nn.Linear(3136,1),
    nn.Sigmoid()
)
loss = nn.BCELoss()
opt = optim.Adam(discriminator.parameters(),lr = 0.002)

discriminator.to(dev)

def train_discriminator(model, dataset,opt, n_iter=100, n_batch=256):
    half_batch = int(n_batch / 2)
    for i in range(n_iter):
        X_real, y_real = generate_real_samples(dataset, half_batch)
        error = loss(model(X_real),y_real)
        error.backward()
        X_fake, y_fake = generate_fake_samples(half_batch)
        error = loss(model(X_fake),y_fake)
        error.backward()
        opt.step()

Now on running train_discriminator(discriminator,dataset,opt)
I get the following error which I cannot make sense of.
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-15-ee20eb2a8e55> in <module>
----> 1 train_discriminator(discriminator,dataset,opt)

<ipython-input-13-9e6f9b4874c8> in train_discriminator(model, dataset, opt, n_iter, n_batch)
      3     for i in range(n_iter):
      4         X_real, y_real = generate_real_samples(dataset, half_batch)
----> 5         error = loss(model(X_real),y_real)
      6         error.backward()
      7         X_fake, y_fake = generate_fake_samples(half_batch)

~/environments/workspace/lib/python3.7/site-packages/torch/nn/modules/module.py in __call__(self, *input, **kwargs)
    530             result = self._slow_forward(*input, **kwargs)
    531         else:
--> 532             result = self.forward(*input, **kwargs)
    533         for hook in self._forward_hooks.values():
    534             hook_result = hook(self, input, result)

~/environments/workspace/lib/python3.7/site-packages/torch/nn/modules/loss.py in forward(self, input, target)
    496
    497     def forward(self, input, target):
--> 498         return F.binary_cross_entropy(input, target, weight=self.weight, reduction=self.reduction)
    499
    500

~/environments/workspace/lib/python3.7/site-packages/torch/nn/functional.py in binary_cross_entropy(input, target, weight, size_average, reduce, reduction)
   2075
   2076     return torch._C._nn.binary_cross_entropy(
-> 2077         input, target, weight, reduction_enum)
   2078
   2079

RuntimeError: Expected object of device type cuda but got device type cpu for argument #2 'target' in call to _thnn_binary_cross_entropy_forward

Would really appreciate it if anyone could suggest any changes that are needed to be made that will solve this issue.
Comment: What do/don't you understand from that error message? Have you done any debugging? Please provide a [mcve].
Answer: According to the error message, the ground truths are not in GPU:

RuntimeError: Expected object of device type cuda but got device type cpu for argument #2 'target' in call to _thnn_binary_cross_entropy_forward
Comment: Oh, okay.
I made the necessary changes and it worked. Thanks a ton!
Comment: @HarshSulakhe , you can indicate that this answer is correct, so you can help others

Issue training pytorch model on gpu


How to avoid changes in file-permission of any file by transfering to other place?

Question: See I have made one executable file in my fedora -14 linux machine & set its permission is like
-rwxrwxr-x   1 jeegar jeegar     4809 Oct 18 12:40 a.out

But when I transfer this file by "G2ipMsg" (a one program for chating/sharing on local LAN connection) to another fedora 15 machine then its permission are going to changed
Why this happening?
What should I do, so that file's permission noone can change even if I sent or transfer to anywhere?
Answer: The receiver of this file is receiving the contents that your chat application is reading and passing over the network. The receiver is creating a new file with their own default permissions and the contents is being written into that new file.
If you want to transfer files and retain permissions you need to record those permissions along with the file. one way to do this is using 'tar', this will create an archive of the file you want and when you want to extract the file you can specify 'preserve permissions'.
create:
tar -cvf archive.tar file1 file2

extract:
tar -xpvf archive.tar

Answer: Your transfer program "G2ipMsg" needs to know how to transfer permissions, and this is something that it might not be capable of, if the program only transfers the contents of the file, and not permissions and other metadata.
You may be able to work around this a bit by wrapping the file in something that supports the metadata you want. For permissions, a .tar file should be able to store it. (The other end will have to extract the .tar file.)


Distribution of a function of exponential and uniform random variables?

Question: Consider the following independent random variables:
$$\begin{equation} \begin{aligned}
A &\sim \text{Exp}(\lambda_1), \\[6pt]
C &\sim \text{Exp}(\lambda_2), \\[6pt]
B &\sim \text{U}(0,1), \\[6pt]
D &\sim \text{U}(0,1). \\[6pt]
\end{aligned} \end{equation}$$
Define the random variable:
$$M \equiv \frac{(A+BC)^2}{AC(B-1)^2 + CD + A + C}.$$
How do I find the distribution of this random variable?
Comment: Could you explain where $M$ comes from?  It is so strange (a non-homogeneous rational function of degree four) that one wonders whether it might be an attempt to solve a problem in an unusual way and that (therefore) a better way might be available.  It is highly unlikely you will obtain any simple closed form for the distribution of $M.$
Comment: Please register &/or merge your accounts (you can find information on how to do
this in the **My Account** section of our [help]), then you will be able to
edit & comment on your own question.
Answer: Simulate it (this is python)
<code>import numpy as np
lambda1 = 1.0
N = 1000000
A = np.random.exponential(scale=lambda1,size=N)
B = np.random.uniform(size=N)
C = np.random.exponential(scale=lambda1,size=N)
D = np.random.uniform(size=N)
M = (A+B*C)**2/(A*C*(B-1)**2 + C*D + A + C) # N realizations of the random variable

import matplotlib.pyplot as plt
_ = plt.hist(M, bins=5000, density=True) # plot
</code>
Here it is. You could regress something to it for practical purposes.
The other way would be to use your rules for combinations of random variables and work really hard. I don't know what that would become
Comment: I need a mathematical expression for the pdf(M).


How can I add a Hashtable as an object in another hashtable Option Strict On is set?

Question: I'm trying to create an object in VB.net that contains a set of key/value pairs, the values of which  could be strings, ints, or other objects containing key/value pairs.
The following code runs as I would expect; I can add key/values to the hashtable, including another hashtable that I can also add key/values to.  I can also read the values out of the object.
Dim ht As Hashtable = New Hashtable

    ht.Add("Item1", "Item1 Description")
    ht.Add("Item2", 42)

    ht.Add("Item3", New Hashtable)
    ht.Item("Item3").Add("Item3a", "Item3a Description")
    ht.Item("Item3").Add("Item3b", "Item3b Description")

    Console.WriteLine(ht.Item("Item3")("Item3b"))

However, this only works if 'Option Strict' is not set.  Adding Option Strict On gives me an error: "BC30574  Option Strict On disallows late binding".
My question is, 'How can I set a hashtable as a value inside another hashtable when Option Strict On is set?'
I'm open to using collections other than a hashtable if it's that choice that's causing the issue. I don't have the options of setting Option Strict Off, as this is for an 'invoke code' block of a Ui Path workflow.
Thanks!
Comment: The `Hashtable` class effectively became obsolete in 2005. Just as we all started using `List(Of T)` instead of `ArrayList`, so we also started using `Dictionary(Of TKey, TValue)` instead of `Hashtable`. In your case, if your keys are all type `String` and you values are different types then you should be using a `Dictionary(Of String, Object)`. Note that that doesn't solve your problem because you still get values as `Object` references. It's just good practice in this decade.
Comment: Hashtable is a particularly ancient data storage container; why are you using it? ("this is for an 'invoke code' block of a Ui Path workflow" doesn't mean much to me)
Comment: DirectCast(ht("Item3), HashTable).Add(...)
Comment: How about using a `Dictionary`?
Answer: There is different ways as code below shows:
    Dim ht As Hashtable = New Hashtable

    ht.Add("Item1", "Item1 Description")
    ht.Add("Item2", 42)

    ht.Add("Item3", New Hashtable From {{"Item3_1", "Item3_1 Description"},
                                        {"Item3_2", "Item3_3 Description"},
                                        {"Item3_3", "Item3_3 Description"}})

    CType(ht.Item("Item3"), Hashtable).Add("Item3_4", "Item3_4 Description")
    CType(ht.Item("Item3"), Hashtable).Item("Item3_1") = "Another description for Item3_1"

    ht.Add("Item4", New List(Of String) From {"Element1", "Element2"})

Comment: Are you always going to know for sure that the value you are getting will be a `Hashtable`? The fact that you have different types in the values could mean that you won't know know what type you're getting back for a particular key until you get it. In that case, it's actually `TryCast` that you should be using, which would mean restructuring your code a bit.
Comment: I've updated my test code using CType as shown by G3nt_M3caj, and DirectCast as mentioned by @Hans Passant, and both work.  (I just have some reading to do now to properly understand CType and DirectCast, and the uses of each of them...)  Thanks!
Comment: CType is a general type converter and have a vast use as doesn't need types is the same in a conversion (obviosly you cannot convert an Integer to an Image). Directcast is more strict as needs target to be the same/descendant or extended of the type which you are going to convert. Is a bit more faster than Ctype but throws exception when  the type is not correspondent. You also can use TryCast (is like Directcast) which doesn't throws exception if the type missed. At this point you can only test the returned Type if is nothing.Where you are sure the types are the same I suggest DirectCast.


Is there a theorem or conjecture that specifies a balanced prime must be multiple of 3# distance from neighboring primes?

Question: I hope I have written this question in an answerable form.  Basically, I am assuming this theorem or conjecture exists, but I can't find it from my reading / searching (I'm not a mathematician).  What I know:

A "balanced prime" is the middle prime number in a sequence of three consecutive primes in arithmetic progression.  This would make the number "CPAP-3", and thus the minimum separation is 6 = 3# = 3 * 2.
What I've noticed from just analyzing balanced primes (see my post on GooglePlus: I am too new of a user to post an image) is that not only is their minimum separation 6 = 3# = 3 * 2 (see the lowest magenta "line" in picture).  But greater separations must be a multiple of 6 (by observation)

So, my question is: is there a named theorem or conjecture that describes the isolation of balanced primes must be a multiple of 3#?  I'm not a mathematician, but I'm guessing this exists and I just can't find it.
I'm also very interested to know if there's a theorem or conjecture about how the maximum isolation of a balanced prime grows.  It appears to grow faster than log(Pn).
Thanks!
PS: I labeled the graph with terms like "prime loneliness" before I was pointed to better terminology.  "swiss primes" are actually "balanced primes."
EDIT (again): From comments: this is a proven (and easily explained) theorem (much more elementary than the Green-Tao theorem), which covers the more general case of primes in arithmetic progression (AP-K; not necessarily consecutive primes).  Thank you to all for pointing me to the obvious! :)
Comment: The article you gave a link to mentions early on, with reference, a more general result about $k$ primes in AP.
Comment: 3,5,7 appears to be a sequence which has difference which is not a multiple of 3.
Comment: @MarkBennet yes, 3,5,7 is an exception, but I think that would be covered in the theorem for minimum separation of a balanced prime (besides 5, all others have a minimum separation of 3#)
Comment: @AndréNicolas Thank you!  I had read that, but didn't properly realize that CPAP-3 is a special case of AP-3.  And apparently the Green-Tao theorem says:
"If an AP-k does not begin with the prime k, then the common difference is a multiple of the primorial k# = 2·3·5·...·j, where j is the largest prime ≤ k."
Comment: @SteveKoch: That's not the Green-Tao Theorem, it is far more elementary. Green-Tao is the assertion that there are arbitrarily long (finite!) arithmetic sequences of primes.
Comment: I added the pic from your page. Please check if it is the right one...
Comment: Thank you, that's the right picture!
Answer: If you have three numbers in arithmetic progression where the common difference is not divisible by 3, one of those three numbers will be divisible by 3. And in your case, that would mean it would not be prime (unless it were 3).
Answer: I don't think anyone has addressed here the question OP raised of the maximum isolation of a "balanced prime". It is conjectured (but I'm not sure whether it has been proved) that for any odd prime $p$ there are infinitely many three-term arithmetic progressions of primes with $p$ the smallest member. So, for example, there should be infinitely many primes $q$ such that $2q-3$ is prime, making $q$ a balanced prime with isolation $q-3$. In short, the isolation of a balanced prime can, conjecturally, be practically as big as the prime itself.
EDIT: On re-reading the question, I'm no longer sure what's being asked. Maybe OP means primes $p$ and positive integers $a$ such that $p\pm a$ are both prime and there are no other primes between $p-a$ and $p+a$. In that case, we're asking about gaps between successive primes, and there is a lot of literature on that; there are results, and widely-believed conjectures, and lots of room between the two. It's generally believed the gap between $p$ and the next prime maxes out at something like $(\log p)^2$. I see no reason why the isolation of "balanced" primes should be any different.
MORE EDIT: I notice that these primes are tabulated at the Online Encyclopedia of Integer Sequences. However I don't see anything there likely to aid in the estimation of maximum isolation.
Comment: Thanks, @Gerry Myerson!  I don't have reputation to upvote these answers, but thank you everyone for the links and help.


How to pass duration to lilypond function

Question: I defined a simple function:
disdn =
#(define-music-function
     (d)
     (ly:duration?)
   #{
    <dis ais dis g>#d
   #})

I am calling it as follows:
\disdn #8

I am getting an error:
wrong type for argument 1.  Expecting duration, found 8

What is the correct syntax for passing a duration? Please provide documentation reference as well.
Answer: You need to call your function either like this
\disdn 8

or like this
\disdn #(ly:make-duration 3)

When you write #8 you tell Lilypond to use the guile object 8, which is a number. But if you write 8 the parser will try to properly interpret this and will interpret this as duration.
For your code to work though you'd need to write
disdn =
#(define-music-function
     (d)
     (ly:duration?)
   #{
    <dis ais dis g>$d
   #})

Check the documentation for the difference between # and $: https://lilypond.org/doc/v2.24/Documentation/extending/lilypond-scheme-syntax
Basically # will mean the expression is lexed and then evaluated later by the parser. Meanwhile $ will mean that the expression is evaluated while it is being lexed, and the parser will parse the already evaluated expression. So writing
<...>#d

the parser will see <...> followed by a scheme expression and thus first evaluates <...> with the previous duration and then evaluates the scheme expression. But if you do

<dis ais dis g>$d

the parser will see <...> followed by a duration, and will thus evaluate this with the given duration.
Comment: @ElementsinSpace No. `ly:make-duration` takes a duration-log, so for a whole note we use 0, for a half 1, for a quarter 2, for an eigth 3 &c.
Comment: I do not know why, but this site seems to turn $d into a TAB clef ...
Comment: Also, is the "3" supposed to be an "8" in your second code block?
Comment: *(cleaning up my previous comments)*
The site is trying render the Markdown code block as ABCjs (a similar bug sometimes happens with jTab).
To prevent this, use the HTML preformatted text delimiters `` & `` around the code block, and replace angle brackets `<` & `>` with their HTML entities `<` & `>`.


Mapeando Objetos Json em Flutter

Question: boa noite galera estava estudando mapeamento de objetos json atraves de string. e cheguei a este projeto no flutter.
main.dart =>

import 'dart:convert';

class Usuario {
  final int userId;
  final int id;
  final String title;
  final bool completed;

  Usuario({required this.userId, required this.id, required this.title, required this.completed});

  factory Usuario.fromJson(Map<String, dynamic> json){
    return  Usuario(
    userId: json['userId'],
    id: json['id'],
    title: json['title'],
    completed: json['completed']
    );
  }
}

void main() async{

  const String jsonData = """
 [
  {
    "userId": 1,
    "id": 1,
    "title": "delectus aut autem",
    "completed": false
  },
  {
    "userId": 1,
    "id": 2,
    "title": "quis ut nam facilis et officia qui",
    "completed": false
  },
  {
    "userId": 1,
    "id": 3,
    "title": "fugiat veniam minus",
    "completed": false
  }
]
""";

  final todos = Usuario.fromJson(jsonDecode(jsonData));

  print(todos[1].title);
}

mas ao executar o projeto ele fala que a variavel todos nao esta inicializada
como faço para dar certo e executar todos os dados da string jsonData?
estou seguindo este projeto no site: https://medium.com/flutter-comunidade-br/descomplicando-o-json-em-flutter-47e12b87753b
Answer: O problema que você está tendo é que está tentando converter uma lista de objetos do JSON para uma classe do Flutter.
O que você precisa fazer é percorrer essa lista do JSON e converter cada objeto dela e ir jogando em uma lista.

Leia com atenção o artigo, que nele mostro certinho como fazer a conversão de uma lista de objetos do JSON para uma lista de classes no flutter.

Em relação ao teu exemplo, veja como ajustar:
void main() async{

  const String jsonData = """
     [
      {
        "userId": 1,
        "id": 1,
        "title": "delectus aut autem",
        "completed": false
      },
      {
        "userId": 1,
        "id": 2,
        "title": "quis ut nam facilis et officia qui",
        "completed": false
      },
      {
        "userId": 1,
        "id": 3,
        "title": "fugiat veniam minus",
        "completed": false
      }
    ]
    """;

  // Transforma o JSON numa lista de Maps que o Flutter entende.
  final listaRaw = jsonDecode(jsonData) as List;

  // Transforma a lista de Maps em uma lista do tipo da sua classe Usuario
  final List<Usuario> listaDeTodos = listaRaw.map((item) => Usuario.fromJson(item)).toList();

  // Para passar item a item
  for (final element in listaDeTodos) {
    print("Título: " + element.title);
  }

  // Para printar um item em específico
    print("\nTítulo do item 1: " + listaDeTodos[1].title);

}

Obs.: Fico feliz em saber que meu artigo esteja lhe ajudando nos
estudos!

Explicação
Você estava tentando usar um index para acessar valores de uma classe, que não está correto:
  final todos = Usuario.fromJson(jsonDecode(jsonData));

  print(todos[1].title);

Como seu JSON retorna uma lista de objetos, primeiro você precisa transformar isso em uma lista de classes, para depois sim conseguir acessar seus itens através de um index.
Comment: Obrigado por me ajudar.. estou tentando agora abrir um arquivo .json e trazer os dados.

Mapeando Objetos Json em Flutter


Does the graph of a measurable function always have zero measure?

Question:
Question: Let $(X,\mathscr{M},\mu)$ be a measure space and $f\colon X \to [0,+\infty[$ be a measurable function. If ${\rm gr}(f) \doteq \{ (x,f(x)) \mid x \in X \}$, then does it always satisfy $$(\mu \times \newcommand{\m}{\mathfrak{m}} \m)({\rm gr}(f)) = 0$$even if the domain space is not $\sigma$-finite? Here $\m$ denotes Lebesgue measure in $[0,+\infty[$.

Context: define the "shadows" $$\begin{align*} G_{f,<} &\doteq \{ (x,y) \in X \times \left[0,+\infty\right[ \mid y < f(x)
 \} \\ G_{f,\leq} &\doteq \{ (x,y) \in X \times \left[0,+\infty\right[ \mid y \leq f(x)\}.\end{align*}$$One can prove that $$(1) \qquad (\mu \times \m)(G_{f,<}) = \int_X f(x)\,{\rm d}\mu(x)$$ and that, if $\mu$ is $\sigma$-finite, that $$(2) \qquad(\mu \times \m)(G_{f,\leq}) = \int_X f(x)\,{\rm d}\mu(x).$$This implies that if $\mu$ is $\sigma$-finite, then $(\mu \times \m)({\rm gr}(f)) = 0$. But is this hypothesis really needed?
I have the following proofs, in case this helps anyone think:

Proof of (1) without $\sigma$-finiteness: If $A \in \mathscr{M}$ and $f = \chi_A$, then $$(\mu \times \m)(G_{f,<}) \stackrel{(\ast)}{=} (\mu \times \m)(A \times [0,1[) = \mu(A)\m([0,1[) = \mu(A) = \int_X \chi_A(x)\,{\rm d}\mu(x),$$where $(\ast)$ holds because points have zero Lebesgue measure. The above clearly implies that the formula is valid for simple positive functions. If $f$ is measurable and positive, take a sequence $(\varphi_n)_n$ of simple and positive functions that converge to $f$, increasing. Then $\bigcup_n G_{\varphi_n,<} = G_{f,<}$, so upper continuity of the product measure and the Monotone Convergence Theorem give $$\begin{align*}(\mu \times \m)(G_{f,<})&=(\mu \times \m)\left(\bigcup_n G_{\varphi_n,<}\right) = \lim_n (\mu \times \m)(G_{\varphi_n,f})\\ &= \lim_n \int_X \varphi_n(x)\,{\rm d}\mu(x) = \int_X f(x)\,{\rm d}\mu(x),\end{align*}$$as wanted. This fails for $G_{f,\leq}$, since that set equality need not be true anymore. If we still had equality of measures, it would be fine, but I think that amounts to my initial question.
Proofs assuming $\sigma$-finitess: apply Fubini-Tonelli as follows: $$\begin{align*} (\mu \times \m)(G_{f,<}) &= \int_{X \times [0,+\infty[} \chi_{G_{f,<}}(x,y)\,{\rm d}(\mu \times \m)(x,y) \\ &= \int_X \int_{[0,+\infty[} \chi_{[0,f(x)[}(y)\,{\rm d}\m(y)\,{\rm d}\mu(x) = \int_X f(x)\,{\rm d}\mu(x)\end{align*}$$Since points have zero Lebesgue measure, the same argument with $[0,f(x)]$ instead of $[0,f(x)[$ gives the formula for $G_{f,\leq}$. And using $\{f(x)\}$ instead along with $\m(\{f(x)\}) =0$ gives $(\mu \times \m)({\rm gr}(f))=0$.

Bonus track: does anyone know any results in this direction if we had another measure space as co-domain? Is it possible to have "fat" graphics?
Answer: No. First, recall that the product measure is not unique for non-$\sigma$-finite spaces.
Let $(X,\mathscr{M},\mu)=(\mathbb{R},2^\mathbb{R},\#)$ and $f(x)=|x|$. We consider the product measure
$$\nu(A)=\int_\mathbb{R}\#A^xdm(x)$$
where $A^x=\left\{y\in\mathbb{R}:(y,x)\in A\right\}$. Note that this is well-defined in the product $\sigma$-algebra of $X\times\mathbb{R}$ (for rectangles $A=E_1\times E_2$, where $E_1\subseteq\mathbb{R}$ and $E_2\subseteq\mathbb{R}$ is Borel, the map $x\mapsto\#A^x$ is simply $\#E_1\chi_{E_2}$).
It should be clear that $\nu(\operatorname{graph}(f))=\infty$.
Answer: In the non-$\sigma$-finite case you have to be careful with which "product measure" you mean, because they are not all equivalent.  For example, let $X = [0,1]$ with counting measure $\mu$, $Y = [0,1]$ with Lebesgue measure and $f(x) = x$.  The "minimal" product measure on $X \times Y$ gives the graph of $f$ measure $0$, because $\int_Y \chi_{\text{gr}(f)}(x,y)\; dm(y) = 0$ for all $x$,
but the "maximal" product measure gives it measure $1$, because $\int_X \chi_{\text{gr}(f)}(x,y)\; d\mu(x) = 1$ for all $y$.
Comment: @IvoTerek It *might*: In the example in my answer, different orders for iterated integrals define different measures (with the other order we'd obtain $\nu(\operatorname{graph}f)=0$), But if we took, say, two spaces with counting measures then the order for the iterated integrals doesn't matter (and the resulting measure is the counting one).
Comment: Great! Just let me confirm if I understood it right, even it is silly: every different order for the iterated integrals will define a different product measure in the non $\sigma$-finite case? Thanks.
Comment: Ah! Ok, I understood. Thanks a lot. :-)


How to know if a figure is inside another figure

Question: I need to invent an algorithm for determining if a figure is inside another figure. Until now this was done using only straight lines (circles were replaced by a list of straight lines). In that case the following algorithm was used:
For every point (x,y) of figure1, create a straight half-line from (-$\infty$,y) to (x,y) and calculate the number of intersections of that line with figure2. In case the number of intersections is even, then the point is located outside of figure2, in case the number of intersections is odd, then the point is located inside of figure2.
Obviously this algorithm is only applicable when both figure1 and figure2 are composed out of straight lines. Once you are dealing with arcs (pieces of circles) then the situation becomes more difficult, as you can see in following image:

Figure1 is composed out of the points ABC, while figure2 is composed out of the points DEFGH, and as you can see, the fact whether or not figure1 is inside of figure2 depends on the centre of the coloured arc:
  - in case the center is the point E, then figure1 is inside figure2.
  - in case the center is the point I, then figure1 is not inside figure2.
Does anybody have any ideas on how to implement this algorithm? (any idea, even not complete, is welcome)
Thanks
Answer: I think that in the general case you need to consider Boolean operations on conic polygons.
Here are two papers on this subject that Google found:

Boolean Operations on Conic Polygons
A Computational Basis for Conic Arcs and Boolean Operations on Conic Polygons


Simplest way to integrate $\int \frac{u^2+1}{(u^2-2u-1)^2}\mathrm{d}u$

Question: What is the simplest way to integrate $$I = \int \frac{u^2+1}{(u^2-2u-1)^2}\mathrm{d}u$$ ?
I already from Maple know that the answer is
$$I = - \frac{u}{u^2 - 2u - 1} + \mathcal{C}$$
and since the answer is so simple, I thought that there must be some clever way to evaluate the integral. I know one could do partial fractions, but why would one want to suffer so much pain ?
Answer: Notice that the integral can be rewritten as
$$ I = \int \frac{1 + 1/u^2}{(u - 1/u - 2)^2}\mathrm{d}u$$
Now using the substitution $\kappa = u - \frac{1}{u}$, the integral turns into
$$ I = \int \frac{\mathrm{d}\kappa}{(\kappa - 2)^2} = -\frac{1}{\kappa-2} = -\frac{u}{u^2-2u-1} + \mathcal{C}$$
as wanted.
Heh, figured this out just after posting the question. This integral had spun around inside my head for quite a few days.
Comment: But is that the **simplest** way? =)


Consume OAuth2 secured REST API using swagger generated ApiClient

Question: I am trying to use an ApiClient generated by swagger-codegen-maven-plugin (Version 3.0.0), to consume an OAuth2 secured REST API from within my spring boot application. The auth server (keycloak) provides a JWT and refresh token, but I cannot figure out how to best handle tokens in my bean.
At the moment my bean looks like this:
<code>@Configuration
public class SomeApiClientConfiguration {

    @Bean
    public SomeApi someApi() {
        return new SomeApi(apiClient());
    }

    @Bean
    public ApiClient apiClient() {
        ApiClient apiClient = new ApiClient();

        OAuth oAuth = (OAuth) apiClient.getAuthentication("auth");
        oAuth.setAccessToken("");

        return apiClient;
    }
}
</code>
Question is: What is the best approach for getting the token and handling the refresh token?
EDIT: In order to get the token I want to use client ID, username, and password. Grant type: Password Credentials.
Best,
Marc
Comment: which authentication flow do you want to use? Authorization flow with client id and secret?
Comment: @Clijsters I am not sure what exactly you mean, but I added further information to the question if that helps.
Comment: You might want to read about the auth flow here: https://www.appsdeveloperblog.com/keycloak-authorization-code-grant-example/ It is mandatory that you understand how your authentication works.
Comment: This is what we use and what already is enabled: https://www.appsdeveloperblog.com/keycloak-requesting-token-with-password-grant/
Answer: I was able to solve this problem and want to share the solution for future reference:
This is my SomeApiClientConfiguration:
<code>@Configuration
public class SomeApiClientConfiguration{

    @Value("${app.api.url}")
    private String apiURL;

    @Bean
    public SomeApi someApi(OAuth2RestTemplate restTemplate) {
        return new SomeApi(apiClient(restTemplate));
    }

    @Bean
    public ApiClient apiClient(OAuth2RestTemplate restTemplate) {
        var apiClient = new ApiClient(restTemplate);
        apiClient.setBasePath(apiURL);
        return apiClient;
    }
}
</code>
Additionally I needed a SomeApiOAuth2Config class, which look as follows:
<code>@Configuration
@EnableOAuth2Client
public class SomeApiOAuth2Config {

    @Value("${app.api.client-id}")
    private String clientId;

    @Value("${app.api.token-endpoint}")
    private String accessTokenUri;

    @Value("${app.api.name}")
    private String username;

    @Value("${app.api.password}")
    private String password;

    @Bean
    public ClientHttpRequestFactory httpRequestFactory() {
        return new HttpComponentsClientHttpRequestFactory(httpClient());
    }

    @Bean
    public HttpClient httpClient() {
        var connectionManager = new PoolingHttpClientConnectionManager();
        var maxPoolSize = 1;
        connectionManager.setMaxTotal(maxPoolSize);
        // This client is for internal connections so only one route is expected
        connectionManager.setDefaultMaxPerRoute(maxPoolSize);
        return HttpClientBuilder.create().setConnectionManager(connectionManager).build();
    }

    @Bean
    public OAuth2ProtectedResourceDetails oauth2ProtectedResourceDetails() {
        var details = new ResourceOwnerPasswordResourceDetails();
        var resourceId = "";
        details.setId(resourceId);
        details.setClientId(clientId);
        var clientSecret = "";
        details.setClientSecret(clientSecret);
        details.setAccessTokenUri(accessTokenUri);
        details.setClientAuthenticationScheme(AuthenticationScheme.form);
        return details;
    }

    @Bean
    public AccessTokenProvider accessTokenProvider() {
        var tokenProvider = new ResourceOwnerPasswordAccessTokenProvider();
        tokenProvider.setRequestFactory(httpRequestFactory());
        return new AccessTokenProviderChain(
            Collections.<AccessTokenProvider>singletonList(tokenProvider)
        );
    }

    @Bean
    @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
    public OAuth2RestTemplate restTemplate(@Qualifier("oauth2ClientContext") OAuth2ClientContext oauth2ClientContext) {
    var template = new OAuth2RestTemplate(oauth2ProtectedResourceDetails(),     oauth2ClientContext);
        template.setRequestFactory(httpRequestFactory());
        template.setAccessTokenProvider(accessTokenProvider());
        template.getOAuth2ClientContext().getAccessTokenRequest().set("username", username);
        template.getOAuth2ClientContext().getAccessTokenRequest().set("password", password);
        return template;
    }
}
</code>


Output value from array

Question: $rows = mysql_fetch_assoc(mysql_query("SELECT COUNT(*) FROM x WHERE id='{$variable}' GROUP BY id"));
    return $rows;

When i do a print_r($rows), i get an output which looks like this:
Array ( [COUNT(*)] => 2 )

What i want is the '2', so i tried
print $rows[0];

which didn't work. I tried:
print $rows[COUNT(*)];

which didn't work either...
Any ideas?
Thx.
Answer: You can add alias using AS keyword. I given the name as total
"SELECT COUNT(*) AS total FROM x WHERE id='{$variable}' GROUP BY id"

Now you can get it print $rows['total'];
Answer: Just modify your SQL statement to:
SELECT COUNT(*) AS total .......

And now you can access it with total keyword:
print $rows['total'];

Answer: You need a column alias for the COUNT().
$result = mysql_query("SELECT COUNT(*) AS numrows FROM x WHERE id='{$variable}' GROUP BY id"));
if ($result) {
   $rows = mysql_fetch_assoc($result);
   echo $rows['numrows'];
}

*Note about error handling and style:  * I have refactored your code to store the result resource in$result rather than passing it directly to mysql_fetch_assoc().  If your query fails for any reason but you pass the resource directly to a fetch call, you will get errors.
Answer: Please below code
$rows = mysql_fetch_array(mysql_query("SELECT COUNT(*) FROM x WHERE id='{$variable}' GROUP BY id"));
    return $rows;

This will work for you.
If you use mysql_fetch_array then result set come in 2 type one as field name and another as array index 0,1,.... and so on
This will help you
Answer: If you need complex query (for example select article and count of comments for it) I'd use AS as Click suggested, based on those lines from manual:

A select_expr can be given an alias using AS alias_name. The alias is
  used as the expression's column name and can be used in GROUP BY,
  ORDER BY, or HAVING clauses. For example:
SELECT CONCAT(last_name,', ',first_name) AS full_name   FROM mytable
  ORDER BY full_name;

However you need only one value you should use mysql_fetch_row() which always returns numeric array:

Returns an numerical array of strings that corresponds to the fetched row, or FALSE if there are no more rows.

So you would have:
$result = mysql_query("SELECT COUNT(*) AS numrows FROM x WHERE id='{$variable}' GROUP BY id"));
$row = mysql_fetch_row( $result);
print_r( $row); // array( 0 => 2);
echo $row[0]; //2

Or you could use mysql_fetch_result() which is defined as:

Retrieves the contents of one cell from a MySQL result set.

And usage would simply be:
echo mysql_fetch_result( $result, 0, 0); // 2

Answer: function getOne($sql) {
  $res = mysql_query($sql) or trigger_error(mysql_error().$sql);
  if (!res) return FALSE;
  $row = mysql_fetch_row($res);
  return $row[0];
}

$count = getOne("SELECT COUNT(*) FROM x WHERE id='{$variable}' GROUP BY id");

though to use this code one have to understand what user defined function is.
Answer: echo mysql_result(mysql_query("SELECT COUNT(*) FROM x WHERE id='{$variable}' GROUP BY id"), 0, 0);

Output value from array


Como utilizar uma const com middlewares e routes?

Question: Possuo a seguinte const no meu arquivo routes.js:
const database = [];

Para fins de aprendizagem estou utilizando ela como se fosse o meu "database", onde  de acordo com o tipo de requisição eu manipulo esta variável... Esta variável está no arquivo citado acima e estou utilizando dentro das rotas após o uso de certos middlewares.
Utilizando boas práticas eu gostaria de saber como posso utilizar esta variável entre meus middlewares e minhas rotas, o que eu tentei fazer foi criar um middleware global onde eu fazia o seguinte:
res.locals.database = [];
next();

Porém este código "apaga" a variável quando se dá a resposta com o res.
Answer: Não vejo necessidade no uso de middlewares, você pode declarar um módulo como seu banco de dados e acessar esse módulo quando necessário, não precisa anexa-lo no seu res.
Por exemplo:
// database.js

const database = {
    users: [],
    messages: []
}

module.exports = database

Como em NodeJS os dados persistem em memória (volátil), você pode anexar e remover itens desse "banco" em requisições diferentes.
Agora basta importar esse módulo e utiliza-lo nos seus handlers. Exemplo:
// app.js

const express = require('express')
const bodyParser = require('body-parser')
const database = require('./database')

const server = express()
server.use(bodyParser.json())

server.post('/messages', (req, res) => {
    database.messages.push(req.body)
    res.send()
})

server.get('/messages', (req, res) => {
    res.json(database.messages)
})

server.listen(3000, () => {
    console.log('Servidor iniciado na porta 3000')
})

Na rota POST /messages você pode enviar uma carga útil para ser anexada no array de messages, enquanto na rota GET /messages, você recupera todas as mensagens. Esses dados irão persistir porque o database utilizado para todas as requisições é sempre o mesmo.
Comment: Também é possível encurtar o `database.js` para `module.exports = { /* ... */ }`, já que a variável só é exportada, não precisa dela, basta exportar o objeto literal diretamente, mas a variável pode ser útil para que fique claro que aquele objeto é o banco de dados
Comment: Obrigado aos dois, gostei de ambas as respostas.