问:
SugarORM not working
So, I'm new to this and I'm trying to implement SugarORM to create a database because it's suppose to be easier.
I've followed every step of the tutorial and adapted it to what I want to do in my app but whenever I try to save something into the database, the app crashes and goes back to the previous activity.
Can anyone tell me what I'm doing wrong? I want to save 5 inputs into the database and be able to delete by inputing their name (which will also be stored in the database).

Here is the logcat:

```<code>09-25 15:00:29.909 18121-18121/com.example.cabr.teste E/SQLiteLog: (1)
09-25 15:00:29.911 18121-18121/com.example.cabr.teste E/AndroidRuntime: FATAL EXCEPTION: main
  Process: com.example.cabr.teste, PID: 18121
  android.database.sqlite.SQLiteException: no such table: SUGAR_ORM (Sqlite code 1): ,
  while compiling: INSERT OR REPLACE  INTO SUGAR_ORM(ID,SIMULT,POTENCIA,QUANTIDADE,EQUIPAMENTO,HORAS) VALUES (?,?,?,?,?,?),
  (OS error - 2:No such file or directory)
      at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
      at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:925)
      at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:536)
      at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:603)
      at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:63)
      at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
      at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1725)
      at com.orm.SugarRecord.save(SugarRecord.java:266)
      at com.orm.SugarRecord.save(SugarRecord.java:360)
      at com.example.cabr.teste.Main14Activity$16.onClick(Main14Activity.java:417)
      at android.view.View.performClick(View.java:5647)
      at android.view.View$PerformClick.run(View.java:22465)
      at android.os.Handler.handleCallback(Handler.java:761)
      at android.os.Handler.dispatchMessage(Handler.java:98)
      at android.os.Looper.loop(Looper.java:156)
      at android.app.ActivityThread.main(ActivityThread.java:6577)
      at java.lang.reflect.Method.invoke(Native Method)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:941)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:831)
09-25 15:00:29.919 512-893/? E/logserver: imonitor_add_dynamic_path, path:/data/system/dropbox/data_app_crash@1506348029917.txt
09-25 15:00:29.923 1374-11353/? E/ReportTools: This is not beta user build
09-25 15:00:30.082 1374-11624/? E/HsmCoreServiceImpl: onTransact in code is: 102
09-25 15:00:30.132 1374-11619/? E/Process: isHighLoadProcess: get cpu failed
09-25 15:00:30.736 18416-18447/com.example.cabr.teste E/OpenGLRenderer: allen debug liyu Key: 0
09-25 15:00:30.741 18416-18447/com.example.cabr.teste E/OpenGLRenderer: allen debug liyu Key: 34359738371
09-25 15:00:30.742 18416-18447/com.example.cabr.teste E/OpenGLRenderer: allen debug liyu Key: 240518168576
09-25 15:00:30.743 18416-18447/com.example.cabr.teste E/OpenGLRenderer: allen debug liyu Key: 68719476736
09-25 15:00:30.745 18416-18447/com.example.cabr.teste E/OpenGLRenderer: allen debug liyu Key: 1
</code>```

