Custom android controls with elements

Question: I have a pretty basic idea and experience with creating custom android controls.
I know I can create a custom control that is basically a layout with a number of controls in it, add attributes and any kind of logic I would want.
But now I need something a bit different. I have an app in which all of my EditText elements have a gray horizontal line under them.
I know this can be achived with backgroundTint but this is only for api 21 and more.
So instead of adding this gray line below every EditText element I use, I would like to create a custom element that extends EditText but also has this gray line. Something like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<EditText
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<ImageView
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:src="@drawable/gray_divider"/>

</LinearLayout>

And in the code behind:
public class MyEditText extends LinearLayout {

public MyEditText(Context context, AttributeSet attrs) {
    super(context, attrs);
    Init();
}

private void Init() {
    LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.my_edit_text, this);

    InitViews(view);
}

So my problem is this:
In order for MyEditText to function like an EditText I have to create an attribute for every EditText attribute. I want to do this:
<MyEditText android:layout_width="match_parent"
android:layout_height="match_parent"
android:text_color="@android:color/white" />

Without adding anything in the code behind. Is this possible?
Answer: For a good practice in this case, Use a background with bottom line.
    <?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:left="-10dp"
    android:right="-10dp"
    android:top="-10dp">
    <shape android:shape="rectangle">
        <gradient
            android:angle="270"
            android:endColor="@color/transparent"
            android:startColor="@color/transparent" />
        <stroke
            android:width="@dimen/border"
            android:color="@color/border" />
        <corners android:radius="@dimen/border" />
    </shape>
</item>

Make a .xml resource and put it in Drawable folder.Eg border_bottom.xml
And for Edit text just give background like
    android:background="@drawable/border_bottom"

Hope it helps.
Comment: Works like charm! Very elegant as well. Changed the code a bit. `

`

Custom android controls with elements


Android resource linking failed - ao usar a biblioteca stripe e play-services-wallet

Question: Estou integrando o Android com o Strepe e Google-pay. O problema é que está ocorrendo falha no link com os layouts xml. A figura a seguir mostra a falha nos links.
Pesquisei vários problemas semelhantes, mas não deram certo. Alguém sabe o que pode estar acontecendo?

O erro que aparece é o sequinte:

Android resource linking failed
E:\Android-Studio_2\Stripe\ProjetoStripe5\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values-v28\values-v28.xml:7: error: resource android:attr/dialogCornerRadius not found.
E:\Android-Studio_2\Stripe\ProjetoStripe5\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values-v28\values-v28.xml:11: error: resource android:attr/dialogCornerRadius not found.
E:\Android-Studio_2\Stripe\ProjetoStripe5\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml:3493: error: resource android:attr/fontVariationSettings not found.
E:\Android-Studio_2\Stripe\ProjetoStripe5\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml:3493: error: resource android:attr/ttcIndex not found.
error: failed linking references.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="n.com.projetostripe5">

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <meta-data
            android:name="com.google.android.gms.wallet.api.enabled"
            android:value="true" />
    </application>

</manifest>

build.gradle - app

    apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    buildToolsVersion '28.0.3'
    defaultConfig {
        applicationId "n.com.projetostripe5"
        minSdkVersion 22
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    //noinspection GradleCompatible
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

    implementation 'com.stripe:stripe-android:8.3.0'
    implementation 'com.google.android.gms:play-services-wallet:16.0.1'
}

build.gradle - project

    // Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.3.0'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

package n.com.projetostripe5;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.identity.intents.model.UserAddress;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.wallet.AutoResolveHelper;
import com.google.android.gms.wallet.CardInfo;
import com.google.android.gms.wallet.CardRequirements;
import com.google.android.gms.wallet.IsReadyToPayRequest;
import com.google.android.gms.wallet.PaymentData;
import com.google.android.gms.wallet.PaymentDataRequest;
import com.google.android.gms.wallet.PaymentMethodTokenizationParameters;
import com.google.android.gms.wallet.PaymentsClient;
import com.google.android.gms.wallet.TransactionInfo;
import com.google.android.gms.wallet.Wallet;
import com.google.android.gms.wallet.WalletConstants;
import com.stripe.android.PaymentConfiguration;
import com.stripe.android.model.Token;

import java.util.Arrays;

import n.com.projetostripe5.R;

public class MainActivity extends AppCompatActivity {

    private static final int LOAD_PAYMENT_DATA_REQUEST_CODE = 53;

    private View mPayWithGoogleButton;
    private PaymentsClient mPaymentsClient;
    private ProgressBar mProgressBar;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mPaymentsClient =
                Wallet.getPaymentsClient(this,
                        new Wallet.WalletOptions.Builder()
                                .setEnvironment(WalletConstants.ENVIRONMENT_TEST)
                                .build());

        mProgressBar = findViewById(R.id.pwg_progress_bar);
        mPayWithGoogleButton = findViewById(R.id.btn_buy_pwg);
        mPayWithGoogleButton.setEnabled(false);
        mPayWithGoogleButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                payWithGoogle();
            }
        });

        isReadyToPay();
    }

    private void payWithGoogle() {
        PaymentDataRequest request = createPaymentDataRequest();
        if (request != null) {
            AutoResolveHelper.resolveTask(
                    mPaymentsClient.loadPaymentData(request),
                    MainActivity.this,
                    LOAD_PAYMENT_DATA_REQUEST_CODE);
        }
    }

    private void isReadyToPay() {
        mProgressBar.setVisibility(View.VISIBLE);
        IsReadyToPayRequest request = IsReadyToPayRequest.newBuilder()
                .addAllowedPaymentMethod(WalletConstants.PAYMENT_METHOD_CARD)
                .addAllowedPaymentMethod(WalletConstants.PAYMENT_METHOD_TOKENIZED_CARD)
                .build();
        Task<Boolean> task = mPaymentsClient.isReadyToPay(request);
        task.addOnCompleteListener(
                new OnCompleteListener<Boolean>() {
                    public void onComplete(@NonNull Task<Boolean> task) {
                        try {
                            boolean result =
                                    task.getResult(ApiException.class);
                            mProgressBar.setVisibility(View.INVISIBLE);
                            if(result) {
                                Toast.makeText(MainActivity.this, "Ready", Toast.LENGTH_SHORT).show();
                                mPayWithGoogleButton.setEnabled(true);
                            } else {
                                Toast.makeText(MainActivity.this, "No PWG", Toast.LENGTH_SHORT).show();
                                //hide Google as payment option
                            }
                        } catch (ApiException exception) {
                            Toast.makeText(MainActivity.this,
                                    "Exception: " + exception.getLocalizedMessage(),
                                    Toast.LENGTH_LONG).show();
                        }
                    }
                });

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case LOAD_PAYMENT_DATA_REQUEST_CODE:
                switch (resultCode) {
                    case Activity.RESULT_OK:
                        PaymentData paymentData = PaymentData.getFromIntent(data);
                        // You can get some data on the user's card, such as the brand and last 4 digits
                        CardInfo info = paymentData.getCardInfo();
                        // You can also pull the user address from the PaymentData object.
                        UserAddress address = paymentData.getShippingAddress();
                        // This is the raw string version of your Stripe token.
                        String rawToken = paymentData.getPaymentMethodToken().getToken();

                        // Now that you have a Stripe token object, charge that by using the id
                        Token stripeToken = Token.fromString(rawToken);
                        if (stripeToken != null) {
                            // This chargeToken function is a call to your own server, which should then connect
                            // to Stripe's API to finish the charge.
                            // chargeToken(stripeToken.getId());
                            Toast.makeText(MainActivity.this,
                                    "Got token " + stripeToken.toString(), Toast.LENGTH_LONG).show();
                        }
                        break;
                    case Activity.RESULT_CANCELED:
                        Toast.makeText(MainActivity.this,
                                "Canceled", Toast.LENGTH_LONG).show();

                        break;
                    case AutoResolveHelper.RESULT_ERROR:
                        Status status = AutoResolveHelper.getStatusFromIntent(data);
                        Toast.makeText(MainActivity.this,
                                "Got error " + status.getStatusMessage(), Toast.LENGTH_SHORT).show();

                        // Log the status for debugging
                        // Generally there is no need to show an error to
                        // the user as the Google Payment API will do that
                        break;
                    default:
                        // Do nothing.
                }
                break; // Breaks the case LOAD_PAYMENT_DATA_REQUEST_CODE
            default:
                // Do nothing.
        }
    }

    private PaymentMethodTokenizationParameters createTokenizationParameters() {
        return PaymentMethodTokenizationParameters.newBuilder()
                .setPaymentMethodTokenizationType(WalletConstants.PAYMENT_METHOD_TOKENIZATION_TYPE_PAYMENT_GATEWAY)
                .addParameter("gateway", "stripe")
                .addParameter("stripe:publishableKey",
                        PaymentConfiguration.getInstance().getPublishableKey())
                .addParameter("stripe:version", "2018-11-08")
                .build();
    }

    private PaymentDataRequest createPaymentDataRequest() {
        PaymentDataRequest.Builder request =
                PaymentDataRequest.newBuilder()
                        .setTransactionInfo(
                                TransactionInfo.newBuilder()
                                        .setTotalPriceStatus(WalletConstants.TOTAL_PRICE_STATUS_FINAL)
                                        .setTotalPrice("10.00")
                                        .setCurrencyCode("USD")
                                        .build())
                        .addAllowedPaymentMethod(WalletConstants.PAYMENT_METHOD_CARD)
                        .addAllowedPaymentMethod(WalletConstants.PAYMENT_METHOD_TOKENIZED_CARD)
                        .setCardRequirements(
                                CardRequirements.newBuilder()
                                        .addAllowedCardNetworks(Arrays.asList(
                                                WalletConstants.CARD_NETWORK_AMEX,
                                                WalletConstants.CARD_NETWORK_DISCOVER,
                                                WalletConstants.CARD_NETWORK_VISA,
                                                WalletConstants.CARD_NETWORK_MASTERCARD))
                                        .build());

        request.setPaymentMethodTokenizationParameters(createTokenizationParameters());
        return request.build();
    }
}
Answer: Consegui encontrar o problema, alterei a versãodo compileSdkVersion para 28 e exclui a biblioteca

implementation 'com.android.support:appcompat-v7:27.1.1'


Como evitar que o Django localize IDs no template?

Question: Eu estou usando Django 1.4 com localização (L10N) ativada, o que faz com que os valores numéricos no template sejam formatados: 1.234,56. O problema é que toda vez que eu coloco um ID no template, por exemplo:
data-id="{{ form.instance.id }}"

Ele é renderizado como:
data-id="1.234"

Obviamente que se esse ID vai para um request ajax, o ID não é encontrado na base, porque não é um valor int válido. Eu posso evitar esse comportamente utilizando |safe ou |unlocalize, porém em alguns lugares, por exemplo no admin, eu não tenho esse acesso (seria necessário alterar o Django), por exemplo:
{{ original|truncatewords:"18" }}