And my code:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main14);

    final TextView textView12 = (TextView) findViewById(R.id.textView12);

    final Button button1 = (Button) findViewById(R.id.button1);
    final Button button2 = (Button) findViewById(R.id.button2);

    final EditText editText1 = (EditText) findViewById(R.id.editText1);
    final EditText editText2 = (EditText) findViewById(R.id.editText2);
    final EditText editText3 = (EditText) findViewById(R.id.editText3);

    final Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);
    final Spinner spinner2 = (Spinner) findViewById(R.id.spinner2);

    final CheckBox checkBox1 = (CheckBox) findViewById(R.id.checkbox1);

    final ImageView imageView1 = (ImageView) findViewById(R.id.imageview1);
    ImageView imageView2 = (ImageView) findViewById(R.id.imageview2);
    ImageView imageView3 = (ImageView) findViewById(R.id.imageview3);
    ImageView imageView4 = (ImageView) findViewById(R.id.imageview4);
    ImageView imageView5 = (ImageView) findViewById(R.id.imageview5);
    ImageView imageView6 = (ImageView) findViewById(R.id.imageview6);
    ImageView imageView7 = (ImageView) findViewById(R.id.imageview7);
    ImageView imageView8 = (ImageView) findViewById(R.id.imageview8);
    ImageView imageView9 = (ImageView) findViewById(R.id.imageview9);
    ImageView imageView10 = (ImageView) findViewById(R.id.imageview10);
    ImageView imageView11 = (ImageView) findViewById(R.id.imageview11);
    ImageView imageView12 = (ImageView) findViewById(R.id.imageview12);
    ImageView imageView13 = (ImageView) findViewById(R.id.imageview13);
    ImageView imageView14 = (ImageView) findViewById(R.id.imageview14);
    ImageView imageView15 = (ImageView) findViewById(R.id.imageview15);
    ImageView imageView16 = (ImageView) findViewById(R.id.imageview16);

    final TableLayout tableLayout1 = (TableLayout) findViewById(R.id.tablelayout1);

    final ScrollView scrollView1 = (ScrollView) findViewById(R.id.scrollView);

    imageView2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onBackPressed();
        }
    });

    imageView3.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(getApplicationContext(), Main9Activity.class);
            startActivity(i);
        }
    });

    imageView4.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            imageView1.setImageResource(R.drawable.televisao2);
            textView12.setText(getString(R.string.televisor));
            tableLayout1.setVisibility(View.VISIBLE);
            imageView1.setVisibility(View.VISIBLE);
            textView12.setVisibility(View.VISIBLE);
            button1.setVisibility(View.VISIBLE);
            button2.setVisibility(View.GONE);
            scrollView1.fullScroll(ScrollView.FOCUS_UP);
            editText1.setText("");
            editText2.setText("");
            editText3.setText("");
        }
    });

    imageView5.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            imageView1.setImageResource(R.drawable.sistemasom2);
            textView12.setText(getString(R.string.sistemasom));
            tableLayout1.setVisibility(View.VISIBLE);
            imageView1.setVisibility(View.VISIBLE);
            textView12.setVisibility(View.VISIBLE);
            button1.setVisibility(View.VISIBLE);
            scrollView1.fullScroll(ScrollView.FOCUS_UP);
            editText1.setText("");
            editText2.setText("");
            editText3.setText("");
        }
    });

    imageView6.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            imageView1.setImageResource(R.drawable.leitordedvd2);
            textView12.setText(getString(R.string.leitordvd));
            tableLayout1.setVisibility(View.VISIBLE);
            imageView1.setVisibility(View.VISIBLE);
            textView12.setVisibility(View.VISIBLE);
            button1.setVisibility(View.VISIBLE);
            button2.setVisibility(View.GONE);
            scrollView1.fullScroll(ScrollView.FOCUS_UP);
            editText1.setText("");
            editText2.setText("");
            editText3.setText("");
        }
    });

    imageView7.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            imageView1.setImageResource(R.drawable.consoladejogos2);
            textView12.setText(getString(R.string.consolajogos));
            tableLayout1.setVisibility(View.VISIBLE);
            imageView1.setVisibility(View.VISIBLE);
            textView12.setVisibility(View.VISIBLE);
            button1.setVisibility(View.VISIBLE);
            button2.setVisibility(View.GONE);
            scrollView1.fullScroll(ScrollView.FOCUS_UP);
            editText1.setText("");
            editText2.setText("");
            editText3.setText("");
        }
    });

    imageView8.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            imageView1.setImageResource(R.drawable.aspirador2);
            textView12.setText(getString(R.string.aspirador));
            tableLayout1.setVisibility(View.VISIBLE);
            imageView1.setVisibility(View.VISIBLE);
            textView12.setVisibility(View.VISIBLE);
            button1.setVisibility(View.VISIBLE);
            button2.setVisibility(View.GONE);
            scrollView1.fullScroll(ScrollView.FOCUS_UP);
            editText1.setText("");
            editText2.setText("");
            editText3.setText("");
        }
    });

    imageView9.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            imageView1.setImageResource(R.drawable.arcondicionado2);
            textView12.setText(getString(R.string.arcondicionado));
            tableLayout1.setVisibility(View.VISIBLE);
            imageView1.setVisibility(View.VISIBLE);
            textView12.setVisibility(View.VISIBLE);
            button1.setVisibility(View.VISIBLE);
            scrollView1.fullScroll(ScrollView.FOCUS_UP);
            editText1.setText("");
            editText2.setText("");
            editText3.setText("");
        }
    });

    imageView10.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            imageView1.setImageResource(R.drawable.lampada2);
            textView12.setText(getString(R.string.lampadas));
            tableLayout1.setVisibility(View.VISIBLE);
            imageView1.setVisibility(View.VISIBLE);
            textView12.setVisibility(View.VISIBLE);
            button1.setVisibility(View.VISIBLE);
            button2.setVisibility(View.GONE);
            scrollView1.fullScroll(ScrollView.FOCUS_UP);
            editText1.setText("");
            editText2.setText("");
            editText3.setText("");
        }
    });

    imageView11.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            imageView1.setImageResource(R.drawable.computadorportatil2);
            textView12.setText(getString(R.string.computadorportatil));
            tableLayout1.setVisibility(View.VISIBLE);
            imageView1.setVisibility(View.VISIBLE);
            textView12.setVisibility(View.VISIBLE);
            button1.setVisibility(View.VISIBLE);
            button2.setVisibility(View.GONE);
            scrollView1.fullScroll(ScrollView.FOCUS_UP);
            editText1.setText("");
            editText2.setText("");
            editText3.setText("");
        }
    });

    imageView12.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            imageView1.setImageResource(R.drawable.aquecedoraoleo2);
            textView12.setText(getString(R.string.aquecedoreletr));
            tableLayout1.setVisibility(View.VISIBLE);
            imageView1.setVisibility(View.VISIBLE);
            textView12.setVisibility(View.VISIBLE);
            button1.setVisibility(View.VISIBLE);
            button2.setVisibility(View.GONE);
            scrollView1.fullScroll(ScrollView.FOCUS_UP);
            editText1.setText("");
            editText2.setText("");
            editText3.setText("");
        }
    });

    imageView13.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            imageView1.setImageResource(R.drawable.ventoinha2);
            textView12.setText(getString(R.string.ventoinha));
            tableLayout1.setVisibility(View.VISIBLE);
            imageView1.setVisibility(View.VISIBLE);
            textView12.setVisibility(View.VISIBLE);
            button1.setVisibility(View.VISIBLE);
            button2.setVisibility(View.GONE);
            scrollView1.fullScroll(ScrollView.FOCUS_UP);
            editText1.setText("");
            editText2.setText("");
            editText3.setText("");
        }
    });

    imageView14.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            imageView1.setImageResource(R.drawable.desumidificador2);
            textView12.setText(getString(R.string.desumificador));
            tableLayout1.setVisibility(View.VISIBLE);
            imageView1.setVisibility(View.VISIBLE);
            textView12.setVisibility(View.VISIBLE);
            button1.setVisibility(View.VISIBLE);
            button2.setVisibility(View.GONE);
            scrollView1.fullScroll(ScrollView.FOCUS_UP);
            editText1.setText("");
            editText2.setText("");
            editText3.setText("");
        }
    });

    imageView15.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            imageView1.setImageResource(R.drawable.ferroeletrico2);
            textView12.setText(getString(R.string.ferroeletrico));
            tableLayout1.setVisibility(View.VISIBLE);
            imageView1.setVisibility(View.VISIBLE);
            textView12.setVisibility(View.VISIBLE);
            button1.setVisibility(View.VISIBLE);
            button2.setVisibility(View.GONE);
            scrollView1.fullScroll(ScrollView.FOCUS_UP);
            editText1.setText("");
            editText2.setText("");
            editText3.setText("");
        }
    });

    imageView16.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Context context = getApplicationContext();
            CharSequence text = "Marque a caixa se utiliza este equipamento em simultâneo com outros equipamentos.";
            int duration = Toast.LENGTH_LONG;

            Toast toast = Toast.makeText(context, text, duration);
            toast.show();
        }
    });

    button1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String equipamento, tipohoras, periodo;
            Integer potencia, quantidade, simult;
            Double quanthoras;
            Double horas = 0.0;

            button2.setVisibility(View.VISIBLE);
            button1.setVisibility(View.GONE);

            equipamento = textView12.getText().toString();
            potencia = Integer.parseInt(editText1.getText().toString());
            quantidade = Integer.parseInt(editText2.getText().toString());
            quanthoras = Double.parseDouble(editText3.getText().toString());
            tipohoras = spinner1.getSelectedItem().toString();
            periodo = spinner2.getSelectedItem().toString();
            simult = 0;

            if (potencia==0){
                if (equipamento.equals("Televisor")){
                    potencia = 90;
                }
                if (equipamento.equals("Sistema de Som")){
                    potencia = 150;
                }
                if (equipamento.equals("Leitor de DVD")){
                    potencia = 195;
                }
                if (equipamento.equals("Consola de Jogos")){
                    potencia = 140;
                }
                if (equipamento.equals("Aspirador")){
                    potencia = 600;
                }
                if (equipamento.equals("Ar Condicionado")){
                    potencia = 1400;
                }
                if (equipamento.equals("Lâmpadas")){
                    potencia = 10;
                }
                if (equipamento.equals("Computador Portátil")){
                    potencia = 65;
                }
                if (equipamento.equals("Aquecedor Elétrico")){
                    potencia = 1500;
                }
                if (equipamento.equals("Ventoinha")){
                    potencia = 80;
                }
                if (equipamento.equals("Desumidificador")){
                    potencia = 150;
                }
                if (equipamento.equals("Ferro Elétrico")){
                    potencia = 1000;
                }
            }

            if (quanthoras==0){
                if (equipamento.equals("Televisor")){
                    horas = 5.0;
                }
                if (equipamento.equals("Sistema de Som")){
                    horas = 8.0;
                }
                if (equipamento.equals("Leitor de DVD")){
                    horas = 3.0;
                }
                if (equipamento.equals("Consola de Jogos")){
                    horas = 3.0;
                }
                if (equipamento.equals("Aspirador")){
                    horas = 1.04;
                }
                if (equipamento.equals("Ar Condicionado")){
                    horas = 8.0;
                }
                if (equipamento.equals("Lâmpadas")){
                    horas = 5.0;
                }
                if (equipamento.equals("Computador Portátil")){
                    horas = 8.0;
                }
                if (equipamento.equals("Aquecedor Elétrico")){
                    horas = 4.0;
                }
                if (equipamento.equals("Ventoinha")){
                    horas = 6.0;
                }
                if (equipamento.equals("Desumidificador")){
                    horas = 4.0;
                }
                if (equipamento.equals("Ferro Elétrico")){
                    horas = 1.0;
                }
            } else {
                if (periodo.equals("dia")){
                    if (tipohoras.equals("min")){
                        horas = quanthoras/60;
                    }
                    if (tipohoras.equals("h")){
                        horas = quanthoras;
                    }
                }

                if (periodo.equals("semana")){
                    if (tipohoras.equals("min")){
                        horas = (quanthoras/60)/7;
                    }
                    if (tipohoras.equals("h")){
                        horas = quanthoras/7;
                    }
                }

                if (periodo.equals("mês")){
                    if (tipohoras.equals("min")){
                        horas = (quanthoras/60)/30.42;
                    }
                    if (tipohoras.equals("h")){
                        horas = quanthoras/30.42;
                    }
                }
            }

            SugarORM sugarORM = new SugarORM(equipamento, potencia, quantidade, horas, simult);
            sugarORM.save();

            Toast.makeText(getBaseContext(),"O equipamento foi adicionado com sucesso.", Toast.LENGTH_LONG).show();

        }
    });

    button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            button2.setVisibility(View.GONE);
            tableLayout1.setVisibility(View.GONE);
            imageView1.setVisibility(View.GONE);
            textView12.setVisibility(View.GONE);

            String equipamento;
            equipamento = textView12.getText().toString();

            SugarORM sugarORM = SugarORM.findById(SugarORM.class, 1);
            sugarORM.delete();

            Toast.makeText(getBaseContext(),"O equipamento foi removido com sucesso.", Toast.LENGTH_LONG).show();

        }
    });

}
</code>```

}

And the SugarORM class:

```<code>public class SugarORM extends SugarRecord {
String equipamento;
Integer potencia;
Integer quantidade;
Double horas;
Integer simult;

public SugarORM(){

}

public SugarORM(String equipamento, Integer potencia, Integer quantidade, Double horas, Integer simult){
    this.equipamento = equipamento;
    this.potencia = potencia;
    this.quantidade = quantidade;
    this.horas = horas;
    this.simult = simult;
}
</code>```

}

And the manifest:

```<code><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.NoActionBar"
    android:name="com.orm.SugarApp">
    <meta-data
        android:name="DATABASE"
        android:value="notes.db" />
    <meta-data
        android:name="VERSION"
        android:value="1" />
    <meta-data
        android:name="QUERY_LOG"
        android:value="true" />
    <meta-data
        android:name="DOMAIN_PACKAGE_NAME"
        android:value="com.example.cabr.teste" />
    <activity android:name=".Main10Activity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".Main2Activity" />
    <activity android:name=".Main3Activity" />
    <activity android:name=".Main4Activity" />
    <activity android:name=".Main5Activity" />
    <activity android:name=".Main6Activity" />
    <activity android:name=".Main7Activity" />
    <activity android:name=".Main8Activity" />
    <activity android:name=".MainActivity" />
    <activity android:name=".Main9Activity" />
    <activity android:name=".Main11Activity" />
    <activity android:name=".Main12Activity" />
    <activity android:name=".Main13Activity" />
    <activity android:name=".Main14Activity" />
    <activity android:name=".Main15Activity" />
    <activity android:name=".Main16Activity" />
    <activity android:name=".Main17Activity" />
    <activity android:name=".Main18Activity" />
    <activity android:name=".Main19Activity" />
    <activity android:name=".Main20Activity"></activity>
</application>
</code>```

答:
The problem is that you do not change the version of your database in the AndroidManifest.xml. Every time you change something in your code (SugarORM in this case) you need to update the version in your Manifest. Otherwise it wil not update your database and you will get this error.

The same goes for changing names of attributes, then the error will be: no such column.

```<code><meta-data  android:name="VERSION"  android:value="2" />
</code>```

Title: SugarORM not working

Body:
So, I'm new to this and I'm trying to implement SugarORM to create a database because it's suppose to be easier.
I've followed every step of the tutorial and adapted it to what I want to do in my app but whenever I try to save something into the database, the app crashes and goes back to the previous activity.
Can anyone tell me what I'm doing wrong? I want to save 5 inputs into the database and be able to delete by inputing their name (which will also be stored in the database).

Here is the logcat:

09-25 15:00:29.909 18121-18121/com.example.cabr.teste E/SQLiteLog: (1)
09-25 15:00:29.911 18121-18121/com.example.cabr.teste E/AndroidRuntime: FATAL EXCEPTION: main
  Process: com.example.cabr.teste, PID: 18121
  android.database.sqlite.SQLiteException: no such table: SUGAR_ORM (Sqlite code 1): ,
  while compiling: INSERT OR REPLACE  INTO SUGAR_ORM(ID,SIMULT,POTENCIA,QUANTIDADE,EQUIPAMENTO,HORAS) VALUES (?,?,?,?,?,?),
  (OS error - 2:No such file or directory)
      at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
      at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:925)
      at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:536)
      at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:603)
      at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:63)
      at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
      at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1725)
      at com.orm.SugarRecord.save(SugarRecord.java:266)
      at com.orm.SugarRecord.save(SugarRecord.java:360)
      at com.example.cabr.teste.Main14Activity$16.onClick(Main14Activity.java:417)
      at android.view.View.performClick(View.java:5647)
      at android.view.View$PerformClick.run(View.java:22465)
      at android.os.Handler.handleCallback(Handler.java:761)
      at android.os.Handler.dispatchMessage(Handler.java:98)
      at android.os.Looper.loop(Looper.java:156)
      at android.app.ActivityThread.main(ActivityThread.java:6577)
      at java.lang.reflect.Method.invoke(Native Method)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:941)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:831)
09-25 15:00:29.919 512-893/? E/logserver: imonitor_add_dynamic_path, path:/data/system/dropbox/data_app_crash@1506348029917.txt
09-25 15:00:29.923 1374-11353/? E/ReportTools: This is not beta user build
09-25 15:00:30.082 1374-11624/? E/HsmCoreServiceImpl: onTransact in code is: 102
09-25 15:00:30.132 1374-11619/? E/Process: isHighLoadProcess: get cpu failed
09-25 15:00:30.736 18416-18447/com.example.cabr.teste E/OpenGLRenderer: allen debug liyu Key: 0
09-25 15:00:30.741 18416-18447/com.example.cabr.teste E/OpenGLRenderer: allen debug liyu Key: 34359738371
09-25 15:00:30.742 18416-18447/com.example.cabr.teste E/OpenGLRenderer: allen debug liyu Key: 240518168576
09-25 15:00:30.743 18416-18447/com.example.cabr.teste E/OpenGLRenderer: allen debug liyu Key: 68719476736
09-25 15:00:30.745 18416-18447/com.example.cabr.teste E/OpenGLRenderer: allen debug liyu Key: 1

And my code:

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

    final TextView textView12 = (TextView) findViewById(R.id.textView12);

    final Button button1 = (Button) findViewById(R.id.button1);
    final Button button2 = (Button) findViewById(R.id.button2);

    final EditText editText1 = (EditText) findViewById(R.id.editText1);
    final EditText editText2 = (EditText) findViewById(R.id.editText2);
    final EditText editText3 = (EditText) findViewById(R.id.editText3);

    final Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);
    final Spinner spinner2 = (Spinner) findViewById(R.id.spinner2);

    final CheckBox checkBox1 = (CheckBox) findViewById(R.id.checkbox1);

    final ImageView imageView1 = (ImageView) findViewById(R.id.imageview1);
    ImageView imageView2 = (ImageView) findViewById(R.id.imageview2);
    ImageView imageView3 = (ImageView) findViewById(R.id.imageview3);
    ImageView imageView4 = (ImageView) findViewById(R.id.imageview4);
    ImageView imageView5 = (ImageView) findViewById(R.id.imageview5);
    ImageView imageView6 = (ImageView) findViewById(R.id.imageview6);
    ImageView imageView7 = (ImageView) findViewById(R.id.imageview7);
    ImageView imageView8 = (ImageView) findViewById(R.id.imageview8);
    ImageView imageView9 = (ImageView) findViewById(R.id.imageview9);
    ImageView imageView10 = (ImageView) findViewById(R.id.imageview10);
    ImageView imageView11 = (ImageView) findViewById(R.id.imageview11);
    ImageView imageView12 = (ImageView) findViewById(R.id.imageview12);
    ImageView imageView13 = (ImageView) findViewById(R.id.imageview13);
    ImageView imageView14 = (ImageView) findViewById(R.id.imageview14);
    ImageView imageView15 = (ImageView) findViewById(R.id.imageview15);
    ImageView imageView16 = (ImageView) findViewById(R.id.imageview16);

    final TableLayout tableLayout1 = (TableLayout) findViewById(R.id.tablelayout1);

    final ScrollView scrollView1 = (ScrollView) findViewById(R.id.scrollView);

    imageView2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onBackPressed();
        }
    });

    imageView3.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(getApplicationContext(), Main9Activity.class);
            startActivity(i);
        }
    });

    imageView4.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            imageView1.setImageResource(R.drawable.televisao2);
            textView12.setText(getString(R.string.televisor));
            tableLayout1.setVisibility(View.VISIBLE);
            imageView1.setVisibility(View.VISIBLE);
            textView12.setVisibility(View.VISIBLE);
            button1.setVisibility(View.VISIBLE);
            button2.setVisibility(View.GONE);
            scrollView1.fullScroll(ScrollView.FOCUS_UP);
            editText1.setText("");
            editText2.setText("");
            editText3.setText("");
        }
    });

    imageView5.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            imageView1.setImageResource(R.drawable.sistemasom2);
            textView12.setText(getString(R.string.sistemasom));
            tableLayout1.setVisibility(View.VISIBLE);
            imageView1.setVisibility(View.VISIBLE);
            textView12.setVisibility(View.VISIBLE);
            button1.setVisibility(View.VISIBLE);
            scrollView1.fullScroll(ScrollView.FOCUS_UP);
            editText1.setText("");
            editText2.setText("");
            editText3.setText("");
        }
    });

    imageView6.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            imageView1.setImageResource(R.drawable.leitordedvd2);
            textView12.setText(getString(R.string.leitordvd));
            tableLayout1.setVisibility(View.VISIBLE);
            imageView1.setVisibility(View.VISIBLE);
            textView12.setVisibility(View.VISIBLE);
            button1.setVisibility(View.VISIBLE);
            button2.setVisibility(View.GONE);
            scrollView1.fullScroll(ScrollView.FOCUS_UP);
            editText1.setText("");
            editText2.setText("");
            editText3.setText("");
        }
    });

    imageView7.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            imageView1.setImageResource(R.drawable.consoladejogos2);
            textView12.setText(getString(R.string.consolajogos));
            tableLayout1.setVisibility(View.VISIBLE);
            imageView1.setVisibility(View.VISIBLE);
            textView12.setVisibility(View.VISIBLE);
            button1.setVisibility(View.VISIBLE);
            button2.setVisibility(View.GONE);
            scrollView1.fullScroll(ScrollView.FOCUS_UP);
            editText1.setText("");
            editText2.setText("");
            editText3.setText("");
        }
    });

    imageView8.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            imageView1.setImageResource(R.drawable.aspirador2);
            textView12.setText(getString(R.string.aspirador));
            tableLayout1.setVisibility(View.VISIBLE);
            imageView1.setVisibility(View.VISIBLE);
            textView12.setVisibility(View.VISIBLE);
            button1.setVisibility(View.VISIBLE);
            button2.setVisibility(View.GONE);
            scrollView1.fullScroll(ScrollView.FOCUS_UP);
            editText1.setText("");
            editText2.setText("");
            editText3.setText("");
        }
    });

    imageView9.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            imageView1.setImageResource(R.drawable.arcondicionado2);
            textView12.setText(getString(R.string.arcondicionado));
            tableLayout1.setVisibility(View.VISIBLE);
            imageView1.setVisibility(View.VISIBLE);
            textView12.setVisibility(View.VISIBLE);
            button1.setVisibility(View.VISIBLE);
            scrollView1.fullScroll(ScrollView.FOCUS_UP);
            editText1.setText("");
            editText2.setText("");
            editText3.setText("");
        }
    });

    imageView10.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            imageView1.setImageResource(R.drawable.lampada2);
            textView12.setText(getString(R.string.lampadas));
            tableLayout1.setVisibility(View.VISIBLE);
            imageView1.setVisibility(View.VISIBLE);
            textView12.setVisibility(View.VISIBLE);
            button1.setVisibility(View.VISIBLE);
            button2.setVisibility(View.GONE);
            scrollView1.fullScroll(ScrollView.FOCUS_UP);
            editText1.setText("");
            editText2.setText("");
            editText3.setText("");
        }
    });

    imageView11.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            imageView1.setImageResource(R.drawable.computadorportatil2);
            textView12.setText(getString(R.string.computadorportatil));
            tableLayout1.setVisibility(View.VISIBLE);
            imageView1.setVisibility(View.VISIBLE);
            textView12.setVisibility(View.VISIBLE);
            button1.setVisibility(View.VISIBLE);
            button2.setVisibility(View.GONE);
            scrollView1.fullScroll(ScrollView.FOCUS_UP);
            editText1.setText("");
            editText2.setText("");
            editText3.setText("");
        }
    });

    imageView12.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            imageView1.setImageResource(R.drawable.aquecedoraoleo2);
            textView12.setText(getString(R.string.aquecedoreletr));
            tableLayout1.setVisibility(View.VISIBLE);
            imageView1.setVisibility(View.VISIBLE);
            textView12.setVisibility(View.VISIBLE);
            button1.setVisibility(View.VISIBLE);
            button2.setVisibility(View.GONE);
            scrollView1.fullScroll(ScrollView.FOCUS_UP);
            editText1.setText("");
            editText2.setText("");
            editText3.setText("");
        }
    });

    imageView13.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            imageView1.setImageResource(R.drawable.ventoinha2);
            textView12.setText(getString(R.string.ventoinha));
            tableLayout1.setVisibility(View.VISIBLE);
            imageView1.setVisibility(View.VISIBLE);
            textView12.setVisibility(View.VISIBLE);
            button1.setVisibility(View.VISIBLE);
            button2.setVisibility(View.GONE);
            scrollView1.fullScroll(ScrollView.FOCUS_UP);
            editText1.setText("");
            editText2.setText("");
            editText3.setText("");
        }
    });

    imageView14.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            imageView1.setImageResource(R.drawable.desumidificador2);
            textView12.setText(getString(R.string.desumificador));
            tableLayout1.setVisibility(View.VISIBLE);
            imageView1.setVisibility(View.VISIBLE);
            textView12.setVisibility(View.VISIBLE);
            button1.setVisibility(View.VISIBLE);
            button2.setVisibility(View.GONE);
            scrollView1.fullScroll(ScrollView.FOCUS_UP);
            editText1.setText("");
            editText2.setText("");
            editText3.setText("");
        }
    });

    imageView15.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            imageView1.setImageResource(R.drawable.ferroeletrico2);
            textView12.setText(getString(R.string.ferroeletrico));
            tableLayout1.setVisibility(View.VISIBLE);
            imageView1.setVisibility(View.VISIBLE);
            textView12.setVisibility(View.VISIBLE);
            button1.setVisibility(View.VISIBLE);
            button2.setVisibility(View.GONE);
            scrollView1.fullScroll(ScrollView.FOCUS_UP);
            editText1.setText("");
            editText2.setText("");
            editText3.setText("");
        }
    });

    imageView16.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Context context = getApplicationContext();
            CharSequence text = "Marque a caixa se utiliza este equipamento em simultâneo com outros equipamentos.";
            int duration = Toast.LENGTH_LONG;

            Toast toast = Toast.makeText(context, text, duration);
            toast.show();
        }
    });

    button1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String equipamento, tipohoras, periodo;
            Integer potencia, quantidade, simult;
            Double quanthoras;
            Double horas = 0.0;

            button2.setVisibility(View.VISIBLE);
            button1.setVisibility(View.GONE);

            equipamento = textView12.getText().toString();
            potencia = Integer.parseInt(editText1.getText().toString());
            quantidade = Integer.parseInt(editText2.getText().toString());
            quanthoras = Double.parseDouble(editText3.getText().toString());
            tipohoras = spinner1.getSelectedItem().toString();
            periodo = spinner2.getSelectedItem().toString();
            simult = 0;

            if (potencia==0){
                if (equipamento.equals("Televisor")){
                    potencia = 90;
                }
                if (equipamento.equals("Sistema de Som")){
                    potencia = 150;
                }
                if (equipamento.equals("Leitor de DVD")){
                    potencia = 195;
                }
                if (equipamento.equals("Consola de Jogos")){
                    potencia = 140;
                }
                if (equipamento.equals("Aspirador")){
                    potencia = 600;
                }
                if (equipamento.equals("Ar Condicionado")){
                    potencia = 1400;
                }
                if (equipamento.equals("Lâmpadas")){
                    potencia = 10;
                }
                if (equipamento.equals("Computador Portátil")){
                    potencia = 65;
                }
                if (equipamento.equals("Aquecedor Elétrico")){
                    potencia = 1500;
                }
                if (equipamento.equals("Ventoinha")){
                    potencia = 80;
                }
                if (equipamento.equals("Desumidificador")){
                    potencia = 150;
                }
                if (equipamento.equals("Ferro Elétrico")){
                    potencia = 1000;
                }
            }

            if (quanthoras==0){
                if (equipamento.equals("Televisor")){
                    horas = 5.0;
                }
                if (equipamento.equals("Sistema de Som")){
                    horas = 8.0;
                }
                if (equipamento.equals("Leitor de DVD")){
                    horas = 3.0;
                }
                if (equipamento.equals("Consola de Jogos")){
                    horas = 3.0;
                }
                if (equipamento.equals("Aspirador")){
                    horas = 1.04;
                }
                if (equipamento.equals("Ar Condicionado")){
                    horas = 8.0;
                }
                if (equipamento.equals("Lâmpadas")){
                    horas = 5.0;
                }
                if (equipamento.equals("Computador Portátil")){
                    horas = 8.0;
                }
                if (equipamento.equals("Aquecedor Elétrico")){
                    horas = 4.0;
                }
                if (equipamento.equals("Ventoinha")){
                    horas = 6.0;
                }
                if (equipamento.equals("Desumidificador")){
                    horas = 4.0;
                }
                if (equipamento.equals("Ferro Elétrico")){
                    horas = 1.0;
                }
            } else {
                if (periodo.equals("dia")){
                    if (tipohoras.equals("min")){
                        horas = quanthoras/60;
                    }
                    if (tipohoras.equals("h")){
                        horas = quanthoras;
                    }
                }

                if (periodo.equals("semana")){
                    if (tipohoras.equals("min")){
                        horas = (quanthoras/60)/7;
                    }
                    if (tipohoras.equals("h")){
                        horas = quanthoras/7;
                    }
                }

                if (periodo.equals("mês")){
                    if (tipohoras.equals("min")){
                        horas = (quanthoras/60)/30.42;
                    }
                    if (tipohoras.equals("h")){
                        horas = quanthoras/30.42;
                    }
                }
            }

            SugarORM sugarORM = new SugarORM(equipamento, potencia, quantidade, horas, simult);
            sugarORM.save();

            Toast.makeText(getBaseContext(),"O equipamento foi adicionado com sucesso.", Toast.LENGTH_LONG).show();

        }
    });

    button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            button2.setVisibility(View.GONE);
            tableLayout1.setVisibility(View.GONE);
            imageView1.setVisibility(View.GONE);
            textView12.setVisibility(View.GONE);

            String equipamento;
            equipamento = textView12.getText().toString();

            SugarORM sugarORM = SugarORM.findById(SugarORM.class, 1);
            sugarORM.delete();

            Toast.makeText(getBaseContext(),"O equipamento foi removido com sucesso.", Toast.LENGTH_LONG).show();

        }
    });

}

}

And the SugarORM class:

public class SugarORM extends SugarRecord {
String equipamento;
Integer potencia;
Integer quantidade;
Double horas;
Integer simult;

public SugarORM(){

}

public SugarORM(String equipamento, Integer potencia, Integer quantidade, Double horas, Integer simult){
    this.equipamento = equipamento;
    this.potencia = potencia;
    this.quantidade = quantidade;
    this.horas = horas;
    this.simult = simult;
}

}

And the manifest:

<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.NoActionBar"
    android:name="com.orm.SugarApp">
    <meta-data
        android:name="DATABASE"
        android:value="notes.db" />
    <meta-data
        android:name="VERSION"
        android:value="1" />
    <meta-data
        android:name="QUERY_LOG"
        android:value="true" />
    <meta-data
        android:name="DOMAIN_PACKAGE_NAME"
        android:value="com.example.cabr.teste" />
    <activity android:name=".Main10Activity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".Main2Activity" />
    <activity android:name=".Main3Activity" />
    <activity android:name=".Main4Activity" />
    <activity android:name=".Main5Activity" />
    <activity android:name=".Main6Activity" />
    <activity android:name=".Main7Activity" />
    <activity android:name=".Main8Activity" />
    <activity android:name=".MainActivity" />
    <activity android:name=".Main9Activity" />
    <activity android:name=".Main11Activity" />
    <activity android:name=".Main12Activity" />
    <activity android:name=".Main13Activity" />
    <activity android:name=".Main14Activity" />
    <activity android:name=".Main15Activity" />
    <activity android:name=".Main16Activity" />
    <activity android:name=".Main17Activity" />
    <activity android:name=".Main18Activity" />
    <activity android:name=".Main19Activity" />
    <activity android:name=".Main20Activity"></activity>
</application>

Body:
The problem is that you do not change the version of your database in the AndroidManifest.xml. Every time you change something in your code (SugarORM in this case) you need to update the version in your Manifest. Otherwise it wil not update your database and you will get this error.

The same goes for changing names of attributes, then the error will be: no such column.

<meta-data  android:name="VERSION"  android:value="2" />


来源: stackexchange

问:
Follower Table issue in user Database schema
[user Database model][1]

https://www.linkedin.com/feed/update/urn:li:activity:6345250684744630272

here is my database design for user I want to add user_ following table in this scenario can anyone help me to build user_follower table scheme?

答:
1- Each User has many other Users that followed him

2- Each User can follow many Users

So you have a many-to-many Unary relationship on User in your ER.

Now, to Mapping this data model to Tables:
 you can use a new table named: User_Followers and set 2 IDs of User as foreign key named source and target of following (and other attributes like date of follow and etc.)

you can find other mapping many-to-many Unary relationship (like Bit-Wise or Graph Data Models), but to your project, I offer as I mentioned.

ContentLicense: CC BY-SA 3.0


问:
How to Upload files in SAPUI5?
How to upload file in SAP Netweaver server using SAPUI5? I tried to upload file using FileUploader but did not get the luck if any one can help it will be very appreciated.

Thanks in Advance

答:
Nothing was added to the manifest nor the component nor index files. It is working for me, you just need to change the number of columns to whatever you want to fit your file.

UploadFile.view.xml

```<code><VBox>
    <sap.ui.unified:FileUploader id="idfileUploader" typeMissmatch="handleTypeMissmatch" change="handleValueChange" maximumFileSize="10" fileSizeExceed="handleFileSize" maximumFilenameLength="50" filenameLengthExceed="handleFileNameLength" multiple="false" width="50%" sameFilenameAllowed="false" buttonText="Browse" fileType="CSV" style="Emphasized" placeholder="Choose a CSV file"/>
    <Button text="Upload your file" press="onUpload" type="Emphasized"/>
</VBox>
</code>```

UploadFile.controller.js

```<code>sap.ui.define(["sap/ui/core/mvc/Controller", "sap/m/MessageToast", "sap/m/MessageBox", "sap/ui/core/routing/History"], function(
    Controller, MessageToast, MessageBox, History) {
  "use strict";

  return Controller.extend("cafeteria.controller.EmployeeFileUpload", {
    onNavBack: function() {
      var oHistory = History.getInstance();
      var sPreviousHash = oHistory.getPreviousHash();
      if (sPreviousHash !== undefined) {
        window.history.go(-1);
      } else {
        var oRouter = sap.ui.core.UIComponent.getRouterFor(this);
        oRouter.navTo("admin", true);
      }
    },
    handleTypeMissmatch: function(oEvent) {
      var aFileTypes = oEvent.getSource().getFileType();
      jQuery.each(aFileTypes, function(key, value) {
        aFileTypes[key] = "*." + value;
      });
      var sSupportedFileTypes = aFileTypes.join(", ");
      MessageToast.show("The file type *." + oEvent.getParameter("fileType") +
        " is not supported. Choose one of the following types: " +
        sSupportedFileTypes);
    },
    handleValueChange: function(oEvent) {
      MessageToast.show("Press 'Upload File' to upload file '" + oEvent.getParameter("newValue") + "'");
    },
    handleFileSize: function(oEvent) {
      MessageToast.show("The file size should not exceed 10 MB.");
    },
    handleFileNameLength: function(oEvent) {
      MessageToast.show("The file name should be less than that.");
    },
    onUpload: function(e) {
      var oResourceBundle = this.getView().getModel("i18n").getResourceBundle();
      var fU = this.getView().byId("idfileUploader");
      var domRef = fU.getFocusDomRef();
      var file = domRef.files[0];
      var reader = new FileReader();
      var params = "EmployeesJson=";
      reader.onload = function(oEvent) {
        var strCSV = oEvent.target.result;
        var arrCSV = strCSV.match(/[\w .]+(?=,?)/g);
        var noOfCols = 6;
        var headerRow = arrCSV.splice(0, noOfCols);
        var data = [];
        while (arrCSV.length > 0) {
          var obj = {};
          var row = arrCSV.splice(0, noOfCols);
          for (var i = 0; i < row.length; i++) {
            obj[headerRow[i]] = row[i].trim();
          }
          data.push(obj);
        }
        var Len = data.length;
        data.reverse();
        params += "[";
        for (var j = 0; j < Len; j++) {
          params += JSON.stringify(data.pop()) + ", ";
        }
        params = params.substring(0, params.length - 2);
        params += "]";
        // MessageBox.show(params);
        var http = new XMLHttpRequest();
        var url = oResourceBundle.getText("UploadEmployeesFile").toString();
        http.onreadystatechange = function() {
          if (http.readyState === 4 && http.status === 200) {
            var json = JSON.parse(http.responseText);
            var status = json.status.toString();
            switch (status) {
              case "Success":
                MessageToast.show("Data is uploaded succesfully.");
                break;
              default:
                MessageToast.show("Data was not uploaded.");
            }
          }
        };
        http.open("POST", url, true);
        http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        http.send(params);
      };
      reader.readAsBinaryString(file);
    }
  });
});
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to Upload files in SAPUI5?

Body:
Nothing was added to the manifest nor the component nor index files. It is working for me, you just need to change the number of columns to whatever you want to fit your file.

UploadFile.view.xml

<VBox>
    <sap.ui.unified:FileUploader id="idfileUploader" typeMissmatch="handleTypeMissmatch" change="handleValueChange" maximumFileSize="10" fileSizeExceed="handleFileSize" maximumFilenameLength="50" filenameLengthExceed="handleFileNameLength" multiple="false" width="50%" sameFilenameAllowed="false" buttonText="Browse" fileType="CSV" style="Emphasized" placeholder="Choose a CSV file"/>
    <Button text="Upload your file" press="onUpload" type="Emphasized"/>
</VBox>

UploadFile.controller.js

sap.ui.define(["sap/ui/core/mvc/Controller", "sap/m/MessageToast", "sap/m/MessageBox", "sap/ui/core/routing/History"], function(
    Controller, MessageToast, MessageBox, History) {
  "use strict";

  return Controller.extend("cafeteria.controller.EmployeeFileUpload", {
    onNavBack: function() {
      var oHistory = History.getInstance();
      var sPreviousHash = oHistory.getPreviousHash();
      if (sPreviousHash !== undefined) {
        window.history.go(-1);
      } else {
        var oRouter = sap.ui.core.UIComponent.getRouterFor(this);
        oRouter.navTo("admin", true);
      }
    },
    handleTypeMissmatch: function(oEvent) {
      var aFileTypes = oEvent.getSource().getFileType();
      jQuery.each(aFileTypes, function(key, value) {
        aFileTypes[key] = "*." + value;
      });
      var sSupportedFileTypes = aFileTypes.join(", ");
      MessageToast.show("The file type *." + oEvent.getParameter("fileType") +
        " is not supported. Choose one of the following types: " +
        sSupportedFileTypes);
    },
    handleValueChange: function(oEvent) {
      MessageToast.show("Press 'Upload File' to upload file '" + oEvent.getParameter("newValue") + "'");
    },
    handleFileSize: function(oEvent) {
      MessageToast.show("The file size should not exceed 10 MB.");
    },
    handleFileNameLength: function(oEvent) {
      MessageToast.show("The file name should be less than that.");
    },
    onUpload: function(e) {
      var oResourceBundle = this.getView().getModel("i18n").getResourceBundle();
      var fU = this.getView().byId("idfileUploader");
      var domRef = fU.getFocusDomRef();
      var file = domRef.files[0];
      var reader = new FileReader();
      var params = "EmployeesJson=";
      reader.onload = function(oEvent) {
        var strCSV = oEvent.target.result;
        var arrCSV = strCSV.match(/[\w .]+(?=,?)/g);
        var noOfCols = 6;
        var headerRow = arrCSV.splice(0, noOfCols);
        var data = [];
        while (arrCSV.length > 0) {
          var obj = {};
          var row = arrCSV.splice(0, noOfCols);
          for (var i = 0; i < row.length; i++) {
            obj[headerRow[i]] = row[i].trim();
          }
          data.push(obj);
        }
        var Len = data.length;
        data.reverse();
        params += "[";
        for (var j = 0; j < Len; j++) {
          params += JSON.stringify(data.pop()) + ", ";
        }
        params = params.substring(0, params.length - 2);
        params += "]";
        // MessageBox.show(params);
        var http = new XMLHttpRequest();
        var url = oResourceBundle.getText("UploadEmployeesFile").toString();
        http.onreadystatechange = function() {
          if (http.readyState === 4 && http.status === 200) {
            var json = JSON.parse(http.responseText);
            var status = json.status.toString();
            switch (status) {
              case "Success":
                MessageToast.show("Data is uploaded succesfully.");
                break;
              default:
                MessageToast.show("Data was not uploaded.");
            }
          }
        };
        http.open("POST", url, true);
        http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        http.send(params);
      };
      reader.readAsBinaryString(file);
    }
  });
});


问:
Setting instance variables in synchronized block in Objective C
I have a function that is synchronized, but it seems that I can't directly change the value of my instance variables in that block.

```<code>+(id)allocWithZone:(NSZone *)zone
{
@synchronized(self) {
    if (sharedInstance == nil) {
        sharedInstance = [super allocWithZone:zone];

        //This is not allowed
        something = @"hello";

        //This is allowed
        self.something = @"hello world!";

        return sharedInstance;
    }
}

return nil;
}
</code>```

Why is this the case? I have a variable that I need to access directly (and I don't want to synthesize that variable). How do I get around this?

答:
You can't change instance variables because this isn't an instance method. The value of self is, in fact, the class itself. Your line of code self.something = @"hello world!" won't work either. What you really want is sharedInstance.something = @"hello world!", and that will only work if something is a property. Even better would be to set up the ivars in the init method.

Oh, and you have no business setting ivars in +allocWithZone: anyway. The object has not been initialized yet.

Assuming you're trying to create a singleton here (as that's what it looks like), you may want to read this blog post on singletons in Obj-C.

ContentLicense: CC BY-SA 2.5

Body:
I have a function that is synchronized, but it seems that I can't directly change the value of my instance variables in that block.

+(id)allocWithZone:(NSZone *)zone
{
@synchronized(self) {
    if (sharedInstance == nil) {
        sharedInstance = [super allocWithZone:zone];

        //This is not allowed
        something = @"hello";

        //This is allowed
        self.something = @"hello world!";

        return sharedInstance;
    }
}

return nil;
}

Why is this the case? I have a variable that I need to access directly (and I don't want to synthesize that variable). How do I get around this?


问:
Assign CGPoint in UIPanGestureRecognizer from .began to .changed

Inside my view I have a cardContainerView with a UIPanGestureRecognizer attached to it. Depending on whether the user grabbed the card at the top or bottom half I want to add different rotation angles to my card, which works fine now.

My problem is that the way I implemented it, the user can grab the card at the top (which results in a positive rotation) and slide the card below the location.y threshold I am using, which then results in the card using a negative rotation angle. That causes a jarring jump of the card.

I tried grabbing the location.y in the .began part and assign it to the .changed but apparently I can't do that. It results in a nil value. Anyone have any idea how else I could solve this?

Much appreciated!

```<code>    //When animation begins
    if sender.state == UIGestureRecognizerState.began {
        print("PAN BEGAN")
        cardContainerViewInitialCenter = cardContainerView.center
        addNewTempCard()
        initialPoint = location
        print("InitialPoint PAN BEGAN \(initialPoint)")
        print("InitialPoint.y PAN BEGAN \(initialPoint.y)")
    }

    //While panning
    else if sender.state == UIGestureRecognizerState.changed {
        print("PAN CHANGED")

        //User grabbed card at top half
        if location.y < view.frame.height/2 {
            print("TOP HALF")

            if translation.x >= 0 && translation.x <= 50 {
                cardContainerView.center = CGPoint(x: cardContainerViewInitialCenter.x + translation.x, y: cardContainerViewInitialCenter.y)
                cardContainerView.transform = CGAffineTransform.init(rotationAngle: convertedRotationTopPos)
                tempCardView.alpha = convertedNewCardAlphaPos
                tempCardView.transform = view.transform.scaledBy(x: convertedNewCardScaleXPos, y: convertedNewCardScaleYPos)
            }

            else if translation.x > 50 {
                cardContainerView.center = CGPoint(x: cardContainerViewInitialCenter.x + translation.x, y: cardContainerViewInitialCenter.y)
                cardContainerView.transform = CGAffineTransform.init(rotationAngle: convertedRotationTopPos)
                tempCardView.alpha = convertedNewCardAlphaPos
                tempCardView.transform = view.transform.scaledBy(x: convertedNewCardScaleXPos, y: convertedNewCardScaleYPos)
            }

            else if translation.x < 0 && translation.x >= -50 {
                cardContainerView.center = CGPoint(x: cardContainerViewInitialCenter.x + translation.x, y: cardContainerViewInitialCenter.y)
                cardContainerView.transform = CGAffineTransform.init(rotationAngle: convertedRotationTopNeg)
                tempCardView.alpha = convertedNewCardAlphaNeg
                tempCardView.transform = view.transform.scaledBy(x: convertedNewCardScaleXNeg, y: convertedNewCardScaleYNeg)
            }

            else if translation.x < -50 {
                cardContainerView.center = CGPoint(x: cardContainerViewInitialCenter.x + translation.x, y: cardContainerViewInitialCenter.y)
                cardContainerView.transform = CGAffineTransform.init(rotationAngle: convertedRotationTopNeg)
                tempCardView.alpha = convertedNewCardAlphaNeg
                tempCardView.transform = view.transform.scaledBy(x: convertedNewCardScaleXNeg, y: convertedNewCardScaleYNeg)
            }
        }

        //User grabbed card at bottom half
        else if location.y > view.frame.height/2 {
            print("TOP HALF")

            if translation.x >= 0 && translation.x <= 50 {
                cardContainerView.center = CGPoint(x: cardContainerViewInitialCenter.x + translation.x, y: cardContainerViewInitialCenter.y)
                cardContainerView.transform = CGAffineTransform.init(rotationAngle: convertedRotationBottomPos)
                tempCardView.alpha = convertedNewCardAlphaPos
                tempCardView.transform = view.transform.scaledBy(x: convertedNewCardScaleXPos, y: convertedNewCardScaleYPos)
            }

            else if translation.x > 50 {
                cardContainerView.center = CGPoint(x: cardContainerViewInitialCenter.x + translation.x, y: cardContainerViewInitialCenter.y)
                cardContainerView.transform = CGAffineTransform.init(rotationAngle: convertedRotationBottomPos)
                tempCardView.alpha = convertedNewCardAlphaPos
                tempCardView.transform = view.transform.scaledBy(x: convertedNewCardScaleXPos, y: convertedNewCardScaleYPos)
            }

            else if translation.x < 0 && translation.x >= -50 {
                cardContainerView.center = CGPoint(x: cardContainerViewInitialCenter.x + translation.x, y: cardContainerViewInitialCenter.y)
                cardContainerView.transform = CGAffineTransform.init(rotationAngle: convertedRotationBottomNeg)
                tempCardView.alpha = convertedNewCardAlphaNeg
                tempCardView.transform = view.transform.scaledBy(x: convertedNewCardScaleXNeg, y: convertedNewCardScaleYNeg)
            }

            else if translation.x < -50 {
                cardContainerView.center = CGPoint(x: cardContainerViewInitialCenter.x + translation.x, y: cardContainerViewInitialCenter.y)
                cardContainerView.transform = CGAffineTransform.init(rotationAngle: convertedRotationBottomNeg)
                tempCardView.alpha = convertedNewCardAlphaNeg
                tempCardView.transform = view.transform.scaledBy(x: convertedNewCardScaleXNeg, y: convertedNewCardScaleYNeg)
            }
        }
    }
</code>```

答:
I think you should set your intialPoint in the .began state. It shouldn't be nil in .changed

```<code>//When animation begins
if sender.state == .began {
    ...
    initialPoint = sender.location(in: self)
}
</code>```

Also I don't think that else is really helping you. It shouldn't be .began else .changed, rather check if .began and if .changed.

Body:
Inside my view I have a cardContainerView with a UIPanGestureRecognizer attached to it. Depending on whether the user grabbed the card at the top or bottom half I want to add different rotation angles to my card, which works fine now.

My problem is that the way I implemented it, the user can grab the card at the top (which results in a positive rotation) and slide the card below the location.y threshold I am using, which then results in the card using a negative rotation angle. That causes a jarring jump of the card.

I tried grabbing the location.y in the .began part and assign it to the .changed but apparently I can't do that. It results in a nil value. Anyone have any idea how else I could solve this?

Much appreciated!

    //When animation begins
    if sender.state == UIGestureRecognizerState.began {
        print("PAN BEGAN")
        cardContainerViewInitialCenter = cardContainerView.center
        addNewTempCard()
        initialPoint = location
        print("InitialPoint PAN BEGAN \(initialPoint)")
        print("InitialPoint.y PAN BEGAN \(initialPoint.y)")
    }

    //While panning
    else if sender.state == UIGestureRecognizerState.changed {
        print("PAN CHANGED")

        //User grabbed card at top half
        if location.y < view.frame.height/2 {
            print("TOP HALF")

            if translation.x >= 0 && translation.x <= 50 {
                cardContainerView.center = CGPoint(x: cardContainerViewInitialCenter.x + translation.x, y: cardContainerViewInitialCenter.y)
                cardContainerView.transform = CGAffineTransform.init(rotationAngle: convertedRotationTopPos)
                tempCardView.alpha = convertedNewCardAlphaPos
                tempCardView.transform = view.transform.scaledBy(x: convertedNewCardScaleXPos, y: convertedNewCardScaleYPos)
            }

            else if translation.x > 50 {
                cardContainerView.center = CGPoint(x: cardContainerViewInitialCenter.x + translation.x, y: cardContainerViewInitialCenter.y)
                cardContainerView.transform = CGAffineTransform.init(rotationAngle: convertedRotationTopPos)
                tempCardView.alpha = convertedNewCardAlphaPos
                tempCardView.transform = view.transform.scaledBy(x: convertedNewCardScaleXPos, y: convertedNewCardScaleYPos)
            }

            else if translation.x < 0 && translation.x >= -50 {
                cardContainerView.center = CGPoint(x: cardContainerViewInitialCenter.x + translation.x, y: cardContainerViewInitialCenter.y)
                cardContainerView.transform = CGAffineTransform.init(rotationAngle: convertedRotationTopNeg)
                tempCardView.alpha = convertedNewCardAlphaNeg
                tempCardView.transform = view.transform.scaledBy(x: convertedNewCardScaleXNeg, y: convertedNewCardScaleYNeg)
            }

            else if translation.x < -50 {
                cardContainerView.center = CGPoint(x: cardContainerViewInitialCenter.x + translation.x, y: cardContainerViewInitialCenter.y)
                cardContainerView.transform = CGAffineTransform.init(rotationAngle: convertedRotationTopNeg)
                tempCardView.alpha = convertedNewCardAlphaNeg
                tempCardView.transform = view.transform.scaledBy(x: convertedNewCardScaleXNeg, y: convertedNewCardScaleYNeg)
            }
        }

        //User grabbed card at bottom half
        else if location.y > view.frame.height/2 {
            print("TOP HALF")

            if translation.x >= 0 && translation.x <= 50 {
                cardContainerView.center = CGPoint(x: cardContainerViewInitialCenter.x + translation.x, y: cardContainerViewInitialCenter.y)
                cardContainerView.transform = CGAffineTransform.init(rotationAngle: convertedRotationBottomPos)
                tempCardView.alpha = convertedNewCardAlphaPos
                tempCardView.transform = view.transform.scaledBy(x: convertedNewCardScaleXPos, y: convertedNewCardScaleYPos)
            }

            else if translation.x > 50 {
                cardContainerView.center = CGPoint(x: cardContainerViewInitialCenter.x + translation.x, y: cardContainerViewInitialCenter.y)
                cardContainerView.transform = CGAffineTransform.init(rotationAngle: convertedRotationBottomPos)
                tempCardView.alpha = convertedNewCardAlphaPos
                tempCardView.transform = view.transform.scaledBy(x: convertedNewCardScaleXPos, y: convertedNewCardScaleYPos)
            }

            else if translation.x < 0 && translation.x >= -50 {
                cardContainerView.center = CGPoint(x: cardContainerViewInitialCenter.x + translation.x, y: cardContainerViewInitialCenter.y)
                cardContainerView.transform = CGAffineTransform.init(rotationAngle: convertedRotationBottomNeg)
                tempCardView.alpha = convertedNewCardAlphaNeg
                tempCardView.transform = view.transform.scaledBy(x: convertedNewCardScaleXNeg, y: convertedNewCardScaleYNeg)
            }

            else if translation.x < -50 {
                cardContainerView.center = CGPoint(x: cardContainerViewInitialCenter.x + translation.x, y: cardContainerViewInitialCenter.y)
                cardContainerView.transform = CGAffineTransform.init(rotationAngle: convertedRotationBottomNeg)
                tempCardView.alpha = convertedNewCardAlphaNeg
                tempCardView.transform = view.transform.scaledBy(x: convertedNewCardScaleXNeg, y: convertedNewCardScaleYNeg)
            }
        }
    }

Body:
I think you should set your intialPoint in the .began state. It shouldn't be nil in .changed

//When animation begins
if sender.state == .began {
    ...
    initialPoint = sender.location(in: self)
}

Also I don't think that else is really helping you. It shouldn't be .began else .changed, rather check if .began and if .changed.


问:
How to add Nougat Permission in below Code?
This code runs on all version Below 7.0 version of android but doesn't runs on  Nougat. When I press the button, it does not go next activity? Please tell us how to add Nougat permission in below code?

```<code>currentlocation.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        currentlocation.startAnimation(animTranslate);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            if (ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.READ_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(Front.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_PERMISSON_SORAGE);

            }
        } else {
            if (interstitialAd.isLoaded()) {
                interstitialAd.show();
            }
            Intent iu = new Intent(Front.this, MainActivity.class);
            startActivity(iu);
        }
    }
});
</code>```

```<code>@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == REQUEST_PERMISSON_SORAGE
            && grantResults.length > 0
            && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        Intent i = new Intent(Front.this, MainActivity.class);
        startActivity(i);
        //finish();
    } else {
        Toast.makeText(this, "Please Allow permision to use App .", Toast.LENGTH_SHORT).show();
        finish();
    }
}
</code>```

Here is my manifest showing added permissions :

```<code><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
</code>```

答:
First off, the permission system starts at API 23 and above, so that code should be:

```<code>if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
</code>```

Secondly, there are more dangerous permissions you haven't requested:

```<code><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> ---> You did request this
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
</code>```

You only request READ_EXTERNAL_STORAGE. Request the rest as well. Add them into the String array like you did with READ_EXTERNAL_STORAGE

Body:
This code runs on all version Below 7.0 version of android but doesn't runs on  Nougat. When I press the button, it does not go next activity? Please tell us how to add Nougat permission in below code?

currentlocation.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        currentlocation.startAnimation(animTranslate);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            if (ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.READ_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(Front.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_PERMISSON_SORAGE);

            }
        } else {
            if (interstitialAd.isLoaded()) {
                interstitialAd.show();
            }
            Intent iu = new Intent(Front.this, MainActivity.class);
            startActivity(iu);
        }
    }
});

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == REQUEST_PERMISSON_SORAGE
            && grantResults.length > 0
            && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        Intent i = new Intent(Front.this, MainActivity.class);
        startActivity(i);
        //finish();
    } else {
        Toast.makeText(this, "Please Allow permision to use App .", Toast.LENGTH_SHORT).show();
        finish();
    }
}

Here is my manifest showing added permissions :

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

Body:
First off, the permission system starts at API 23 and above, so that code should be:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

Secondly, there are more dangerous permissions you haven't requested:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> ---> You did request this
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

You only request READ_EXTERNAL_STORAGE. Request the rest as well. Add them into the String array like you did with READ_EXTERNAL_STORAGE


问:
Grails database migration plugins
There are at least two Grails plugins that emulate the database migration functionality of Rails:

Autobase

Liquibase

Is there a consensus about which of these is best, or is there another plugin that does database migration better than either of the above?

答:
There is now a standard Grails database migration plugin available. According to this blog post at least the liquibase plugin will therefore not be maintained past the liquibase 1.9 release anymore.

The new database migration plugin has built-in functionality to execute changelogs on startup and supports the definition of changes in Groovy DSL, so it's probably what you are looking for.

Title: Grails database migration plugins


问:
add a row with button in td dynamically using javascript
I'm trying to add a row into a table with a button on the 3rd cell but it seems not to work</p>

```<code>Script:

   function addRow()
      {
        var table = document.getElementById("myTable"),
          newRow = table.insertRow(table.length),
          cell1 = newRow.insertCell(0),
          cell2 = newRow.insertCell(1),
          cell3 = newRow.insertCell(2),
          name = document.getElementById("form").value,
          amount = document.getElementById("amount").value;
          //this is where I assign a button
          delete1 = <input type='button' id='delete' value="delete">;

        cell1.innerHTML = name;
        cell2.innerHTML = amount;
        cell3.innerHTML = delete1;
      }
</code>```