É possível fazer o Django não localizar IDs de maneira generalizada?
Comment: É possível usar templates customizados para o admin, sem editar o APP admin do Django.
Answer: Você pode desativar o localize em apenas um valor:
{% load l10n %}
{{ value|unlocalize }}

Ou pode desativar em algum trecho do template:
{% load l10n %}
{% localize off %}
    {{ value }}
{% endlocalize %}

Fonte: https://docs.djangoproject.com/en/dev/topics/i18n/formatting/
Answer: Você poderia usar o
def __str__(self):
    return self.id

OU
def __unicode__(self):
    return self.id

E usar a própria classe como string.
Não é a maneira ideal, mas funcionaria.
{{ form.instance }}

Sobre o Admin, é possível criar Templates customizados se necessário, mas imagino que não seja necessário, o Django deve montar os formulários e funcionar corretamente mesmo com a internacionalização ativada.
Comment: Então o `{% url opts|admin_urlname:'changelist' %}{{ original.pk }}` acima estar renderizando o URL como `` pode ser considerado um bug?
Comment: O que vc está fazendo ali é renderizar a id no HTML, num template seu, onde a localização fica ativada, se você está criando links para o admin manualmente em algum template imagino que precise usar o filtro |safe. Eu nunca usei links para urls do Django admin usando a url tag, mas imagino que deva ser possível passar os parâmetros de dentro da tag não? algo como
`{% url opts|admin_urlname:'changelist' original.id %}`
Comment: Não, meu amigo, isso é código do Django! Mas deixe para lá, nas versões mais novas, isso já foi corrigido.
Answer: Você pode evitar essa formatação numérica utilizando o template tag safe:
Entrada:
data-id="{{ form.instance.id|safe }}"

Saída:
data-id="1234"

Referência: https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#safe
Só não entendi o motivo de você estar tendo problemas no admin. No primeiro momento parece que você está customizando. Em seguida diz que o problema ocorre como se não estivesse alterando nada no template do admin.
Comment: A pergunta já menciona a solução com `|safe` ou `|unlocalize`. O problema acontece em todos os lugares onde se renderiza ID em urls, e um desses lugares é o admin (onde eu não quero sobrescrever só para corrigir isso).


paint() and repaint() in Java