答:
As mentioned in the comments, you need to make the variable delete a valid string:

```<code>delete1 = '<input type="button" id="delete" value="delete">';
</code>```

Body:
I'm trying to add a row into a table with a button on the 3rd cell but it seems not to work

Script:

   function addRow()
      {
        var table = document.getElementById("myTable"),
          newRow = table.insertRow(table.length),
          cell1 = newRow.insertCell(0),
          cell2 = newRow.insertCell(1),
          cell3 = newRow.insertCell(2),
          name = document.getElementById("form").value,
          amount = document.getElementById("amount").value;
          //this is where I assign a button
          delete1 = <input type='button' id='delete' value="delete">;

        cell1.innerHTML = name;
        cell2.innerHTML = amount;
        cell3.innerHTML = delete1;
      }

Body:
As mentioned in the comments, you need to make the variable delete a valid string:

delete1 = '<input type="button" id="delete" value="delete">';


问:
How can I parse two strings in a table row by using beautifulsoup?
```<code>html = '''
<div class="container">
 <h2>Countries & Capitals</h2>
  <table class="two-column td-red">
  <thead><tr><th>Country</th><th>Capital city</th></tr></thead><tbody>
   <tr class="grey"><td>Afghanistan</td><td>Kabul</td></tr>
   <tr><td>Albania</td><td>Tirana</td></tr>
</tbody>
</table>
</div>
</code>```