Question: I've spent maybe the last two hours browsing and reading up on these methods and the Graphics class, and maybe I'm stupid, haha, but I'm just not understanding them. What are they for? I understand that they're supposed redraw or update components on the screen, but I have never understood why this is required (I'm new to this). For example, if I'm moving a JLabel around the screen, a call to setLocation() moves it just fine. Is that a scenario in which repaint() isn't required? In which scenarios is it useful, and why?
Apologies if you feel that this is a question that could be solved using the search function, but for whatever reason I'm not getting it.
Comment: Repaint is called internally. It is called from within JLabel's setLocation method. (It is actually a longer chain of method calls, feel free to follow it and see what's inside. You an do it in any serious IDE out there)
Comment: Okay, that it is called within setLocation() certainly helps a little bit. Thank you. When would I change something that WOULDN'T call it?
Comment: all controls from swing library can repaint themselves whenever their properties connected in any way with how they look (position, size, color, text, etc.) change. However, when you want to achieve a non-default result, implement the paint method yourself. Drawing geometrical figures in JApplets is a common exercise. You may also want to read up on the subject of double-buffering, which is connected to the way both methods are called. A more real-life example from my experience is extending a swing component to draw the spectrum of a fourier transform of a wav file by overriding paint
Comment: Thank you! Makes much more sense now. So if all I'm using in terms of visuals are built into swing, I don't have to worry about calling repaint()?
Comment: that's right, the library classes will do it for you.
Answer: Difference between Paint() and Repaint() method
Paint():
This method holds instructions to paint this component. Actually, in Swing, you should change paintComponent() instead of paint(), as paint calls paintBorder(), paintComponent() and paintChildren(). You shouldn't call this method directly, you should call repaint() instead.
Repaint():
This method can't be overridden. It controls the update() -> paint() cycle. You should call this method to get a component to repaint itself. If you have done anything to change the look of the component, but not its size ( like changing color, animating, etc. ) then call this method.
Comment: The logic of this answer seems a bit counter-intuitive to me. For paint, you describe, "You shouldn't call this method directly, you should call repaint() instead." Then you go on to say, "If you have done anything to change the look of the component, but not it's size then call this method." for repaint, implying if I have changed its size I can't call either of these functions. If I have changed the size and that's why I want it to redraw the UI, then what do I call?
Comment: Yes, +1 for mentioning that paint() itself shouldn't usually be overridden by user code in Swing.
Comment: Unfortunately, having read lots of documentation, I already have heard this. I just would like to understand what applications I would use it in, and what it actually means to "paint this component".
Comment: Does repaint() reset the component to its original state? Let's say I have a JPanel with a white background, and I've drawn a triangle on it. Is it going repaint to delete that triangle, and reset the JPanel?
Answer: The paint() method supports painting via a Graphics object.
The repaint() method is used to cause paint() to be invoked by the AWT painting thread.
Answer: It's not necessary to call repaint unless you need to render something specific onto a component. "Something specific" meaning anything that isn't provided internally by the windowing toolkit you're using.
Comment: I'm sorry, I don't understand that response. Could you provide an example please? Render what onto what?
Comment: See [this article](http://java.sun.com/products/jfc/tsc/articles/painting/) for a good explanation.

paint() and repaint() in Java


Contradictory Ljung Box results

Question: We want to apply extreme value theory to the maximum yearly temperatures. Before we choose the model we want to test whether or not we can assume independence. First we made a plot of the autocorrelation function:

Thereafter, we applied the Ljung-Box and/or Box-Pierce test. However we find that if we only include one lag, there is no statistical evidence of dependence on the 5% level (our p-value is about 0.1) but if we include 2 or more lags, the p-values are significantly lower than our significance level. Can anyone help us understand what we can conclude from these results?
Answer: It is difficult to answer your question without actually looking into the data not just reflecting on summary statistics like the acf/pacf. To correctly use and understand a statistical test one has to know the assumptions underlying the test ( see A. Wald  https://medium.com/@penguinpress/an-excerpt-from-how-not-to-be-wrong-by-jordan-ellenberg-664e708cfc3d !) . The two tests that you mentioned both requite that the process under evaluation does not have any Pulses, Level/step shifts , seasonal pulses and.or local time trends. Furthermore the process needs to have a constant error process over time.
If you post one of your examples I will try and help. If your data is confidential then I might be able to help offline.
Answer: Please note that LB test has following hypotheses:
H0 :    The model does not exhibit lack of fit.
Ha: The model exhibits lack of fit.
So, significance level higher is better here (has to be >0.05 at least).
Read more from: https://www.itl.nist.gov/div898/handbook/pmc/section4/pmc4481.htm
Answer: A problem is that you're running multiple (at least two) tests here, and the more tests you run, the more likely is it to have a meaningless rejection of a null hypothesis. So in the first place I'd be interested in the precise p-value of the second test, and if this is just below 0.05, I wouldn't interpret this as clear evidence against independence.
Anyway your plot suggests that there might be weak long range dependence (or let's say moderately long range). There isn't any "contradiction" in your results as it may well be that you need to look at lags larger than one to find this. To what extent this will affect your further analysis I can't tell. It may not be that much of a problem, but then this depends on what exactly you want to do.
Note that there is a general misunderstanding about model assumptions. Models are by their very nature idealisations, and model assumptions will never hold precisely. What is important is whether models are violated in ways that mislead the later analysis you want to run. Unfortunately running model misspecification tests as you do here isn't always reliable for addressing this issue. Also note that not rejecting a model assumption does not mean it's true. Particularly Ljung-Box itself could be affected by outliers, so you should look at your actual data to see whether there might be a problem there.

Contradictory Ljung Box results


Não consigo fazer um vetor apontar corretamente para função que ele pertence

Question: Já tentei várias vezes, mas o compilador não entende as referências feitas no cabeçalho da função void CalculaValorparaPagar(float ValorPago[MAX], float Quant_Kwh[MAX],float Preco[MAX], int bandeira[MAX], int tipo[MAX]) e na main CalculaValorparaPagar(&ValorPago[MAX],Quant_Kwh,Preco,bandeira,tipo/i/); e dá o seguinte erro:

[Error] cannot convert 'float' to 'float' for argument '1' to 'void
  CalculaValorparaPagar(float, float, float, int, int)

Como devo proceder?
                #include <stdio.h>
                //#include "headerfiledoconsumo.h"
                #define MAX 2
                int x;
                float Imposto[MAX], Taxa_ilum [MAX];
                float Taxa_Band_Tar [MAX];
                float Quant_Kwh [MAX];
                int tipo [MAX];
                float ValorPago[MAX];
                float Preco[MAX];
                int bandeira[MAX];

                //void CalculaValorparaPagar();
                //void fazperguntas();
                //void imprimevalorpagar();

                void fazperguntas(/*float Quant_Kwh[MAX],float Preco[MAX],int tipo[MAX],int bandeira[MAX]*/){

                for (int i= 0; i<MAX; i++){

                //printf("Informe seu nome:\n");
                //scanf("%s", &nome[i]);
                printf("Informe seu consumo em KW: \n");
                scanf("%f", &Quant_Kwh[i]);
                getchar();
                printf("Digite o preco do Khw: \n");
                scanf("%f", &Preco[i]);
                getchar();
                printf("Informe o tipo de consumidor que voce eh: 1(residencial), 2(comercial), 3(Industrial)\n");
                scanf("%d", &tipo[i]);
                getchar();
                printf("Informe a bandeira tarifaria: Verde(1), Amarela(2), Vermelha(3)\n");
                scanf("%d", &bandeira[i]);
                getchar();

                }
                }

                void CalculaValorparaPagar(float *ValorPago[MAX], float Quant_Kwh[MAX],float Preco[MAX], int bandeira[MAX], int tipo[MAX]){

                    //int i = 10;

                    for(int i=0; i<MAX;i++){

                    if (bandeira[i] == 1){
                        Taxa_Band_Tar[i] = 0;
                    }

                    if(bandeira[i] == 2 || Quant_Kwh[i] > 100){

                        x = (Quant_Kwh[i]/100);
                        Taxa_Band_Tar[i] = x*3.5;
                    }

                    if(bandeira[i] == 3 || Quant_Kwh [i] >100){

                        x = (Quant_Kwh[i]/100);
                        Taxa_Band_Tar[i] = x*10.5;
                    }

                    if (tipo[i] == 1){

                        Taxa_ilum[i] = 23.45;
                    }

                    if(tipo[i] == 2){

                        Taxa_ilum[i] = 29.23;
                    }

                    if(tipo[i] == 3){

                        Taxa_ilum[i] = 37.06;
                    }

                    Imposto[i] = 0.04*Quant_Kwh[i] + 0.02*Taxa_ilum[i];
                    *ValorPago[i] = Quant_Kwh[i]*Preco[i] + Taxa_ilum[i] + Imposto[i] + Taxa_Band_Tar[i];

                    }
                }

                    void imprimevalorpagar(){

                        for(int i = 0; i<MAX; i++){

                 printf("Consumidor %d  Valor a pagar: %f\n", i,ValorPago[i]);
                }

                }

                int main() {

                fazperguntas();

                CalculaValorparaPagar(&ValorPago[MAX],Quant_Kwh,Preco,bandeira,tipo/*i*/);

                imprimevalorpagar();

                }

Comment: A primeira coisa que precisa decidir se vai colocar as variáveis como globais ou locais, fazer os dois ao mesmo tempo não dá certo. É mais complicado fazer tudo local, mas é o certo, global é gambiarra.
Comment: Muito obrigado, vou tentar aqui!
Answer: Eu já comentei o quanto odeio printf e scanf? Enfim, ignore.
A mensagem que o Clang exibe é bem mais esclarecedora:

list.c:24:5: warning: ignoring return value of function declared with 'warn_unused_result' attribute [-Wunused-result]
scanf("%f", &Quant_Kwh[i]);

^~~~~ ~~~~~~~~~~~~~~~~~~~

list.c:27:5: warning: ignoring return value of function declared with 'warn_unused_result' attribute [-Wunused-result]
scanf("%f", &Preco[i]);

^~~~~ ~~~~~~~~~~~~~~~

list.c:30:5: warning: ignoring return value of function declared with 'warn_unused_result' attribute [-Wunused-result]
scanf("%d", &tipo[i]);

^~~~~ ~~~~~~~~~~~~~~

list.c:33:5: warning: ignoring return value of function declared with 'warn_unused_result' attribute [-Wunused-result]
scanf("%d", &bandeira[i]);

^~~~~ ~~~~~~~~~~~~~~~~~~

list.c:110:25: warning: incompatible pointer types passing 'float *' to parameter of type 'float **' [-Wincompatible-pointer-types]
CalculaValorparaPagar(&ValorPago[MAX],Quant_Kwh,Preco,bandeira,tipo/i/);
                    ^~~~~~~~~~~~~~~

list.c:41:35: note: passing argument to parameter 'ValorPago' here
void CalculaValorparaPagar(float *ValorPago[MAX], float Quant_Kwh[MAX],float Preco[MAX], int bandeira[MAX], int tipo[MAX]){
                                    ^
5 warnings generated.

O compilador aponta que você tentou passar float* como se fosse float**
E ao executar, a criaturinha dá um belo Segmentation Fault. O problema é tratar como referência algo que já é um vetor.
Mas, particularmente, acredito que você deveria implodir esse código e fazer algo diferente. Vou listar o que vejo de problemático no seu código:

Variáveis globais. Como imagino que você seja iniciante, serei mais absoluto: não use variáveis globais. Fuja delas como demônios fogem do Van Helsing.
Constantes mágicas. Por exemplo, o que seria esse 3.5 nesta linha : Taxa_Band_Tar[i] = x*3.5;? Qual o "sentido da vida" desse valor? E dos outros valores? Constantes mágicas desse gênero devem ser nomeadas e, se possível, colocadas em um header file.
Funções com parâmetros demais. Para que tanto parâmetro numa mesma função? Pelo que notei, estes parâmetros são de alguma forma relacionados, como se fossem atributos de algum objeto no mundo real - a saber, uma conta de luz.
Pouca encapsulação - parte do problema apontado acima: os parâmetros das funções deveriam estar "mais próximos", formando uma unidade lógica - como uma struct.
Comment: `scanf()`, tudo bem, mas `printf()` é ótimo (embora tenha espaço para melhorias; vide os métodos `string.Format()` de vários descendentes de C)
Comment: É, eu fui meio radical com `printf ()`. É que ele é mal utilizado - o pessoal usando `%d` para imprimir `float`. É fácil abusar dele


Check if Workbench Content Has Published Revision

Question: We are using Rules for advanced Workbench notifications. However, we have a notification that needs to change depending on whether content actually has a previously published version or is entirely new content.
Does anyone know of a way, using  Rules, to check for whether Workbench content has a published revision? (Note: Not whether the current revision is published.)
Answer: I'm assuming this question is about D7 ...
Step 1 - Flag published revisions
Use the Flag module to flag Workbench content whenever a published revision gets created. The flag you'd want to use is a global flag. To actually flag such content, use the Rules module.
Step 2 - Check if flagged
Adapt your existing Rule(s) (for advanced Workbench notifications) to take into account if your content has yes or no been flagged. To do so, you have a choice:

Split your current Rules Action (for those notifications) in 2 Rules Components (in which you can use Rules Condition to check the flag).
Use the Conditional Rules module so that you can include the required Rules Condition(s), to check the status of the flag, within the Rules Actions of your existing rule.


package already installed but rpm -q shows not installed

Question: I have installed package python2-urllib3-1.10.2-7.el7.noarch on my RHEL 7.7 server using yum:
yum install python2-urllib3

and it is successfully installed.
now when I run rpm -q python2-urllib3 it shows me the package is not installed. how to know where is the issue and fix it please.
below is a snapshot for the output:
output
Answer: The "issue" is in the way you're referring to the package name and the specific package you're dealing with.
When you run yum install python2-urllib3:

python2-urllib3 is not an actual package name, it is a capability
python-urllib3 is the actual package name

So while you can pass a package capability to yum, for the rpm you need to pass a package name. That is why it rightfully tells you that there is no such package installed as python2-urllib3.
If you pass the real package name to it, as in python-urllib3, you will get the expected results.
Answer: try
rpm -q python-urllib3

as shown in your post.
in  the  image you ran
rpm -qi python2-urllib3

note the '2' in  python2
presumably copied from the yum command in which you ran
yum install python2-urllib3

actual installed rpm release is

python-urllib3-1.10.2-7.el7.noarch

hint
try  running
yum list installed|grep urllib3|xargs rpm -q

Comment: thanks, but I really mean python2-urllib3 , and I don't know why yum shows me python-urllib3 is installed, I want python2-urllib3 not python-urllib3 .
Comment: can you describe  the problem you are facing in which led you to trying to get 'python2-urllib3'? If you have python 2.7 on your system you should already have the requisite urllib  as well.
Comment: what is the output of `python -c "import  urllib3"`If  you don't get an error you should be good to go.
Comment: "I want python2-urllib3 not python-urllib3" - they are the same thing. The `python2-urllib3` is merely an alias to  `python-urllib3`. See my answer.


Fields capabilities

Question: I am trying to enable a field in one of my content-types to be a sort of selection within a selection and I need some help doing so. Basically, I would like to have a field where the user selects from a more encompassing list (e.g., buildings) from which she is then presented with a more narrow list (perhaps room number, following the example). Is this possible to do with fields in Drupal? I understand that I could simply make two fields but I think it'd be much nicer to have this list within a list. Again, I'd appreciate any help.
Thanks!
Answer: If your list is coming from Taxonomy then you can use Hierarchical Select module.
Comment: Ah that makes sense, thank you! Is there any way to do the same without having the list come from Taxonomy?
Comment: where you are getting your list from?
Comment: It's not a large one so I was planning to simply input it manually into the allowed values body
Comment: I would suggest to use taxonomy only because you can reuse it and it integrates well with views and other modules.
Comment: If you dont like the fact that say the Taxonomies are viewable themselves on urls, install [Rabbit Hole](https://www.drupal.org/project/rabbit_hole) and hide the taxonomy entry menu paths.

Fields capabilities


CSS transition doesn't work from bottom to top

Question: i used below css for my sidebar and transition works since this sidebar opens from left to right
CSS
.sidebar{
    position: absolute;
    width: 300px;
    top: 0;
    bottom: 0;
    left: 0;
    background-color: #FFF;
    height: 100%;
    z-index: 101;
    left: -310px;
    -webkit-transition: all 500ms cubic-bezier(0.215, 0.610, 0.355, 1.000);
    -moz-transition: all 500ms cubic-bezier(0.215, 0.610, 0.355, 1.000);
    -o-transition: all 500ms cubic-bezier(0.215, 0.610, 0.355, 1.000);
    transition: all 500ms cubic-bezier(0.215, 0.610, 0.355, 1.000); /* easeOutCubic */
}

and here am trying to transition from bottom to top with the same css code but there is no transition effect for below code.
.sidebarr{
    position: fixed;
    font-size: 15px;
    width: 100%;
    background-color: #FFF;
    height: 70%;
    z-index: 101;
    bottom: -100%;
    transition: all 0.3s cubic-bezier(0.000, 0.000, 0.230, 1);
}

.sidebarr.opened{
top: 30%
}

Now how do i animate when div slides from bottom to top.
Comment: Surely the `.opened` property should be `bottom: 0` not `top: 30%`? I would suggest making a working example in a snippet so show the problem in action.
Comment: you should use animated.css. It is easy and nice to use
Comment: @DBS yes it works, i didn't notice this simple solution.
Answer: replace
.sidebarr.opened{
top: 30%
}

with
.sidebarr.opened{
    bottom: 0
    }


combination of functions are not working properly

Question: When i try to fetch the results using below function I'm getting only first string available under SH_CHGDESC which is FRTRV-1
string available for the SH_CHGDESC are: FRTRV-11;SFARV-13;SCRRV-12
want to fetch all available strings
If InStr ({pipe.SH_CHGDESC}, "1;") >0
then mid({pipe.SH_CHGDESC},1,InStr ({pipe.SH_CHGDESC}, "1;")-1)

Please suggest.
Comment: That isn't Oracle syntax. And it isn't clear what you are trying to do really, or what you want to happen. Do you have a single string with semicolon-delimited values that you want to split into multiple values?
Answer: I think you're just trying to split a delimited string into multiple values; with your string in a CTE:
with pipe (SH_CHGDESC) as (
  select 'FRTRV-11;SFARV-13;SCRRV-12' from dual
)
select regexp_substr(sh_chgdesc, '(.*?)(;|$)', 1, level, null, 1)
from pipe
connect by level < regexp_count(sh_chgdesc, '(.*?)(;|$)');

REGEXP_SUBSTR(SH_CHGDESC,'
--------------------------
FRTRV-11
SFARV-13
SCRRV-12

If you are getting the string from the table and working with multiple rows at once then it's a bit more complicated, but can be handled if there is a primary/unique key on the pipe table.


JSF list depending on selected value returning nullPointer

Question: In my jsf page, in a dialog, I have a list of EntityB which depends on selected EntityA in a datatable.
When I first load the page it's giving me nullPpointer exception because nothing is selected in the first place. Can anyone tell me how to prevent this?
EDIT: I added an actionlistener to the link who open the dialog
and getting this error:

Cannot convert DemandesDocsAdministratif type DemandesDocsAdministratif to class javax.faces.event.ActionEvent

JSF:

                    <f:setPropertyActionListener
                        target="#{gestionDemandesMB.SelectedEntityA}" value="#{demande}"
                        />

<form>
<datatable>
</datatable>

                                <f:selectItems value="#{gestionDemandesMB.listEntityB}"
                                    var="sign" itemLabel="#{sign.libRole}"
                                    itemValue="#{sign.idPoste}" />

</form>

Bean:
public List<EntityA> getListEntityB() {
    if ( selectedentityA != null ){
    return entityBService.ListByentityA(selectedEntityA)
            ; } else {
    return Collections.emptyList() ; }

Bean listener that I'm working with now:
public void fillSignataires(ActionEvent event)
    {
listB = entityBService.ListByentityA(selectedEntityA)

        signaRender = true ;
    }

this is the getter of entity B list, I'm looking for a way to either get an empty list or call only when I open dialog.
Comment: `

.... ` is ''bad' Please fix and create a [mcve]
Answer: You could use rendered="#{not empty bean.list}" to prevent the rendering of the selectOnMenu until you have the object filled.
Comment: i initialised it to false in post construct , and put booleanRender = true  in getter of that list entityB , the list now is not rendering in my dialog
Comment: The attribute actionListener should call a method like fillEntityB(ActionEvent event)
Try comparing with this example https://mkyong.com/jsf2/jsf-2-actionlistener-example/
Answer: You can also add a f:selectItem with a "Select" label and empty itemValue such as itemValue = " ". By the way, never have a null list, list shouldn't be null but it can be empty. It's the best practice. So you can initialize your listEntityB as an empty list at post construct of your bean.

                            <f:selectItem  itemLabel="Select" itemValue="" />
                                var="sign" itemLabel="#{sign.libRole}"
                            <f:selectItems value="#{gestionDemandesMB.listEntityB}"
                                var="sign" itemLabel="#{sign.libRole}"
                                itemValue="#{sign.idPoste}" />


question on Cauchy-Hadamard formula

Question: I know that the radius of convergence $R$ of a power series $\sum\limits_{k=0}^{\infty}a_kx^k$ is defined by $R:=\frac{1}{\limsup\limits_{k\to\infty}\sqrt[k]{|a_k|}}$ and it can be derived from the root test of infinite series.
However, I am wondering why we don't define the radius of convergence by $R:=\frac{1}{\limsup\limits_{k\to\infty}|a_k|}$?
If we assume that $a_k$ is bounded then for all $x$ with $|x|<\frac{1}{\limsup\limits_{k\to\infty}|a_k|}$ it follows that:
$
|a_kx|<\frac{|a_k|}{\limsup\limits_{k\to\infty}|a_k|}\leq 1$ such that $\sum\limits_{k=0}^{\infty}(|a_kx|)^k$ is a geomtric series. Further, $\sum\limits_{k=0}^{\infty}\sqrt[k]{|a_k|}(|a_kx|)^k$ converges and hence $\sum\limits_{k=0}^{\infty}a_kx^k$ converges as well.
Or is my reasoning flawed?
Comment: I don't like defining the radius of convergence by that formula. A more intuitive definition is to define $R=\sup\{|z|: \sum a_nz^n\,\text{converges}\}.$
Comment: @Nuraly It is indeed.
Comment: @zhw. I really like your definition. Is it equivalent to the original?
Answer: Simple counterexample: $a_k=2$ has radius of convergence $1$, not $1/2$.
A more extreme one: $a_k=2^k$ has radius of convergence $1/2$, not $0$.
The flaw in your reasoning is in the algebra: in order to make the connection to geometric series, you should write $\sum |a_k| |x|^k = \sum \left ( |a_k|^{1/k} |x| \right )^k$. Then if $x<\frac{1}{\limsup |a_k|^{1/k}}$ then $|a_k|^{1/k} |x|<1$ for all but finitely many $k$. On the other hand if $x>\frac{1}{\limsup |a_k|^{1/k}}$ then $|a_k|^{1/k} |x|>1$ for infinitely many $k$.

question on Cauchy-Hadamard formula


What is wrong with ESXi VMKernel Port in Active/Active configuration?

Question: I have the below, simplified configuration:

Essentially, I have an ESXi host with two physical network adapters. Each adapter plugs in to a different switch. Each switch is connected via a trunk port. A PC is connected to one of the switches. A vSwitch with a VMKernel port and VM ports is configured to use both physical NICs in an Active/Active configuration:

I have run esxtop and can see that the ESXi host has chosen the physical NIC connected to Switch 2 for the VMKernel port. From the PC, if I ping the management IP address of the ESXi host the pings are intermittent. They go up and down.
If I show the mac address-table on each switch, I see that Switch 2 always has the VMKernel's MAC address assigned to the switch port connected to the ESXi host. But, Switch 1 continually adds and removes the VMKernel's MAC address on it's respective physical port. Anytime Switch 1 has the VMKernel's MAC assigned to its physical port, the pings fail.
The reason for the failure is obvious. The reason why Switch 1 is routinely picking up the MAC address of the ESXi VMKernel port is the question. The ESXi host has chosen the interface connected to Switch 2 to be the active port. The interface connected to Switch 1 should be inactive. But, it would appear that it is possibly responding to ARP requests?
It's worth noting that none of the VMs on this host have this problem. They are all reachable and are present in only one MAC table at a time. This problem specifically affects the VMKernel port.
What about this configuration is wrong? I am looking for some type of documentation or explanation on top of a solution to this issue. I know that setting the VMKernel port to be Active/Standby mode will probably solve the issue. But, I can't find anything documented why this current configuration is a problem.
UPDATES:

I disabled CDP on the vSwitch thinking that it might be causing communication over the inactive NIC.
I overrode the vSwitch settings for the VMKernel port and set it to use explicit failover and Active/Standby. I also placed the standby NIC in the unused pool. None of it helped. What did solve the issue was changing the port order around. So, when the port connected to Switch 1 becomes active, I do not see the issue. The MAC address does not become active on Switch 2 at all. These are two significantly different NIC cards, and I'm wondering if this isn't some kind of driver issue.

Something has to be causing the VMKernel MAC address to be seen on Switch 1's port, but it comes and goes every several seconds.
Switch configs for STP and ports:
Switch 1
!
spanning-tree mode rapid-pvst
spanning-tree portfast edge default
spanning-tree extend system-id
!
interface Port-channel1
 switchport access vlan 11
 switchport trunk encapsulation dot1q
 switchport mode trunk
!
interface GigabitEthernet1/0/7
 switchport access vlan 11
 switchport mode access
!
interface GigabitEthernet1/0/23
 switchport access vlan 11
 switchport trunk encapsulation dot1q
 switchport mode trunk
 channel-group 1 mode desirable
!
interface GigabitEthernet1/0/24
 switchport access vlan 11
 switchport trunk encapsulation dot1q
 switchport mode trunk
 channel-group 1 mode desirable

Switch 2
!
spanning-tree mode rapid-pvst
spanning-tree portfast edge default
spanning-tree extend system-id
!
interface Port-channel1
 switchport access vlan 11
 switchport trunk encapsulation dot1q
 switchport mode trunk
!
interface GigabitEthernet1/0/3
 switchport access vlan 11
 switchport mode access
!
interface GigabitEthernet1/0/23
 switchport access vlan 11
 switchport trunk encapsulation dot1q
 switchport mode trunk
 channel-group 1 mode desirable
!
interface GigabitEthernet1/0/24
 switchport access vlan 11
 switchport trunk encapsulation dot1q
 switchport mode trunk
 channel-group 1 mode desirable

Answer: The management vmk in ESXI assumes the MAC address of the Nic in the first PCI slot during the initial set-up. This is how it has worked forever. This can break things only when the physical device also starts sending packets. This normally does not happen, physical Nics do not send traffic, they pass traffic along. This behavior also needs to be paid attention to if you decide to move physical Nics from one host to another, this brings down 2 host connections when the physical switch freaks out. My guess is that this Nic started reporting CDP/LLDP traffic and this is when your switch sees the MAC duplication.
The easiest solution is to rebuild the vmk through the command line. This will need to be done from a direct console access (DCUI) (KVM, ILO, IDRAC, etc...).
Here are the commands; (Adjust the IP's/subnet mask/portgroup name etc... to fit your needs.)
esxcli network ip interface remove --interface-name=vmk0
esxcli network vswitch standard portgroup add -p Management_Network -v vSwitch0
esxcli network ip interface add --interface-name=vmk0 --portgroup-name=Management_Network
esxcli network vswitch standard portgroup set -p Management_Network  --vlan-id 50
esxcli network ip interface ipv4 set --interface-name=vmk0 --ipv4=192.168.50.116 --netmask=255.255.255.0 --gateway=192.168.50.1 --type=static
esxcli network ip interface tag add -i vmk0 -t Management
This will rebuild the management vmk with a VMware MAC address to eliminate this issue. However, I would recommend that you reach out to the hardware vendor/manufacturer for the process of shutting the CDP/LLDP coming from the physical card. This will resolve this one ESXi host issue, but you will end up with it happening to others if you allow the card(s) to continue to perform this function.
If this was as big a problem as you had originally thought, VMware would not be a giant company, this is not very common...
Comment: You hit the nail on the head. The problem is a hardware level LLDP agent sending out LLDP packets with the same MAC address. Now I need to decide the best way to solve the problem. Your solution is perfectly reasonable, it's just i do not have easy physical access to the server. I can upgrade my iDrac license or use remote hands and eyes. But, if I do that I can also go in the BIOS and shut off the LLDP agent (apparently). What a pain. Thanks again.
Answer: I have run an extremely similar setup for many years without any issues.
How have you configured the switch ports? You shouldn't do anything special (no (M)LAG/LACP) since ESXi takes care of everything. It's fine to stack the switches, just don't aggregate the ports, configure any link-state mirroring or similar.
Switch2 should have the VMkernel port's MAC on the ESXi-facing port and switch1 on the switch2-facing port, permanently.
The MAC flapping back and forth might be caused by another issue like frequent STP topology changes (which aren't usually visible by the ESXi but might still). Check the switches' logs for any anomalies.

The reason why Switch 1 is routinely picking up the MAC address of the ESXi VMKernel port is the question.

Without any LAG that could only happen if the host actually sent frames with the VMK port's MAC to switch1. It won't normally do that unless the link to switch2 failed.

The interface connected to Switch 1 should be inactive.

For the VMK port, yes. There may be VM traffic attached to the same port group.

But, it would appear that it is possibly responding to ARP requests?

ARP or not, frames with the VMK port MAC do not originate from the other port without reason.
Comment: Thanks for the reply. The switches are standard access ports. Nothing special. I do see millions of BDPUs sent from Switch 1 to Switch 2. I'm not sure if that is related. It seems to me that Switch 1 is seeing traffic from the ESXi interface connected to it and adding the MAC to it's table temporarily. But, that adapter should be "inactive." I thought I was on to something by disabling CDP on the physical adapter, but it didn't make any difference. Nor has changing the VMKernel to Active/Standby mode. In other words, having anything on the vSwitch in Active/Active mode causes this issue.
Comment: *millions of BDPUs sent from Switch 1 to Switch 2* doesn't seem to be normal - BPDUs are normally only sent on designated ports (=towards root ports), every 2s. Also, the adapters isn't active when you're running active-active. vNICs are attached by virtual port number (roughly randomly) and stay there. If you want active-passive you need to move one port down to *Standby adapters*. No, CDP/LLDP doesn't make a difference, I'd leave it active. The issue facing up with Active/Standby *very much* indicates an issue with the switch configs.
Comment: Could you add the sanitzed configs (at least the parts relevant for the ports and STP) to you question? Do the switch logs show anything?
Comment: Hi. Thank you for your help on this. Your updates are spot on, and we are in agreement. Packets from the inactive card should not be seen on Switch 1, yet it is. I updated my original post. If I change the order of ports - i.e. I make the NIC on Switch 1 active, the problem goes away and switch 2 does not see traffic from the inactive NIC. If I swap them back, the problem reappears. These are two significantly different NICs. I'm wondering if this is some kind of driver issue. I appreciate the focus on the switches, but all things point to frames coming from the inactive NIC for some reason???
Comment: switch configs added. This is a fairly basic switch configuration. Nothing special. STP is only enabled because there is a connection to another stack of switches over 2 ethernet cables, and these two switches in the discussion are not stacked. Again, using `show mac address-table interface gi1/0/7` shows the VMKernel MAC address popping in and out. Where as on the other switch the MAC is stable, as expected.
Comment: Do you have a well defined root bridge? The other switches are also running RPVST+ or RSTP/MSTP? Port 23&23 as port-channel are the stacking link? And 7 and 4 are the host links?
Answer: The switch port config that you posted shows that you are using a port channel on the catalyst switches.
Just don't do that! With standalone ESXi hosts this is not supported. ESXi takes care of load balancing and failover on its own within software only. If you absolutely want to use external switch based port channels then this requires that you use vCenter and a distributed switch.
See https://kb.vmware.com/s/article/82609 and https://kb.vmware.com/s/article/1001938 for further details.
Comment: Thanks for the reply. The port channel is not configured on any ESXi connected ports. These are trunks between Cisco switches.


Definition of quotient space: equivalence classes vs affine subsets

Question: Suppose $V$ is a vector space over any field and $U$ its subspace. Consider two different definitions of the quotient space $V/U$:

$V/U = \{v + U \mid v \in V\}$, i.e. the set of all affine subsets of $V$ parallel to $U$. This definition is used in Axler's Linear Algebra Done Right 3rd edition section 3.E.
Define an equivalence relation $\sim$ on $V$: $v \sim v' \text{ iff } v - v' \in U$. Define $V/U$ to be the set of all equivalence classes generated by $\sim$. This definition is used in Hackbusch's Tensor Spaces and Numerical Tensor Calculus 3.1.3.

What advantages and disadvantages do these two definitions have compared to each other
Comment: They are not really different definitions. Note that $v+U=w+U$ happens if and only if $v-w\in U$. So the equivalence class of $v$ by the relation $\sim$ is exactly the set $v+U$. So the only difference is that in the first definition you just define the elements of $V/U$ directly (which gives a natural equivalence relation: $v\sim w$ iff $v+U=w+U$), in the second one you first define an equivalence relation. The only difference is what you define first: the equivalence relation or the equivalence classes.
Answer: They are the same.
Whenever $v'\sim v$, then $v'=v+v'-v\in v+U$. Conversely, if $v'\in v+U$, then $v'-v\in v-v+U=U$, hence $v'\sim v$.


How to substract datetime index by a series of numbers in Pandas?

Question: I have a DataFrame similar to the following, and I want to subtract the DateTimeIndex by numbers in the Day_Count column.
import pandas as pd

x = pd.DataFrame(np.arange(1,14), index = pd.date_range('2020-01-01', periods = 13, freq= 'D'), columns = ['Day_Count'])

                Day_Count
2020-01-01          1
2020-01-02          2
2020-01-03          3
2020-01-04          4
2020-01-05          5
2020-01-06          6
2020-01-07          7
2020-01-08          8
2020-01-09          9
2020-01-10         10
2020-01-11         11
2020-01-12         12
2020-01-13         13

So, the expected results should have the same DateTimeIndex of 2019-12-31 (e.g., 2020-01-01 minus one day, 2020-01-02 minus 2 days, and so on). I tried the following code but it does not work.
from dateutil.relativedelta import relativedelta
x.index = x.index - relativedelta(days = x.Day_Count)

Please help with this. Thank you in advance.
Answer: Try this code and see if it gives the expected result.
df.index = df.index - pd.to_timedelta(df['Day_Count'],unit='day')

Comment: It is fantastic!! Thank you very much for the help.


Computing the expectation for the coordinate wise minimum of a single multivariate normal draw

Question: Let $x = (x_1, \ldots, x_n) \sim \mathcal{N}(\mathbf{\mu, \Sigma})$ be a $n$-dimensional multivariate normal random variable.
Are there efficient techniques for computing $\mathbb{E}(\min_i x_i)$?
The best I'm coming up with right now is straight MC integration, or maybe HMC sampling of the minimum itself, but I'm looking for something very fast, even if approximate.
Comment: How large an n? Is the special case of all mean elements being equal of any interest to you - that makes things easier. What about exchangeable (all mean elements equal, all diagonal elements equal, common non-negative correlation between all elements)? If exchangeable, E(min order statistic) = $\sigma \sqrt{1-\rho} E(\text{min order statistic of n iid N(0,1)}) + \mu$. (use pre-computed values). Afonja "The Moments of the Maximum of Correlated Normal and t-Variates" https://www.jstor.org/stable/2985184?seq=1#page_scan_tab_contents may be good., but I've only seen the first page.
Comment: Roughly speaking $10 < n < 100$. No such luck with the variables, I need a fully general covariance matrix and a fully general mean vector.
Comment: The good news is that Afonja equation 3.1 has an explicit formula for E(max(general multivariate normal)), which should be easy to change to min by taking negative of the value for E(max()) using negative of $\mu$. The bad news is that it involves evaluation of standardized (i.e., N(0 vector, Identity matrix)) distribution function at arguments depending on (crunched down from) $\mu$ and $\Sigma$ in dimension as high as n-1. You can sign up for JSTOR for free and view the article on your bookshelf, which I recommend you do.
Comment: Variance reduction techniques might help. How about using min of n iid N(0,1) as a control variable? You can use precomputed value of E(min of n i.i.d N(0,1)) .  I have no idea how big the variance reduction might be - perhaps the amount of variance reduction depends on $\mu$ and $\Sigma$. Or maybe can use formula in my 1st comment for exchangeable r.v.s based on some kind of averaged $\sigma$ and $\rho$, it would make use of the same precomputed values of  E(min of n iid N(0,1)). There are probably a lot of variations you could try for control variable9s).
Comment: So if I follow Afonja, i still have to take an expectation over an orthant, correct? In which case we're back at doing HMC
Comment: I wrote " bad news is that it involves evaluation of standardized (i.e., N(0 vector, Identity matrix)) distribution function at arguments depending on (crunched down from) μ and Σ in dimension as high as n-1" so you get down to dimension n-1. That's why i gave the suggestion on control variables. Anyhow, how fast do you need to do the simulation - I think I did over 10 million replications per second for n = 100 in a very non-optimized set up. An approximate answer is good enough? Then give up a digit of accuracy in exchange for 100 time speedup. And this is all before any variance reduction.
Comment: I tried using min of n iid N(0,1) as a control variable.  Variance reduction ranges from 100% (i.e., perfect) when all mean elements are equal and covariance matrix  is a multiple of the Identity, to not very big when those conditions are far from being true. In terms of variance reduction, it is bad if the disparity in the mean vector is large relative to the covariance, If you had representative mean vectors and covariance matrices of interest, we could see what the actual variance reduction would be.  It's possible that using the exchangeable rv formula for control variable would do better.
Comment: If you had either a mean vector which is near mean vector of interest for several problems, or covariance matrix near covariance matrices for several problems, you could run a very large number of simulation replications once for the typical mean and covaarince to serve that "family" of problems.  Then use that as a control variable for the (nearby)  problems in that family. That could achieve good results if problems in the family aren't too far from what was run for the control variable. Good control variables intro in section 3 of http://www.columbia.edu/~mh2078/MCS04/MCS_var_red1.pdf
Comment: No such luck. My $\mu$ and $\Sigma$ can be all over the place.
Comment: Have you looked at the obvious thing of reducing the number of simulation replications to the maximum number you can do in the time available (time target) and determining whether the resulting accuracy is sufficient for your purpose?  Any variance reduction would then be "gravy', i.e., only make things better.
Comment: Yeah, my best bet right now is to take an empirical average over a fixed sample of vectors. Using the reparametrization trick, I can even make it differentiable wrt mu and Sigma, which is also desirable in my case.
Comment: Cab you write out in detail your approach?
Answer: This is not a full solution, but may help.
According to extreme value theory, the CDF for the coordinate-wise maximum is the joint CDF evaluated "isotropically", i.e.
$\Pr[\max_ix_i\leq X]=\Pr[x_1\leq X,\ldots,x_n\leq X]$.
Wikipedia gives a couple of references for numerically approximating a multivariate normal CDF:
Botev, Z. I. (2016). "The normal law under linear restrictions: simulation and estimation via minimax tilting". Journal of the Royal Statistical Society: Series B (Statistical Methodology). doi:10.1111/rssb.12162.
Genz, Alan (2009). Computation of Multivariate Normal and t Probabilities. Springer. ISBN 978-3-642-01689-9.
Comment: That's equivalent to integrating the mass of a multivariate normal across a given orthant, and afaik the best way to do that is https://arxiv.org/pdf/1208.4118.pdf

But that's slow, and I'll have to do it for all $X$ to compute my expectation !
Comment: OK. For approximation, I might look at computing sample PDFs for some cases of interest, and see how they look. For example, I could imagine the PDF might be reasonably approximated by using the i.i.d. extreme-value PDF, where you parameterize the dof's ("$n$") in terms of your covariance-matrix singular value spectrum.


Views contextual filter - related nodes as an offset from a node's creation date

Question: I have a related content view which displays similar nodes based on shared taxonomy terms. I want it to display related nodes that were published in a date range relative to the current node's creation/published date. E.g: for a node published in March, I want to filter similar nodes that were published between February and April.
Currently I am only able to create a contextual filter "Node: Published at year + month" which displays similar nodes that were published in the same year+month, but I am looking for something similar to the post date filter criteria with operator (image attached), but instead of offset from current time, have an offset from current node's creation date. Is that feasible with views contextual filter?
Comment: https://api.drupal.org/api/views/views.api.php/group/views_hooks/7, hook_views_pre_view, $args
Answer: I think in this case you can use panels for that
In views create a content pane

Then add contextual filter based on Created Date
and in "PANE SETTINGS" click on "Argument input" and use this Settings :

this will export the node's created date from it and pass it through arguments to views.
this will give you an Panel's pane , to add it to your view you can use Page manager module .
Comment: Thanks for your answer, but I don't see how this will enable me to use a date range filter relative to node's creation time, could you explain further? I use panels to display the view could that be of any help?


Can't remove document file from Media

Question: I've created a WebForm that allows a user to upload a document file.  The file stores to Media which I'm using for images.  I can delete the image files but I'll be dog-gone if I can figure out how to delete the document files.  I've deleted the WebForm submission but when deleting the file in Media, I get the 'in use and cannot be deleted' message. Does anyone know how to delete this type of file?  I'm in the Administrator account so privileges shouldn't be the issue.  Thanks!
Answer: You probably need to delete or remove the file from any nodes, or webform submissions that it references. There should be a usage tab on the actual media resource. I don't have a media site handy so I can't provide screenshots. Once that usage tab is empty, it should be possible to delete that file. Otherwise I'd check the recent log messages in admin/reports to see if there's a file permissions issue, like the only file owners can delete files.

Can't remove document file from Media


How to avoid repeated code in views in Django?

Question: I have several function based views in a django project, and I noticed that they have some repeated code, in fact, they all do the same thing:
def my_view(request):
   form = MyForm(request.POST or None)
   if requqest.POST:
      if form.is_valid():
         do_somethin()
         and_something_else()
         return redirect('another:page')
   return render(request, 'my/tempalate.html', {'form': form})

The only thing that is different is the url where the user is redirected to in case of a succcesful form validation, the template, and maybe the form in the future.
Is it a good idea to use something like this to avoid that repetition?:
def a_view(request, success_redirect_url, template):
    form = MyForm(request.POST or None)
    if request.POST:
        if form.is_valid():
           do_something()
           and_something_else()
           return redirect(success_redirect_url)
    return render(request, template, {'form': form})

and then reuse it in other views that have the repeated code? like:
def my_view1(request, url='another_page', template='my/template.html'):
    return a_view(request, url, template)

Comment: Typically class-based views are used for this. What you describe looks close to a `FormView`.
Comment: Yes, factoring out a reusable function is perfectly fine. As Willem says, there are also other ways to do this with class-based views.
Comment: Ok, but the form is already written, I have to use it. And I have to use function based views.
Answer: Typically such patterns are defined in class-based views where one can use inheritance to override only some parts of the code flow.
Class-based views
Your view for example looks quite similar to a FormView [Django-doc]. Indeed, we can define a view with:
# app_name/views.py

from django.urls import reverse_lazy
from django.views.generic import FormView

class MyView(FormView):
    template_name = 'my/template.html'
    success_url = reverse_lazy('another_page')
    form_class = MyForm

    def form_valid(self, form):
        do_somethin()
        and_something_else()
        return super().form_valid(form)
Here the class-based view has implemented a handler for a POST request that will first construct the form, then check if that form is valid, and if it is invalid rerender the template with the form that now contains the errors. It thus minimizes the amount of code that one has to write to handle a simple form.
Such views also explain clearly what they are doing. A CreateView for example explains by its name that it is used to create new objects, it will thus trigger the .save() method of the form it is operating on. A DeleteView on the other hand makes it clear that a POST request to that view will delete an object.
You can also override the attributes in the urls.py by specifying a value in the .as_view(…) [Django-doc] call:
# app_name/urls.py

from app_name.views import MyView
from django.urls import path

urlpatterns = [
    # ⋮,
    path('some/path/', MyView(template_name='other/template.html'), name='some-name'),
    # ⋮
]
A class-based function thus acts as a template method pattern
Decorators
Another way to do this is to work with decorators that implement small pieces of logic that run before/after a call to the function-based view, and can alter the request/response, or decide to raise an error instead of calling the view.
For example the @require_http_methods(…) decorator [Django-doc] [GitHub] is implemented to first check if the method is one of the listed ones. This is implemented as:

def require_http_methods(request_method_list):
    # ⋮
    def decorator(func):
        @wraps(func)
        def inner(request, *args, **kwargs):
            if request.method not in request_method_list:
                response = HttpResponseNotAllowed(request_method_list)
                log_response(
                    'Method Not Allowed (%s): %s', request.method, request.path,
                    response=response,
                    request=request,
                )
                return response
            return func(request, *args, **kwargs)
        return inner
    return decorator

here the decorator thus checks if the request.method is a member of the request_method_list. If that is not the case, it will return a HTTP 405 response, and specify that that method is not allowed.
While Django offers a lot of decorators, most decorators have a mixin counterpart for a class-based views, and some are implemented already in the View class. For example if the View does not contains a get method, then it will return a HTTP 405 response, so here the required_http_method is not needed as a mixin/decorator for a class-based view.
Skeleton functions
You can implement a view function and use parameters instead to pass values. Usually however this will not be as flexible as a class-based view: it is rather easy to pass some parameters, but it is less useful to specify behavior in a pattern: in that case you need to pass a reference to a function, but then the question arises what parameters should be passed to that.
For example if we want to make a function that renders the template, we can work with a view that looks like:
from django.shortcuts import render

def render_some_template(request, parameter, context_generator, template='our/template.html'):
    context = context_generator()
    return render(request, template, context)
but perhaps the context_generator function should be called together with the parameter? or perhaps know what template will be rendered. This is one of the reasons why altering code flow is usually done with a class-based view, and less with a function-based view.
While a function-based view can work with a skeleton function, it is usually less exendible than the class-based counterpart. Django's builtin apps (the ones defined in the django.contrib module) are moving mainly towards class-based views, since it is easier to extend these.
Comment: @DavidEmanuelSandoval: one can use both class-based views and function-based views. Usually class-based views are used to avoid repitition of a view: so one defines a class-based view that encapsulates the code flow, and then subclasses. Function-based views on the other hand are often used if the codeflow is "special", and thus does not fit into a certain "pattern".
Comment: @DavidEmanuelSandoval: well almost all views in Django's builtin apps are moving towards class-based views. The `login` view was marked as deprecated in Django-1.11 and has been removed in Django-2.1 if I recall correctly: https://docs.djangoproject.com/en/2.0/topics/auth/default/#django.contrib.auth.views.login
Comment: @DavidEmanuelSandoval: and in fact likely class-based views are more secure, since it will implement a lot of boilerplate logic that one then never has to write again.
Comment: @DavidEmanuelSandoval There is something to be said about establishing conventions within a team. At the same time, good teams allow some flexibility in their conventions as they discover new and better ways of doing things. I suggest discussing class-based views with your team and weighing the pros and cons of using them.
Comment: Thank you, but, the thing is that I'm am not allowed to use class based views.
Comment: @DavidEmanuelSandoval: you do not need to rewrite your `MyForm`, you can "inject" it the view with `form_class = MyForm`.
Comment: @DavidEmanuelSandoval Why can't you use class based views? Is this a homework assignment? Or are there other constraints that you haven't mentioned here?
Comment: @Code-Apprentice In my job (and it's my first IT job, I started a month ago), if the rest of the code use function based classes, then the new views should also use the same kind of views.
Answer: You can do a lot better if just give a name to any button wich lunch this function:
<button name='lukaku'>
<button name='ronaldo'>

then into the view check for the name
if form.get('lukaku'):
    do something
if form.get('ronaldo'):
    do other thing

and so on. this can be limitless


Como trabalhar com dados binários

Question: Tenho uma função em C que recebe dois bytes um com maior valor significativo (msb) e outro com menor (lsb) e depois os converte para decimal.
int get_pea(char *buffer)
{
    char lsb[8], msb[8], pea[16];
    unsigned int i;

    convertDecimalBinary((int) buffer[0], lsb, 8);
    convertDecimalBinary((int) buffer[1], msb, 8);

    for (i=0; i<8; i++) {
        pea[i] = msb[i];
    }

    for (i=0; i<8; i++) {
        pea[i+8] = lsb[i];
    }

    return convertBinaryDecimal(pea, 16);
}

Essa função esta bem burrinha com tantas conversões de tipo, sei que no C não há necessidade de fazer tanta coisa assim, mas não vi outra forma para:
buffer[0] = 0x84;
buffer[1] = 0x03;

Tendo esses dois bytes como eu converto para decimal o 0x03 0x84 ?
Comment: 0x03 é um número. Se você só precisa da representação decimal é só usar o `%d` da família de funções `printf`. O mesmo para 0x84. Estar em hexa, binário ou decimal é apenas forma de representação. O número em sua essência existe por si só, não necessita de mais nada. Se você quer juntar os dois bytes considerando que `buffer[0]` é o low-byte é que o `buffer[1]` é o high-byte de uma palavra de 16 bits little-endian, bastaria fazer o shift bitwise do high-byte em 8 casas e juntar com o low-byte: `(buffer[0] & 0xff) | ((buffer[1] & 0xff) >> 8)`
Comment: Só uma dúvida, por que `pea`? Alguma relação com ervilhas?
Answer: O comentário fornecido pelo Jefferson Quesado talvez seja mais eficiente, entretanto eu considero:
#include <stdint.h>

uint16_t binary2decimal(const char buffer[2])
{
    union {
        char bytes[2];
        uint16_t value;
    } endianess;
    endianess[0] = buffer[0]; /*msb*/
    endianess[1] = buffer[1]; /*lsb*/

    return endianess.value;
}

mais amigável para o leitor. Embora este código funcione em um x86 (little endian), este não funcionará em processadores big endian (como o ppc). Para mais detalhes, estude o funcionamento de unions em C.
Answer: void get_pea(char *buffer)
    {
        char lsb = buffer[0];
        char msb = buffer[1];
        int mb;

    // Modo1 (@Jefferson Quesado)
        mb = (msb << 8) | (lsb << 0);
        printf("mb 0x%x or %d\n", mb, mb);

    // Modo 2 (@MrParrot)
        union {
            char bytes[2];
            uint16_t value;
        } uniteste;

        uniteste.bytes[0] = lsb;
        uniteste.bytes[1] = msb;

        printf("=> 0x%x or %d\n", uniteste.value, uniteste.value);

    }

Esse exemplo poderia ficar mais otimizado usando os tipos de stdint.h, obrigado a todos.

Como trabalhar com dados binários


Como pular a linha no input do python?

Question: Olá eu estou fazendo um código aqui pra enviar emails, e eu queria que na hora dos inputs da mensagem quando eu apertasse o Enter ele pulassse a linha e não parasse o input, que ele só pare quando o usuário apertar o Enter duas vezes
message = MIMEText(str(input("Mensagem: ")))

Comment: Lembrando que o "input" já retorna uma string, então não é necessário fazer `str(input(...))`  - o patter `int( input(...) )` que se acha em muitos trechinhos de código, inclusive em respostas aqui, não é nenhuma sintaxe especial aplicável ao `input`  - é simplesmente a chamada da "função" `int` com o que quer que o `input` retorne - e se isso for uma string válida para conversão, devolve um número inteiro.
Answer: Por padrão, o Python não inclui ferramentas muito flexíveis para desenvolvimento de aplicações no terminal:
O "input" é praticamente a única opção - para quem estiver no Unix (Linux ou Mac OS), pode usar a biblioteca "curses" para desenvolver um app complexo no terminal (mas é bem mais trabalhoso do que "input") .
A boa notícia é que em geral as pessoas perguntam como pegar uma entrada sem apertar <enter> - nesse caso, tem-se que usar uma lib a parte como curses ou terminedia - Mas para mais de um enter, é só criar uma função que você controle, usando vários inputs. Infelizmente não dá para fazer a navegação com setas, se o usuário quiser editar uma linha para cima, por exemplo - mas dá para ele escrever uma mensagem multilinha bem tranquilo:

def multi_input(msg, help="(digite uma linha em branco para terminar)"):
    print(msg)
    print(help)
    resultado = []
    linha = None
    while linha != "":
        linha = input()
        resultado.append(linha)
    return "\n".join(resultado)

Como pular a linha no input do python?


How to extend a selection in the linux console editors nano and pico?

Question: How do I extend a selection in nano and pico with the keyboard, so I can move and copy blocks?
Sorry, this is a question I would normally find out by myself but I have searched a lot in different occasions now without success.
Answer: I got this from inside the help screen in nano by pressing ctrl-g:
Ctrl    F-Key   Esc Key
^^      (F15)   (M-A)   Mark text at the cursor position
M-^             (M-6)   Copy the current line and store it in the cutbuffer
^U      (F10)           Uncut from the cutbuffer into the current line

^ = ctrl
M = esc
So you position your cursor at the beginning of where you want to select and press esc-a or ctrl-shift-6 or F15 then move the cursor with the arrow keys to highlight the text. Once it is highlighted press esc-6 to copy the text. Lastly move to where you want to paste and press ctrl-u or F10. I just tested this in nano 2.0.6 on OS X but should work across the board.
Comment: When available, you can use the Alt key for Meta. So Alt-A toggles set-mark and release-mark
Comment: Works great, thank you! Can someone tell me the reason why "M" stands for escape?
Comment: Good question, I had to do some searching but found it here: http://en.wikipedia.org/wiki/Meta_key
Comment: Also, I tried alt but it didn't work on my console. Could be my emulation though, I have some custom settings because of the servers I connect to.


pfense needs to be rebooted to effect a change in existing NAT

Question: Using PFSense ver:2.0-RC1 (i386)
When changing an existing NAT rule in pfsense I find that the rule doesn't work when:
1. the rule existed but with a change to its port number or destination LAN ip or both
2. mapping was done using pfsense load balance but that is disabled to use NAT instead.
In both the above mentioned cases I always had to reboot the firewall. As if a bug in the system.
My current situation is as given below:
Rule that existed:
src-any:port1  --nat--> lan-ip1:port2
Rule modified to :
src-any:port1 --nat--> lan-ip1:port3
Rules were altered and loaded. I verified from the shell as well. it showed the changed nat settings. But connection fails. I did a reset state from web-gui, but that worked momentarily and later failed.
I have checked in LAN network and found the service working. It fails only from Internet with firewall in between.
Is there any shell/cli method by which I can get this working. Any freebsd/pfsense command that can help me here. For, I cannot restart the firewall until mid-night (allowed downtime).
Answer: Three possibilities.
One, you're expecting an already-established connection to change, which won't happen with any stateful firewall. You'll have to kill the state(s) matching that port forward first, Diag>States.
Two, you're running an old snapshot build. Upgrade to the latest stable release, regardless of whether the above fixes. There's a chance you got a snapshot that was in the middle of a set of changes and that snapshot didn't reload its ruleset correctly.
Three, you have a buggy package of some sort installed that's hosing up the filter reload process. Running /etc/rc.filter_configure_sync at the command line may spit out what's happening if that's actually the case. But check one first, and upgrade to 2.0.3 before doing anything here.
Comment: Note to op: Chris knows what he's talking about - [check out his profile](http://serverfault.com/users/19233/chris-buechler).
Comment: Thanks Chris. I had reset the states from Diagnosis>States. I posted question in vain almost after an hour after state-reset. I had checked pfctl -s nat and pfctl -s state |grep  to make sure that thing were fine.

I agree I do need to update to latest. It's a scary affair :)

About the issue, it resolved on its on. It took a little over 2 hours. All good for now!


Javascript regex to search string between {}

Question: I have below URL, I need to extract the word present between flower brackets "Control1_Value" & "Control2_Value". I am new to regex please help me in getting the regex solved.
   <http://localhost:85/Default.aspx?FormName=Default&StartTime=Now-1month&EndTime=Now&Action=Edit&ControlName=Control1&ControlValue={Control1_Value}& ControlName=Control2&ControlValue={Control2_Value}#/SampleApp>

Few options I tried but in vain, below is the regex I tried but could not get exactly what I needed.
This is the regex I tried: /\{(.*)|_|Value\}/
Output of the above regex returned:
{Control1_Value}& ControlName=Control2&ControlValue={Control2_Value}#/SampleApp

Answer: \{([^\}]*)\}

You can simply use this or
\{(.*?)\}

Answer: Try the regex
var regex = /[^{]+?(?=})/g;
'<http://localhost:85/Default.aspx?FormName=Default&StartTime=Now-1month&EndTime=Now&Action=Edit&ControlName=Control1&ControlValue={Control1_Value}& ControlName=Control2&ControlValue={Control2_Value}#/SampleApp>'.match(regex );

Demo: RegEx


How to avoid invalid identifier in oracle

Question: I need to create a view but I obtain this error "Invalid Identifier".  The problem is  that I try to access a colum name that doesn't exist but I need to have in my view (if the column not exist I need to put null). This is my code sql:
select .......
case
when
   when exists (select 1  from user_tab_columns where table_name = 'Student' and COLUMN_NAME = 'email') then nvl(SUBSTR(student.email, 0, 100),'') else ''
end as STUDENT_EMAIL,

This is throwed "invalid identifier". I need to create this view and create the field "email" and if exist the colum I must insert the correct otherwise I put in the field value null;
Comment: Why do you not know whether your table contains this column or not?
Comment: Dynamic SQL is your friend here
Comment: What I mean is, are you trying to create a single script that will work on two different customer databases, one of which does have this column and the other of which doesn't have it? I need to know whether you're really trying to work with two tables that have different definitions, or whether you're just trying to work with a table that might not have a value in a column, but the column is always there
Comment: I was hoping you wouldn't say that :)
Comment: @CaiusJard because I don't create table and I must return some result that they aren't in this this table. So I need to check if exist or not
Comment: Then just look at the table definition. You can only create a view on a table and columns that exist.
Comment: @CaiusJard i'm tring to create a single script that will work on two different customer databases ,one of which does have this column and the other of which doesn't have it
Comment: @CaiusJard I know It is ridiculus, but 4-5 field I need to check if column exists for now,
Answer: Use dynamic SQL and try to compile the view and if there are errors then use NULL instead:
Oracle Setup:
CREATE TABLE students ( id, name )
AS SELECT 1, 'Alice' FROM DUAL;

Create View:
DECLARE
  invalid_identifier EXCEPTION;
  PRAGMA EXCEPTION_INIT( invalid_identifier, -904);
BEGIN
  EXECUTE IMMEDIATE 'CREATE VIEW student_view AS SELECT id, name, SUBSTR( email, 1, 100 ) AS STUDENT_EMAIL FROM students';
EXCEPTION
  WHEN invalid_identifier THEN
    EXECUTE IMMEDIATE 'CREATE VIEW student_view AS SELECT id, name, CAST( null AS VARCHAR2(100) ) AS STUDENT_EMAIL FROM students';
END;
/

Results:
SELECT * FROM student_view;

ID | NAME  | STUDENT_EMAIL
-: | :---- | :------------
 1 | Alice | null

db<>fiddle here
Answer: There is a hacky -- but clever -- way of doing this without using dynamic SQL.
You can use the scoping rules for subqueries to assign an email column if it exists.  The challenge is that you need to provide a default and you need a primary key:
select . . .,  -- all columns from `s` *except* for email
       (select email  -- no qualification
        from students s2
        where s2.id = s.id
       ) as email
from student s cross join
     (select '' as email from dual
     ) e;

If email is in students, then select email chooses that value.  If email is not, then it is chosen from e.


permutations of lists python

Question:
Possible Duplicate:
How to generate all permutations of a list in Python

I want to find all the permutations of a the elements in a list.
but then with some conditions imposed.. umm..
Probably an example will help me explain better.
I have four lists
["1"],["0"],["a","b","c],["d","e","f"]

Now I want to have the permutations in following way:
 "10ad" ,"10bd","10cd","10ae", "10be"
 ,"10bf"..

and so on..
So basically every element (with every element)??
Now I know the very naive way to do this.
But what is the pythonic way to do this?
if there is any??
Any suggestions
Thanks
Comment: If the order matters, please explain the ordering you want better; I would have expected "10ce" to come after "10be".
Comment: @ScottHunter: the order doesnt matter actually :)
Answer: I think you want to use the itertools module, which is part of the standard Python distribution.
For example:
import itertools

a = ["1"]
b = ["0"]
c = ["a","b","c"]
d = ["d","e","f"]

for item in itertools.product(a, b, c, d):
    print(item)

Edit: To be clear, the itertools.product function provides all combinations for all items in the inputted lists, not permutations.  But based on OP's wording, I think this is what he/she actually wants.
Comment: Or alternatively, if you want a list of strings, you can just `''.join(item)`
Comment: Great answer. This returns tuples, so slight adjustment to exactly match the question would be something like:  `for item in itertools.product(a,b,c,d): print '%s%s%s'%item`

permutations of lists python


Determinant of a $4\times4$ matrice with one unknown?

Question: I have to calculate the determinant of this matrice. I want to use the rule of sarrus, but this does only work with a $3\times3$ matrice:
$$
A=
  \begin{bmatrix}
    1 & -2 & -6 & u \\
    -3 & 1 & 2 & -5 \\
    4 & 0 & -4 & 3 \\
    6 & 0 & 1 & 8 \\
  \end{bmatrix}
$$
$|A|=35$
Any idea how to solve this?
Answer: (1)  Expand the determinant with respect to the second column and you will end up with two $3\times3$ determinants.
Or first add two times the second row to the first and then do (1).
Then use the rule of Sarrus.
Answer: $$A=\begin{pmatrix}1 & -2 & -6 & u \\-3 & 1 & 2 & -5 \\4 & 0 & -4 & 3 \\6 & 0 & 1 & 8 \\\end{pmatrix}\stackrel{ 3R_1+R_2}{\stackrel{-4R_1+R_3}{\stackrel{-6R_1+R_4}\longrightarrow}}\begin{pmatrix}1 & -2 & \;\;-6 & \;\;\;u \\0 & -5 & -16 & \;\;\,3u-5 \\0 & \;\;\;8 & \;\;\;20 &-4u+ 3 \\0 & \;\,12 & \;\;\;37 & -6u+8 \\\end{pmatrix}$$
Now develop the above wrt the first column and you get a $\,3\times 3\,$ determinant. Compute now directly or repeat the above process.
Comment: what do you mean "develope by first colume"? Would you be so kind to explain that further?
Comment: By minors, @maximus. Read it here http://mathworld.wolfram.com/Determinant.html
Answer: You can write
$$\det{A} = 2 \left| \begin{array}{ccc}
-3 & 2 & -5 \\
4 & -4 & 3 \\
6 & 1 & 8 \end{array} \right| + 1 \left| \begin{array}{ccc}
1 & -6 & u \\
4 & -4 & 3 \\
6 & 1 & 8 \end{array} \right| $$
which you should easily be able to expand to get a simple linear equation for $u$, which comes out to a nice whole number.
Answer: Use  Leibniz formula or the Laplace expansion. For more an Laplace expansion see youtube video .


'linker command failed', 'GenerateDSYMFile errors', and 'Lipo error'

Question: I changed my project name recently and believe I may be having linking problems. I modified my Cocoapod files for Mixpanel yesterday and have been getting unclear error messages since.
I deleted the Mixpanel Cocoapod, so I could manually install Mixpanel with the git repository. I installed the git repo files in iOS project directory, but couldn't get Mixpanel working. I decided to revert back to using the Cocoapod.
Ever since I made that change, I have been getting 'linker command failed', 'GenerateDSYMFile errors', and 'Lipo error'. I have reverted my entire git repo back to before the problem existed, but I can't seem to shake the errors.
I deleted the derived data, snapshots, and restarted xcode. I have even tried to run the same repository of files on another computer. I am still having the issues.
For the curious, the repository is here: https://github.com/NewPublicArtFoundation/GraffitiFound
The current error I find is:
Ld /Users/lbogdono/Library/Developer/Xcode/DerivedData/GraffitiFound-axmdvgkvpehlnwgtxecternwbifq/Build/Products/Debug-iphonesimulator/Public\ Art.temp_caseinsensitive_renameTests.xctest/Public\ Art.temp_caseinsensitive_renameTests normal x86_64
    cd /Users/lbogdono/Spaceship/GraffitiFound
    export IPHONEOS_DEPLOYMENT_TARGET=7.12
    export PATH="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/X11/bin"
    /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -arch x86_64 -bundle -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator8.1.sdk -L/Users/lbogdono/Library/Developer/Xcode/DerivedData/GraffitiFound-axmdvgkvpehlnwgtxecternwbifq/Build/Products/Debug-iphonesimulator -F/Users/lbogdono/Library/Developer/Xcode/DerivedData/GraffitiFound-axmdvgkvpehlnwgtxecternwbifq/Build/Products/Debug-iphonesimulator -F/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator8.1.sdk/Developer/Library/Frameworks -F/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks -F/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator8.1.sdk/Developer/Library/Frameworks -filelist /Users/lbogdono/Library/Developer/Xcode/DerivedData/GraffitiFound-axmdvgkvpehlnwgtxecternwbifq/Build/Intermediates/Public\ Art.build/Debug-iphonesimulator/Public\ Art.Tests.build/Objects-normal/x86_64/Public\ Art.temp_caseinsensitive_renameTests.LinkFileList -Xlinker -rpath -Xlinker @executable_path/Frameworks -Xlinker -rpath -Xlinker @loader_path/Frameworks -bundle_loader /Users/lbogdono/Library/Developer/Xcode/DerivedData/GraffitiFound-axmdvgkvpehlnwgtxecternwbifq/Build/Products/Debug-iphonesimulator/GraffitiFound.app/GraffitiFound -Xlinker -objc_abi_version -Xlinker 2 -framework XCTest -fobjc-arc -fobjc-link-runtime -Xlinker -no_implicit_dylibs -mios-simulator-version-min=7.12 -Xlinker -dependency_info -Xlinker /Users/lbogdono/Library/Developer/Xcode/DerivedData/GraffitiFound-axmdvgkvpehlnwgtxecternwbifq/Build/Intermediates/Public\ Art.build/Debug-iphonesimulator/Public\ Art.Tests.build/Objects-normal/x86_64/Public\ Art.temp_caseinsensitive_renameTests_dependency_info.dat -o /Users/lbogdono/Library/Developer/Xcode/DerivedData/GraffitiFound-axmdvgkvpehlnwgtxecternwbifq/Build/Products/Debug-iphonesimulator/Public\ Art.temp_caseinsensitive_renameTests.xctest/Public\ Art.temp_caseinsensitive_renameTests

ld: file not found: /Users/lbogdono/Library/Developer/Xcode/DerivedData/GraffitiFound-axmdvgkvpehlnwgtxecternwbifq/Build/Products/Debug-iphonesimulator/GraffitiFound.app/GraffitiFound
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Answer: As the error message indicates, you are trying to link a file into your executable that is not present on disk.  Specifically, it is unable to find /Users/lbogdono/Library/Developer/Xcode/DerivedData/GraffitiFound-axmdvgkvpehlnwgtxecternwbifq/Build/Products/Debug-iphonesimulator/GraffitiFound.app/GraffitiFound  I suspect you are trying to link that into the executable on accident as it doesn't really make sense for it to be there.  You probably accidentally dragged "GraffitiFound.app" into the link phase of your target.


Having an issue passing by reference / value

Question: I've got this method that is passed an array of files. It then replaces any / with \\. Then I call a method and pass the array to it, which puts the argument into a new array, formats the itand returns the new array. Next, I call the same method again, pass it the same local array, format it differently, and out both arrays. Problem is, the second method call is retaining the format from the first method call.
    public void Verify(string[] svnFiles, out string[] local, out string[] build)
    {
        //replace / with double \\
        var transformed = TransformToFolders(svnFiles);

        build = GetFiles(_buildPath, transformed);
        local = GetFiles(_localPath, transformed);
    }

    private static string[] GetFiles(string path, params string[] files)
    {
        var moddedFiles = files;
        for (var i = 0; i < files.Count(); i++)
            moddedFiles[i] = string.Format(@"{0}\{1}", path, moddedFiles[i]);

        return moddedFiles;
    }

So when I call local = GetFiles(_localPath, transformed); transformed has the same values as moddedFiles. GetFiles used to manipulate its files parameter directly and I was getting the same behavior, so that's why I tried creating a new array, but moddedFiles seems to still just be a reference instead of an actual copy. Is there an easy way to make an actual copy of it so that way I'm not getting basically _localPath\_buildPath\moddedFile?
Comment: This is not related to your question but is a recommendation based on my personal experience. I have always got hurt in the eye when I used multiple out arguments. IMHO I consider that a bad pattern. Instead I create model classes with output values as properties and return that as the result of function.
Comment: Frankly I'm not a huge fan of it either, slowly working on refactoring this project I inherited. I will probably change it. I think it's ugly and hard to follow. Or at least, the full method is-- I had stripped it down to just the core essentials for this post.
Answer: It sounds like you want:
var moddedFiles = (string[]) files.Clone();

That will create a shallow copy of the array, which is largely equivalent to a deep copy when it comes to strings, as they're immutable.
However, a cleaner (IMO) alternative would be to use LINQ:
private static string[] GetFiles(string path, params string[] files)
{
    return files.Select(file => string.Format(@"{0}\{1}", path, file))
                .ToArray();
}

Or if you really want to keep your original rough approach, you don't need to clone the array really - just create a new array of the right size.
private static string[] GetFiles(string path, params string[] files)
{
    var moddedFiles = new string[files.Length];
    for (var i = 0; i < files.Length; i++)
    {
        moddedFiles[i] = string.Format(@"{0}\{1}", path, files[i]);
    }
    return moddedFiles;
}

Comment: Thanks, that did it. For some reason I didn't think I could cast it to a string array-- I just looking at Clone / MemberwiseClone. This worked, and I'll mark it in 10 minutes :)
Comment: @sab669: Have a look at my edit for a cleaner approach though :)


PhoneGAP, Cordova : Modifying Android project to load external URL

Question: I am trying my hands on Cordova and phonegap. From the tutorials available, I was able to create a cordova app from command-line, and add android platform to it via the below mentioned commands. I then imported the android project in Android studio. As phonegap takes html, css content, I modified index.html to load an external URL, but it didn't work. What am I doing wrong? How can I point the application to load external URL? There were many other suggestions as I saw, but none of them even have the data I do. Thank you.
Also, when I changed in config.xml the file from index.html to URL, it opened a chrome instance instead of opening it in the app.
Commands :
cordova create hello com.example.hello HelloWorld
cordova platform add android --save
cordova build

MainActivity.java :
public class MainActivity extends CordovaActivity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        // enable Cordova apps to be started in the background
        Bundle extras = getIntent().getExtras();
        if (extras != null && extras.getBoolean("cdvStartInBackground", false)) {
            moveTaskToBack(true);
        }

        // Set by <content src="index.html" /> in config.xml
        loadUrl(launchUrl);
    }
}

Added the below line in index.html, but that didn't work either :

config.xml :
// Trying to open google.com
  <content src="http://www.google.com" />
    <access origin="*" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <allow-intent href="tel:*" />
    <allow-intent href="sms:*" />
    <allow-intent href="mailto:*" />
    <allow-intent href="geo:*" />
    <allow-intent href="market:*" />
    <preference name="loglevel" value="DEBUG" />

How can I load an external URL in the app itself. Thank you.
Answer: What allow-intent tag does it to open the schemes/urls you put on the href property on a system app that can handle that scheme, so right now your <allow-intent href="http://*/*" /> is opening chrome with google url.
The tag you need isn't allow-intent, it's allow-navigation
Add
<allow-navigation href="http://www.google.com" /> to only allow navigation inside your app to google.com and the rest of urls open in chrome, or add <allow-navigation href="*" /> to allow navigation to any website inside your app