Given this HTML, I would like to specifically parse the country name and the capital city name and put them into a dictionary so that I can get

dict["Afghanistan] = 'Kabul'

I've started by doing

```<code>soup = BeautifulSoup(open(filename), 'lxml')
countries = {}
# YOUR CODE HERE
table = soup.find_all('table')
for each in table:
    if each.find('tr'):
        continue
    else:
        print(each.prettify())
return countries
</code>```

But it's confusing since it's the first time using it.

答:
The solution is for the given html example:

```<code>from bs4 import BeautifulSoup  # assuming you did pip install bs4
soup = BeautifulSoup(html, "html.parser")  # the html you mentioned
table_data = soup.find('table')
data = {}  # {'country': 'capital'} dict
for row in table_data.find_all('tr'):
    row_data = row.find_all('td')
    if row_data:
        data[row_data[0].text] = row_data[1].text
</code>```

I've skipped the try, except block for any erroneous case. I suggest to go through documentation of BeautifulSoup, it covers everything.

Body:
html = '''

Countries & Capitals

Country	Capital city

Afghanistan	Kabul

Albania	Tirana

Given this HTML, I would like to specifically parse the country name and the capital city name and put them into a dictionary so that I can get

dict["Afghanistan] = 'Kabul'

I've started by doing

soup = BeautifulSoup(open(filename), 'lxml')
countries = {}
# YOUR CODE HERE
table = soup.find_all('table')
for each in table:
    if each.find('tr'):
        continue
    else:
        print(each.prettify())
return countries

But it's confusing since it's the first time using it.

Body:
The solution is for the given html example:

from bs4 import BeautifulSoup  # assuming you did pip install bs4
soup = BeautifulSoup(html, "html.parser")  # the html you mentioned
table_data = soup.find('table')
data = {}  # {'country': 'capital'} dict
for row in table_data.find_all('tr'):
    row_data = row.find_all('td')
    if row_data:
        data[row_data[0].text] = row_data[1].text

I've skipped the try, except block for any erroneous case. I suggest to go through documentation of BeautifulSoup, it covers everything.


问:
Hide and show columns using jQuery
I'm trying to show and hide columns and my code isn't doing it's job.

Basically I want to be able to hide and show columns based on the class name.

My functions to hide and show the columns are not working.

```<code>$(document).ready(function () {
    appendHeader();
    select();
    var amountOfDayEnds = parseInt($('#amountOfDayEnds').val());
    appendBody(amountOfDayEnds);
});

$('#group').change(function () {
   select();
});

//Change Header based on the select
function select() {
    var group = $('#group').val();
    // Get the column API object
    console.log(group);
    switch (group) {
        case "DDA":
            hideColumn("mtg");
            hideColumn("sav");
            showColumn("dda");
            break;
        case "SAV":
            hideColumn("mtg");
            showColumn("sav");
            hideColumn("dda");
            break;
        case "MTG":
            showColumn("mtg");
            hideColumn("sav");
            hideColumn("dda");
            break;
    }
}

function hideColumn(className){

    var columnIndex = $("#dataTable thead tr th."+className).index();

    $("#dataTable thead tr th:eq("+columnIndex+")").hide();

    $("#dataTable tbody tr").each(function(){
        $(this).find("td:eq("+columnIndex+")").hide();
    });
}

function showColumn(className){

    var columnIndex = $("#dataTable thead tr th."+className).index();

    $("#dataTable thead tr th:eq("+columnIndex+")").show();

    $("#dataTable tbody tr").each(function(){
        $(this).find("td:eq("+columnIndex+")").show();
    });
}

//Append Header
function appendHeader() {
    var thead = '<thead>';
    thead += "<tr class='text-primary text-center'>";
    thead += '<th>Day</th>';
    thead += '<th class="dda">Type 400</th>';
    thead += '<th class="dda">Type 4044</th>';
    thead += '<th class="dda">Type 4045</th>';
    thead += '<th class="sav">Type 300</th>';
    thead += '<th class="sav">Type 310</th>';
    thead += '<th class="mtg">Type 700</th>';
    thead += '<th class="mtg">Type 710</th>';
    thead += '</tr>';
    thead += '</thead>';

    $('#dataTableHead').append(thead);
}
</code>```

EDIT: it seems like I'm hidding only one column of each type. I want to hide all columns with class name.

Can someone tell me what I'm missing here?

答:
It could be more simpler than that. You adding an element into the DOM by js so its better to cache it by $(document).find() so in this case you are always sure js will find it and never will get element doesn't exist error. You use a switch case that is not recommend in your situation (better if/else)

Note: there is some function that will manipulate/add some element to this table that you missed to add in your code for us so this code works fine with your current code. if its not work for td, because you didnt add them in your code and i dont know how is look like or what classes they have.

jsfiddle

Js/jQuery:

```<code>$(document).ready(function () {
    appendHeader();
    select();
    var amountOfDayEnds = parseInt($('#amountOfDayEnds').val());
    appendBody(amountOfDayEnds);
});

$('#group').change(function () {
   select();
});

//Change Header based on the select
function select() {
    var group = $('#group').val();
    // Get the column API object
    console.log(group);
    if(group == 'dda'){
            hideColumn("mtg");
            hideColumn("sav");
            showColumn("dda");
    } else if(group == 'sav'){
            hideColumn("mtg");
            showColumn("sav");
            hideColumn("dda");

    } else {
            showColumn("mtg");
            hideColumn("sav");
            hideColumn("dda");

    }
}

function hideColumn(className){
    $(document).find("#dataTableHead thead th."+className).hide();
}

function showColumn(className){
    $(document).find("#dataTableHead thead th."+className).show();

}

//Append Header
function appendHeader() {
    var thead = '<thead>';
    thead += "<tr class='text-primary text-center'>";
    thead += '<th>Day</th>';
    thead += '<th class="dda">Type 400</th>';
    thead += '<th class="dda">Type 4044</th>';
    thead += '<th class="dda">Type 4045</th>';
    thead += '<th class="sav">Type 300</th>';
    thead += '<th class="sav">Type 310</th>';
    thead += '<th class="mtg">Type 700</th>';
    thead += '<th class="mtg">Type 710</th>';
    thead += '</tr>';
    thead += '</thead>';

    $('#dataTableHead').append(thead);
}
</code>```

Title: Hide and show columns using jQuery

Body:
I'm trying to show and hide columns and my code isn't doing it's job.

Basically I want to be able to hide and show columns based on the class name.

My functions to hide and show the columns are not working.

$(document).ready(function () {
    appendHeader();
    select();
    var amountOfDayEnds = parseInt($('#amountOfDayEnds').val());
    appendBody(amountOfDayEnds);
});

$('#group').change(function () {
   select();
});

//Change Header based on the select
function select() {
    var group = $('#group').val();
    // Get the column API object
    console.log(group);
    switch (group) {
        case "DDA":
            hideColumn("mtg");
            hideColumn("sav");
            showColumn("dda");
            break;
        case "SAV":
            hideColumn("mtg");
            showColumn("sav");
            hideColumn("dda");
            break;
        case "MTG":
            showColumn("mtg");
            hideColumn("sav");
            hideColumn("dda");
            break;
    }
}

function hideColumn(className){

    var columnIndex = $("#dataTable thead tr th."+className).index();

    $("#dataTable thead tr th:eq("+columnIndex+")").hide();

    $("#dataTable tbody tr").each(function(){
        $(this).find("td:eq("+columnIndex+")").hide();
    });
}

function showColumn(className){

    var columnIndex = $("#dataTable thead tr th."+className).index();

    $("#dataTable thead tr th:eq("+columnIndex+")").show();

    $("#dataTable tbody tr").each(function(){
        $(this).find("td:eq("+columnIndex+")").show();
    });
}

//Append Header
function appendHeader() {
    var thead = '
';
    thead += "
";
    thead += 'Day	';
    thead += 'Type 400	';
    thead += 'Type 4044	';
    thead += 'Type 4045	';
    thead += 'Type 300	';
    thead += 'Type 310	';
    thead += 'Type 700	';
    thead += 'Type 710	';
    thead += '
';
    thead += '
';

    $('#dataTableHead').append(thead);
}

EDIT: it seems like I'm hidding only one column of each type. I want to hide all columns with class name.

Can someone tell me what I'm missing here?

Body:
It could be more simpler than that. You adding an element into the DOM by js so its better to cache it by $(document).find() so in this case you are always sure js will find it and never will get element doesn't exist error. You use a switch case that is not recommend in your situation (better if/else)

Note: there is some function that will manipulate/add some element to this table that you missed to add in your code for us so this code works fine with your current code. if its not work for td, because you didnt add them in your code and i dont know how is look like or what classes they have.

jsfiddle

Js/jQuery:

$(document).ready(function () {
    appendHeader();
    select();
    var amountOfDayEnds = parseInt($('#amountOfDayEnds').val());
    appendBody(amountOfDayEnds);
});

$('#group').change(function () {
   select();
});

//Change Header based on the select
function select() {
    var group = $('#group').val();
    // Get the column API object
    console.log(group);
    if(group == 'dda'){
            hideColumn("mtg");
            hideColumn("sav");
            showColumn("dda");
    } else if(group == 'sav'){
            hideColumn("mtg");
            showColumn("sav");
            hideColumn("dda");

    } else {
            showColumn("mtg");
            hideColumn("sav");
            hideColumn("dda");

    }
}

function hideColumn(className){
    $(document).find("#dataTableHead thead th."+className).hide();
}

function showColumn(className){
    $(document).find("#dataTableHead thead th."+className).show();

}

//Append Header
function appendHeader() {
    var thead = '<thead>';
    thead += "<tr class='text-primary text-center'>";
    thead += '<th>Day</th>';
    thead += '<th class="dda">Type 400</th>';
    thead += '<th class="dda">Type 4044</th>';
    thead += '<th class="dda">Type 4045</th>';
    thead += '<th class="sav">Type 300</th>';
    thead += '<th class="sav">Type 310</th>';
    thead += '<th class="mtg">Type 700</th>';
    thead += '<th class="mtg">Type 710</th>';
    thead += '</tr>';
    thead += '</thead>';

    $('#dataTableHead').append(thead);
}


问:
React: Are there respectable limits to number of props on react components
At times I have components with a large amounts of properties.

Is there any inherent problem with this?

e.g.

```<code>render() {

  const { create, update, categories, locations, sectors, workTypes, organisation } = this.props; // eslint-disable-line no-shadow

  return (
    <div className="job-container">
      <JobForm
        organisationId={organisation.id}
        userId={user.id}
        action={action}
        create={create}
        update={update}
        categories={categories}
        locations={locations}
        sectors={sectors}
        workTypes={workTypes}
      />
    </div>
  );
}
</code>```

What are the best practices?

答:
For years there have been style guides in many languages that suggest limits to the number of params to a function.  Even ESLint has a rule regarding this and states: "...can be difficult to read and write because it requires the memorization of what each parameter is, its type, and the order they should appear in.".

I think this is true in JSX too. And since, JSX is a DSL of JS, we're compiling code smells, kind of.

Body:
At times I have components with a large amounts of properties.

Is there any inherent problem with this?

e.g.

render() {

  const { create, update, categories, locations, sectors, workTypes, organisation } = this.props; // eslint-disable-line no-shadow

  return (

      <JobForm
        organisationId={organisation.id}
        userId={user.id}
        action={action}
        create={create}
        update={update}
        categories={categories}
        locations={locations}
        sectors={sectors}
        workTypes={workTypes}
      />

  );
}

What are the best practices?


问:
Counting zeros in a recursive manner
I am trying to count TRAILING zeros from a recursive manner. Basically I split the final recursive result and then created a var counter that will count all the zeros.

```<code>function countingZeros(n) {
  if (n < 0) {
    // Termination condition to prevent infinite recursion
    return;
  }
  // Base case
  if (n === 0) {
    return 1;
  }

  // Recursive case
  let final = n * countingZeros(n -1);

  let counter = 0;

  String(final).split('').forEach(function(item){
    item === 0 ? counter++ : counter;
  });

  return counter;
}

countingZeros(12) // => suppose to output 2 since there are 2 trailing zeros from 479001600 but got 0

countingZeros(6) // => suppose to get 1 since 720 is the final result.
</code>```

I am expecting to get 2 in return as the counter must return but instead I got 0. Any idea what am I missing on my function? How should I fix it?

答:
You are trying to count the number of zeroes using string functions(i will assume, you forgot to include the factorial method. Correct flow could have been- you first pass the input to a factorial method and pass output from factorial method to countingZeros method). Anyways as stated already in other answer, you don't really need to calculate the factorial product to count the trailing zeroes.

Here a sample to count the number of trailing zeroes in n!

```<code>        temp = 5;
        zeroes = 0;
        //counting the sum of multiples of 5,5^2,5^3....present in n!
        while(n>=temp){
            fives = n/temp;
            zeroes = zeroes + fives;
            temp = temp*5;
        }
        printf("%d",zeroes);
</code>```

Note that each multiple of 5 in the factorial product will contribute 1 to the number of trailing zeros. On top of this, each multiple of 25 will contribute an additional 1 to the number of trailing zeros. Then, each multiple of 125 will contribute another 1 to the number of trailing zeros, and so on.

Here's a great link to understand the concept behind this:
https://brilliant.org/wiki/trailing-number-of-zeros/

Title: Counting zeros in a recursive manner

Body:
I am trying to count TRAILING zeros from a recursive manner. Basically I split the final recursive result and then created a var counter that will count all the zeros.

function countingZeros(n) {
  if (n < 0) {
    // Termination condition to prevent infinite recursion
    return;
  }
  // Base case
  if (n === 0) {
    return 1;
  }

  // Recursive case
  let final = n * countingZeros(n -1);

  let counter = 0;

  String(final).split('').forEach(function(item){
    item === 0 ? counter++ : counter;
  });

  return counter;
}

countingZeros(12) // => suppose to output 2 since there are 2 trailing zeros from 479001600 but got 0

countingZeros(6) // => suppose to get 1 since 720 is the final result.

I am expecting to get 2 in return as the counter must return but instead I got 0. Any idea what am I missing on my function? How should I fix it?

Body:
You are trying to count the number of zeroes using string functions(i will assume, you forgot to include the factorial method. Correct flow could have been- you first pass the input to a factorial method and pass output from factorial method to countingZeros method). Anyways as stated already in other answer, you don't really need to calculate the factorial product to count the trailing zeroes.

Here a sample to count the number of trailing zeroes in n!

        temp = 5;
        zeroes = 0;
        //counting the sum of multiples of 5,5^2,5^3....present in n!
        while(n>=temp){
            fives = n/temp;
            zeroes = zeroes + fives;
            temp = temp*5;
        }
        printf("%d",zeroes);

Note that each multiple of 5 in the factorial product will contribute 1 to the number of trailing zeros. On top of this, each multiple of 25 will contribute an additional 1 to the number of trailing zeros. Then, each multiple of 125 will contribute another 1 to the number of trailing zeros, and so on.

Here's a great link to understand the concept behind this:
https://brilliant.org/wiki/trailing-number-of-zeros/