问:
I am making a login and sign up page for android but the sqlite database i use crashes on onCreate
```<code>package company.mystorage.com.mystorage;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper{

private static final String DATABASE_NAME = "mystorage.db";
private static final String TABLE_NAME = "userlist";

public static final String COLUMN_1 ="Id";
private static final String COLUMN_2 = "username";
private static final String COLUMN_3 = "password";
SQLiteDatabase db;

    public DatabaseHelper(Context context) {
        // database is created when constructor is called.
        super(context, DATABASE_NAME, null, 1);
        // to invoke onCreate() and onUpgrade() methods to create the tables
        SQLiteDatabase db = this.getWritableDatabase();

    }

    @Override
    public void onCreate(SQLiteDatabase db){
        db.execSQL("create table " + TABLE_NAME + "("
                + COLUMN_1 +" INTEGER PRIMARY KEY AUTOINCREMENT, "
                + COLUMN_2 +" TEXT, "
                + COLUMN_3 +" TEXT)"
        );

    }

    public boolean insertData(String username, String password){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COLUMN_2, username);
        contentValues.put(COLUMN_3, password);
        long result = db.insert(TABLE_NAME, null, contentValues);
        if (result == -1)
            return false;
        else
            return true;
    }

    public boolean searchPass(String user){
        db = this.getReadableDatabase();
        String query = "select * from  " + TABLE_NAME + " where " + COLUMN_2 + " = " + "'" + user + "'";
        Cursor cursor = db.rawQuery(query, null);

        cursor.moveToFirst();
        if (cursor.getCount() > 0) {

            return true;
        }
        cursor.close();
        db.close();

        return false;

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS "+ TABLE_NAME);
        onCreate(db);
    }

}
</code>```

This code will create a database and also contains the functions to search and add users to the database. I tried to debug the code and it showed that it crashed when the onCreate was called. I checked the onCreate but the query is being execute correctly.

Edited* I changed the this. for the db but it still crashed.

答:
This should help :

```<code> public void onCreate(SQLiteDatabase db) {
        db.execSQL(SQL_CREATE_ENTRIES);
    }
</code>```

Please remove "this".

Also, in your method SearchPass(), if cursor has more count than it wont close the cursor and db object. It would be a better idea to handle that in Finally block.

Body:
package company.mystorage.com.mystorage;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper{

private static final String DATABASE_NAME = "mystorage.db";
private static final String TABLE_NAME = "userlist";

public static final String COLUMN_1 ="Id";
private static final String COLUMN_2 = "username";
private static final String COLUMN_3 = "password";
SQLiteDatabase db;

    public DatabaseHelper(Context context) {
        // database is created when constructor is called.
        super(context, DATABASE_NAME, null, 1);
        // to invoke onCreate() and onUpgrade() methods to create the tables
        SQLiteDatabase db = this.getWritableDatabase();

    }

    @Override
    public void onCreate(SQLiteDatabase db){
        db.execSQL("create table " + TABLE_NAME + "("
                + COLUMN_1 +" INTEGER PRIMARY KEY AUTOINCREMENT, "
                + COLUMN_2 +" TEXT, "
                + COLUMN_3 +" TEXT)"
        );

    }

    public boolean insertData(String username, String password){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COLUMN_2, username);
        contentValues.put(COLUMN_3, password);
        long result = db.insert(TABLE_NAME, null, contentValues);
        if (result == -1)
            return false;
        else
            return true;
    }

    public boolean searchPass(String user){
        db = this.getReadableDatabase();
        String query = "select * from  " + TABLE_NAME + " where " + COLUMN_2 + " = " + "'" + user + "'";
        Cursor cursor = db.rawQuery(query, null);

        cursor.moveToFirst();
        if (cursor.getCount() > 0) {

            return true;
        }
        cursor.close();
        db.close();

        return false;

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS "+ TABLE_NAME);
        onCreate(db);
    }

}

This code will create a database and also contains the functions to search and add users to the database. I tried to debug the code and it showed that it crashed when the onCreate was called. I checked the onCreate but the query is being execute correctly.

Edited* I changed the this. for the db but it still crashed.

Body:
This should help :

 public void onCreate(SQLiteDatabase db) {
        db.execSQL(SQL_CREATE_ENTRIES);
    }

Please remove "this".

Also, in your method SearchPass(), if cursor has more count than it wont close the cursor and db object. It would be a better idea to handle that in Finally block.


来源: stackexchange

问:
How to downcast when it's necessary?
I am facing a downcast issue in my company software and I can't manage to find a workaround. (It's something put in place and I cannot change the whole conception)

I will try to give you the whole context with an example: Basically, we have 2 software components, let's say BrickHigh, BrickLow. BrickLow can use everything from BrickHigh but BrickHigh can't see Bricklow.

In BrickHigh there is an Animal class (dozens of attributes) with its DAO :

```<code>public class Animal .. {
 //attributes...
}
</code>```

In BrickLow I have created a Cat class (dozens of unmapped attributes aswell) which extends Animal.

```<code>public class Cat extends Animal {
//attributes
}
</code>```

What was intended to do is to have a super class(Animal) with every mapped attribute. But I cannot use my animal class in my application because it would be too many changes since the whole app uses Cat.

But obviously, I cannot cast my Animal to Cat after getting it from the DAO since Java doesn't allow it, and I need every information from Animal.

Since my BrickHigh doesn't see my BrickLow, there are no such things as Animal animal = new Cat(); possible.

My first idea was to create a constructor in Cat that would take an Animal as parameter

```<code>public Cat(Animal a) {
 super(a);
}
</code>```

But what my constructor must be in my Animal class? It doesn't seem to work.

答:
I'm not sure I understand fully your question, but if you want to create an instance of some animal class from within the code of BrickHigh, but without having any knowledge of BrickLow, you could either use a factory, or a Class object that would be identified by one or more attributes of the DAO.

For instance:

```<code>public interface AnimalFactory {
    boolean canInstanciate(AnimalDAO dao);
    Animal instanciate(AnimalDAO dao);
}
</code>```

Your BrickHigh would then have a set of factories, and would supply a mechanism to register new factories.

For instance:

```<code>public enum AnimalFactories implements AnimalFactory {
    INSTANCE;

    private List<AnimalFactory> factories = new ArrayList<>();

    public void registerFactory(AnimalFactory factory) {
        factories.add(factory);
    }

    @Override
    public boolean canInstanciate(AnimalDAO dao) {
        for (AnimalFactory fac: factories) {
            if (fac.canInstanciate(dao)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public Animal instanciate(AnimalDAO dao) {
        for (AnimalFactory fac: factories) {
            if (fac.canInstanciate(dao)) {
                return fac.instanciate(dao);
            }
        }
        throw new InstanciationException("No factory for that animal");
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to downcast when it's necessary?

Body:
I am facing a downcast issue in my company software and I can't manage to find a workaround. (It's something put in place and I cannot change the whole conception)

I will try to give you the whole context with an example: Basically, we have 2 software components, let's say BrickHigh, BrickLow. BrickLow can use everything from BrickHigh but BrickHigh can't see Bricklow.

In BrickHigh there is an Animal class (dozens of attributes) with its DAO :

public class Animal .. {
 //attributes...
}

In BrickLow I have created a Cat class (dozens of unmapped attributes aswell) which extends Animal.

public class Cat extends Animal {
//attributes
}

What was intended to do is to have a super class(Animal) with every mapped attribute. But I cannot use my animal class in my application because it would be too many changes since the whole app uses Cat.

But obviously, I cannot cast my Animal to Cat after getting it from the DAO since Java doesn't allow it, and I need every information from Animal.

Since my BrickHigh doesn't see my BrickLow, there are no such things as Animal animal = new Cat(); possible.

My first idea was to create a constructor in Cat that would take an Animal as parameter

public Cat(Animal a) {
 super(a);
}

But what my constructor must be in my Animal class? It doesn't seem to work.

Body:
I'm not sure I understand fully your question, but if you want to create an instance of some animal class from within the code of BrickHigh, but without having any knowledge of BrickLow, you could either use a factory, or a Class object that would be identified by one or more attributes of the DAO.

For instance:

public interface AnimalFactory {
    boolean canInstanciate(AnimalDAO dao);
    Animal instanciate(AnimalDAO dao);
}

Your BrickHigh would then have a set of factories, and would supply a mechanism to register new factories.

For instance:

public enum AnimalFactories implements AnimalFactory {
    INSTANCE;

    private List<AnimalFactory> factories = new ArrayList<>();

    public void registerFactory(AnimalFactory factory) {
        factories.add(factory);
    }

    @Override
    public boolean canInstanciate(AnimalDAO dao) {
        for (AnimalFactory fac: factories) {
            if (fac.canInstanciate(dao)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public Animal instanciate(AnimalDAO dao) {
        for (AnimalFactory fac: factories) {
            if (fac.canInstanciate(dao)) {
                return fac.instanciate(dao);
            }
        }
        throw new InstanciationException("No factory for that animal");
    }
}


问:
Connection String Form to an SQL server
i want to connect to database in an SQL server, so is the form of this connection string correct:</p>

```<code><connectionStrings>
  <add name="OnlineStoreEntities" connectionString="Data Source=SERVERNAME\SQLEXPRESS;Initial Catalog=MVCOnlineShop;Integrated Security=True" providerName="System.Data.SqlClient" />
  <add name="MVCOnlineShop" connectionString="metadata=res://*/Models.ShopModel.csdl|res://*/Models.ShopModel.ssdl|res://*/Models.ShopModel.msl;provider=System.Data.SqlClient;provider connection string="data source=AHMADZAKARIA-PC;initial catalog=MVCOnlineShop;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
</code>```

答:
change your names as below</p>

```<code><connectionStrings>
    <add name="MVCOnlineShop" connectionString="Data Source=SERVERNAME\SQLEXPRESS;Initial Catalog=MVCOnlineShop;Integrated Security=True" providerName="System.Data.SqlClient" />
  <add name="OnlineStoreEntities" connectionString="metadata=res://*/Models.ShopModel.csdl|res://*/Models.ShopModel.ssdl|res://*/Models.ShopModel.msl;provider=System.Data.SqlClient;provider connection string="data source=AHMADZAKARIA-PC;initial catalog=MVCOnlineShop;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
  </connectionStrings>
</code>```

Title: Connection String Form to an SQL server

Body:
i want to connect to database in an SQL server, so is the form of this connection string correct:

<connectionStrings>
  <add name="OnlineStoreEntities" connectionString="Data Source=SERVERNAME\SQLEXPRESS;Initial Catalog=MVCOnlineShop;Integrated Security=True" providerName="System.Data.SqlClient" />
  <add name="MVCOnlineShop" connectionString="metadata=res://*/Models.ShopModel.csdl|res://*/Models.ShopModel.ssdl|res://*/Models.ShopModel.msl;provider=System.Data.SqlClient;provider connection string="data source=AHMADZAKARIA-PC;initial catalog=MVCOnlineShop;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>

Body:
change your names as below

<connectionStrings>
    <add name="MVCOnlineShop" connectionString="Data Source=SERVERNAME\SQLEXPRESS;Initial Catalog=MVCOnlineShop;Integrated Security=True" providerName="System.Data.SqlClient" />
  <add name="OnlineStoreEntities" connectionString="metadata=res://*/Models.ShopModel.csdl|res://*/Models.ShopModel.ssdl|res://*/Models.ShopModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=AHMADZAKARIA-PC;initial catalog=MVCOnlineShop;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>


问:
How to save a sequence in an array?
I am trying to set the values of r (which is a sequence) in 1D array. So, I can use it further to construct a 2D array. Below written code is giving following error:

File "V_urc_3D.py", line 28, in
    r[j] = np.linspace(0.01,lim,500)
ValueError: setting an array element with a sequence.

Could anyone help to solve this problem.

from __future__ import division
import numpy as np
import math
import matplotlib.pylab as plt
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D

Mh = np.linspace(10**11, 10**13, 5)
Rv = 259.3*(Mh/10**12)**(1/3)

r = np.zeros(len(Rv))
for j in np.arange(len(Rv)):
 lim = Rv[j]
 r[j] = np.linspace(0.01,lim,500)```

答:
r = np.zeros(len(Rv)) creates a numpy array initialised with zeros, which are (by default) floating-point values.

In the line that the error traceback references, you are attempting to assign np.linspace(0.01, lim, 500) (which is an array of 500 floating-point values) to a memory location which only has space for a single floating-point value; hence the error.

For an immediate fix, add a dimension to the initialisation of r, specifically r = np.zeros(len(Rv), 500). If you are interested in more advanced syntax, list comprehension can give you a speed boost:

```<code>r = np.array([np.linspace(0.01,lim,500) for lim in Rv])
</code>```

Title: How to save a sequence in an array?

Body:
r = np.zeros(len(Rv)) creates a numpy array initialised with zeros, which are (by default) floating-point values.

In the line that the error traceback references, you are attempting to assign np.linspace(0.01, lim, 500) (which is an array of 500 floating-point values) to a memory location which only has space for a single floating-point value; hence the error.

For an immediate fix, add a dimension to the initialisation of r, specifically r = np.zeros(len(Rv), 500). If you are interested in more advanced syntax, list comprehension can give you a speed boost:

r = np.array([np.linspace(0.01,lim,500) for lim in Rv])


答: In your onCreate Method don't use this with db.execSQL(..)

Title: I am making a login and sign up page for android but the sqlite database i use crashes on onCreate


问:
Group By (Name) and Order By (Date) for two select query
I got a sort of large query which contains a inner select query. My objective is to group all the records by field call Product Number (which is not unique and appears multiple times) and then by the Date.

I added the Order By date at the end of the query and seems to work fine. The query generated all the records in order of the Date but the records are not grouped by the ProductNumber.

Here is a visual sample of the data

```<code>ProductId   Manufacturer        ProductNumber       Date
1           Kellog                H1            05/05/2017
5           Nestle                H1            05/01/2017
8           Nutmeg                H1            04/30/2017
9           Highland              H3            04/09/2017
10          Houston               H1            04/15/2017
11          Miami                 H3            04/12/2017
</code>```

I am trying to get the output to look like the following

```<code>ProductId   Manufacturer        ProductNumber       Date
1           Kellog                H1            05/05/2017
5           Nestle                H1            05/01/2017
8           Nutmeg                H1            04/30/2017
10          Houston               H1            04/15/2017
9           Highland              H3            04/09/2017
11          Miami                 H3            04/12/2017
</code>```

So, how would I group by a column field (ProductNumber) with group by and then order by Date?
In the query, I added the Order by Date. When I added the group by ProductNumber, the error message is asking me add all the fields in the inner select to the group by. Do I really need to all all the fields(there are lot of them in the real query) in the select to my group by? There must be a better solution.

Here is my query (just a sample) so far

```<code>SELECT DISTINCT TOP 100 *,
FROM   (SELECT DISTINCT NP.ManufacuturerId,
                        C.ManufacuturerName,
                        IR2.ProductNumber,
                        NP.Field1,
                        NP.Field2,
                        NP.Field3,
                        NP.Field4,
                        CN.C2Date                     CN.CompanyNotificationId,
                        NPR.NotificationProcessName,
                        Cast(NP.CompanyId AS VARCHAR(15))
                        + NPR.NotificationProcessName AS 'CompanyIdAndProcess',
                        CC.UserId,
                        NT.NotificationTypeName,
                        CC.EmailAddress,
                        IsRegistered = CASE
                                         WHEN C.IsRegistered = 1 THEN 'Yes'
                                         ELSE 'No'
                                       END,
        FROM   ProductDetails NP
               INNER JOIN Manufactuers C
                       ON C.ManufacuturerId = NP.ManufacturerId) Q
ORDER  BY CN.C2DateDESC;
</code>```

答:
I think your problem is that you are trying to order by a field that is included inside the grouped data, and is not always the same, example:

```<code>1       Kellog          H1          05/05/2017
5       Nestle          H1          05/01/2017
</code>```

If you group by ProductNumber and after the grouping you want to sort by date, is very likely that your database engine will not know by which value to order by (May 5th or May 1st?). So what you will need to do is to specify which value to use when grouping, for example with a MAX or MIN function.

Quick sample:

```<code>SELECT   Count(*) AS Products, ProductNumber, MAX(Date) AS maxdate
FROM     Table
GROUP BY ProductNumber
ORDER BY maxdate;
</code>```

Body:
I got a sort of large query which contains a inner select query. My objective is to group all the records by field call Product Number (which is not unique and appears multiple times) and then by the Date.

I added the Order By date at the end of the query and seems to work fine. The query generated all the records in order of the Date but the records are not grouped by the ProductNumber.

Here is a visual sample of the data

ProductId   Manufacturer        ProductNumber       Date
1           Kellog                H1            05/05/2017
5           Nestle                H1            05/01/2017
8           Nutmeg                H1            04/30/2017
9           Highland              H3            04/09/2017
10          Houston               H1            04/15/2017
11          Miami                 H3            04/12/2017

I am trying to get the output to look like the following

ProductId   Manufacturer        ProductNumber       Date
1           Kellog                H1            05/05/2017
5           Nestle                H1            05/01/2017
8           Nutmeg                H1            04/30/2017
10          Houston               H1            04/15/2017
9           Highland              H3            04/09/2017
11          Miami                 H3            04/12/2017

So, how would I group by a column field (ProductNumber) with group by and then order by Date?
In the query, I added the Order by Date. When I added the group by ProductNumber, the error message is asking me add all the fields in the inner select to the group by. Do I really need to all all the fields(there are lot of them in the real query) in the select to my group by? There must be a better solution.

Here is my query (just a sample) so far

SELECT DISTINCT TOP 100 *,
FROM   (SELECT DISTINCT NP.ManufacuturerId,
                        C.ManufacuturerName,
                        IR2.ProductNumber,
                        NP.Field1,
                        NP.Field2,
                        NP.Field3,
                        NP.Field4,
                        CN.C2Date                     CN.CompanyNotificationId,
                        NPR.NotificationProcessName,
                        Cast(NP.CompanyId AS VARCHAR(15))
                        + NPR.NotificationProcessName AS 'CompanyIdAndProcess',
                        CC.UserId,
                        NT.NotificationTypeName,
                        CC.EmailAddress,
                        IsRegistered = CASE
                                         WHEN C.IsRegistered = 1 THEN 'Yes'
                                         ELSE 'No'
                                       END,
        FROM   ProductDetails NP
               INNER JOIN Manufactuers C
                       ON C.ManufacuturerId = NP.ManufacturerId) Q
ORDER  BY CN.C2DateDESC;

Body:
I think your problem is that you are trying to order by a field that is included inside the grouped data, and is not always the same, example:

1       Kellog          H1          05/05/2017
5       Nestle          H1          05/01/2017

If you group by ProductNumber and after the grouping you want to sort by date, is very likely that your database engine will not know by which value to order by (May 5th or May 1st?). So what you will need to do is to specify which value to use when grouping, for example with a MAX or MIN function.

Quick sample:

SELECT   Count(*) AS Products, ProductNumber, MAX(Date) AS maxdate
FROM     Table
GROUP BY ProductNumber
ORDER BY maxdate;


答:
Your mistake is here:

I have one extra block because the first block should be the encrypted IV.

The extra block is because OpenSSL adds padding to the plain text, so that it is a multiple of the block size (16 bytes for AES). In this case the plain text is already a multiple of 16 bytes, but the padding scheme used (PKCS7) always adds padding, so here an entire block is added before encryption.

It’s common to add the IV to the front of the ciphertext, but that’s not what’s happening here.

In order to get the same result from your code you will need to add this padding yourself. In this case it is fairly simple, just add sixteen 0x10 bytes to the end of msg1 (so its toal length is 64), and change the 48 in the call to AES_cbc_encrypt to 64. The zeros you are seeing a just the value you initialize obuf to, since you are only writing 48 bytes into this buffer.

Title: Compute the CBC-MAC with AES-256 and openssl in C

Body:
I want to compute the CBC-MAC of a given plaintext with openssl. I have the following plaintext (hexdump):

hexdump -C example.txt
00000000  4d 41 43 73 20 61 72 65  20 76 65 72 79 20 75 73  |MACs are very us|
00000010  65 66 75 6c 20 69 6e 20  63 72 79 70 74 6f 67 72  |eful in cryptogr|
00000020  61 70 68 79 21 20 20 20  20 20 20 20 20 20 20 20  |aphy!           |

If I use the command line function of openssl I get the following solution:

openssl aes-256-cbc -in example.txt -K 8000000000000000000000000000000000000000000000000000000000000001 -e -iv 00 | hexdump -C
00000000  e8 e9 a4 ce 5d 20 c4 ad  f5 52 b2 c6 38 2e 12 4e  |....] ...R..8..N|
00000010  20 f5 63 65 b4 b3 96 9f  ad 8d ca e4 e8 34 2a e5  | .ce.........4*.|
00000020  0d 82 0e 3a 1e 10 5d 30  72 16 fc 00 c7 a5 b4 49  |...:..]0r......I|
00000030  f5 63 9f 85 ff e3 a4 a4  23 6e 6f 09 20 ed b1 ae  |.c......#no. ...|

So far so good. I have one extra block because the first block should be the encrypted IV. Now the last line should be my CBC-MAC, if I understood it correctly. Next I tried to do the same thing in C, here is the example code:

#include <stdio.h>
#include <string.h>
#include <openssl/sha.h>
#include <openssl/aes.h>

int main(int argc, char *argv[])
{
    unsigned char obuf[64] = {0};
    unsigned char decbuf[48] = {0};
    unsigned char msg1[] = {0x4d, 0x41, 0x43, 0x73, 0x20, 0x61, 0x72, 0x65, 0x20, 0x76, 0x65, 0x72, 0x79, 0x20, 0x75, 0x73,
                            0x65, 0x66, 0x75, 0x6c, 0x20, 0x69, 0x6e, 0x20, 0x63, 0x72, 0x79, 0x70, 0x74, 0x6f, 0x67, 0x72,
                            0x61, 0x70, 0x68, 0x79, 0x21, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20};
    unsigned char key[] =  {0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01};
    unsigned char ivenc[] ={0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
    unsigned char ivdec[] ={0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
    int i=0;

    AES_KEY enc_key, dec_key;
    AES_set_encrypt_key(key, 256, &enc_key);
    AES_cbc_encrypt(msg1, obuf, 48, &enc_key, ivenc, AES_ENCRYPT);

    for (i = 0; i < 64; i++) {
        if (!(i%16))
            printf("\n");
        printf("%02x ", obuf[i]);
    }
    printf("\n");

    AES_set_decrypt_key(key, 256, &dec_key);
    AES_cbc_encrypt(obuf, decbuf, 64, &dec_key, ivdec, AES_DECRYPT);

    for (i = 0; i < 48; i++) {
        if (!(i%16))
            printf("\n");
        printf("%02x ", decbuf[i]);
    }
    printf("\n");

    return 0;
}

I decrypt the encrypted message afterwards to verify my code. The output of my code is pretty surprising:

e8 e9 a4 ce 5d 20 c4 ad f5 52 b2 c6 38 2e 12 4e
20 f5 63 65 b4 b3 96 9f ad 8d ca e4 e8 34 2a e5
0d 82 0e 3a 1e 10 5d 30 72 16 fc 00 c7 a5 b4 49
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

4d 41 43 73 20 61 72 65 20 76 65 72 79 20 75 73
65 66 75 6c 20 69 6e 20 63 72 79 70 74 6f 67 72
61 70 68 79 21 20 20 20 20 20 20 20 20 20 20 20

The encrypted message is completely identical to the command line output, except the last line is all 0. I thought, that the first line is the encrypted IV and the three following lines are the encrypted message, so with my interpretation the last line of the message wasn't encrypted. But to my surprise the decryption results exactly to the text I used as input, so it seems that there is no loss of information.

Questions:

How is it possible that I can decrypt the output of my encryption, even if I don't have the last line?

What is my CBC-MAC? is it the last line from my command line output or the last line of my C-code output?

Am I doing something wrong in my C code? I used this so question as help.


问:
one controller for some models and views in codeigniter
I have three models: add_customer_model, add_post_model and add_project_model. Also I have three views: add_customer.tpl, add_post.tpl and add_project.tpl. I want to make one controller for them. Here it is:

```<code>  <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class ADD extends MX_Controller {

public $mname, $tag, $tpl;

function __construct()
{
    $this->mname=strtolower(get_class());// imya modulya
    $this->tag=strtoupper($this->mname); // TAG v shablone
}

//add_customer
public function index()
{
    include APPPATH."language/".LANG.".php";

    $userGROUP = $this->session->userdata('_userGROUP');
    if($userGROUP!=='Administrator')
    {
        show_404('page');
        exit;
    }
    $this->load->model($this->mname.'/add_customer_model');
   // $model=$this->mname.'_model';
    //$this->$model->index($this->mname);
    $a['IsEnabled']=$LANGUAGE['IsEnabled'];
    $a['Submit']=$LANGUAGE['Submit'];
    $a['Cancel']=$LANGUAGE['Cancel'];
    $a['Reset']=$LANGUAGE['Reset'];
    $a['Name']=$LANGUAGE['Name'];
    $a['Project Name']=$LANGUAGE['CustomerName'];
    $a['Customer Name']=$LANGUAGE['Customer Name'];

    $this->tp->assign($a);
    $this->tp->parse('CONTENT', $this->mname.'/add_customer.tpl');
}

//add_post
public function add_post()
{
    include APPPATH."language/".LANG.".php";

    $userGROUP = $this->session->userdata('_userGROUP');
    if($userGROUP=='Engineer')
    {
        show_404('page');
        exit;
    }
    $this->load->model($this->mname.'/add_post_model');
   // $model=$this->mname.'_model';
    $this->$model->add_post($this->mname);
    $a['IsEnabled']=$LANGUAGE['IsEnabled'];
    $a['Submit']=$LANGUAGE['Submit'];
    $a['Cancel']=$LANGUAGE['Cancel'];
    $a['Reset']=$LANGUAGE['Reset'];
    $a['Activity Name']=$LANGUAGE['Activity Name'];

    $this->tp->assign($a);
    $this->tp->parse('CONTENT', $this->mname.'/add_post.tpl');
}

//add_project
public function add_project()
{
include APPPATH."language/".LANG.".php";

    $this->load->model($this->mname.'/add_project_model');
   // $model=$this->mname.'_model';
   // $this->$model->add_project($this->mname);
    $a['IsEnabled']=$LANGUAGE['IsEnabled'];
    $a['Submit']=$LANGUAGE['Submit'];
    $a['Cancel']=$LANGUAGE['Cancel'];
    $a['Reset']=$LANGUAGE['Reset'];
    $a['Name']=$LANGUAGE['Name'];
    $a['SelectCustomer']=$LANGUAGE['SelectCustomer'];
    $a['Project Name']=$LANGUAGE['ProjectName'];
    $a['Manager']=$LANGUAGE['Manager'];
    $a['Customer']=$LANGUAGE['Customer'];
    $userGROUP = $this->session->userdata('_userGROUP');
    if ($userGROUP=='Administrator')
    $a['AddManager']='<button type="button" class="btn btn-warning" onclick="AddNewManager()">+</button>';
    else
    $a['AddManager']='';
    $this->tp->assign($a);
    $this->tp->parse('CONTENT', $this->mname.'/add_project.tpl');
}
</code>```

}

```<code>But in my browser I can see only add_customer page. But when I want to see add_post and add_project pages, it also shows me add_customer page. Where is a mistake?
</code>```

答:
```<code>$this->load->model($this->mname.'/'.$this->mname.'add_post_model');
</code>```

This translates to:

```<code>$this->load->model('add/addadd_post_model');
</code>```

Unusual setup. I suppose if you changed it to the following, it might work:

```<code>$this->load->model($this->mname.'/add_post_model');
</code>```

Body:
I have three models: add_customer_model, add_post_model and add_project_model. Also I have three views: add_customer.tpl, add_post.tpl and add_project.tpl. I want to make one controller for them. Here it is:

  <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class ADD extends MX_Controller {

public $mname, $tag, $tpl;

function __construct()
{
    $this->mname=strtolower(get_class());// imya modulya
    $this->tag=strtoupper($this->mname); // TAG v shablone
}

//add_customer
public function index()
{
    include APPPATH."language/".LANG.".php";

    $userGROUP = $this->session->userdata('_userGROUP');
    if($userGROUP!=='Administrator')
    {
        show_404('page');
        exit;
    }
    $this->load->model($this->mname.'/add_customer_model');
   // $model=$this->mname.'_model';
    //$this->$model->index($this->mname);
    $a['IsEnabled']=$LANGUAGE['IsEnabled'];
    $a['Submit']=$LANGUAGE['Submit'];
    $a['Cancel']=$LANGUAGE['Cancel'];
    $a['Reset']=$LANGUAGE['Reset'];
    $a['Name']=$LANGUAGE['Name'];
    $a['Project Name']=$LANGUAGE['CustomerName'];
    $a['Customer Name']=$LANGUAGE['Customer Name'];

    $this->tp->assign($a);
    $this->tp->parse('CONTENT', $this->mname.'/add_customer.tpl');
}

//add_post
public function add_post()
{
    include APPPATH."language/".LANG.".php";

    $userGROUP = $this->session->userdata('_userGROUP');
    if($userGROUP=='Engineer')
    {
        show_404('page');
        exit;
    }
    $this->load->model($this->mname.'/add_post_model');
   // $model=$this->mname.'_model';
    $this->$model->add_post($this->mname);
    $a['IsEnabled']=$LANGUAGE['IsEnabled'];
    $a['Submit']=$LANGUAGE['Submit'];
    $a['Cancel']=$LANGUAGE['Cancel'];
    $a['Reset']=$LANGUAGE['Reset'];
    $a['Activity Name']=$LANGUAGE['Activity Name'];

    $this->tp->assign($a);
    $this->tp->parse('CONTENT', $this->mname.'/add_post.tpl');
}

//add_project
public function add_project()
{
include APPPATH."language/".LANG.".php";

    $this->load->model($this->mname.'/add_project_model');
   // $model=$this->mname.'_model';
   // $this->$model->add_project($this->mname);
    $a['IsEnabled']=$LANGUAGE['IsEnabled'];
    $a['Submit']=$LANGUAGE['Submit'];
    $a['Cancel']=$LANGUAGE['Cancel'];
    $a['Reset']=$LANGUAGE['Reset'];
    $a['Name']=$LANGUAGE['Name'];
    $a['SelectCustomer']=$LANGUAGE['SelectCustomer'];
    $a['Project Name']=$LANGUAGE['ProjectName'];
    $a['Manager']=$LANGUAGE['Manager'];
    $a['Customer']=$LANGUAGE['Customer'];
    $userGROUP = $this->session->userdata('_userGROUP');
    if ($userGROUP=='Administrator')
    $a['AddManager']='<button type="button" class="btn btn-warning" onclick="AddNewManager()">+</button>';
    else
    $a['AddManager']='';
    $this->tp->assign($a);
    $this->tp->parse('CONTENT', $this->mname.'/add_project.tpl');
}

}

But in my browser I can see only add_customer page. But when I want to see add_post and add_project pages, it also shows me add_customer page. Where is a mistake?

Body:
$this->load->model($this->mname.'/'.$this->mname.'add_post_model');

This translates to:

$this->load->model('add/addadd_post_model');

Unusual setup. I suppose if you changed it to the following, it might work:

$this->load->model($this->mname.'/add_post_model');


问:
Convert JS variable to JSTL
I have a javascript variable. I'd like to assign the value of it to JSTL variable.

How can I achieve it?

答:
This is not possible since JavaScript is run in the client browser and JSTL in the server.
Your JavaScript must send the value to a servlet, one way or another.</p>

Title: Convert JS variable to JSTL


问:
How to upload particular image on particular imageView click from gallery and camera in android
i have 4 diffrent imageview and try to click on all to upload diffrent images like LIcence,Rc,Profile  etc . I want to uploaded image from gallery or camera dialog..
 like this layout.
like uper layout example</p>

答:
Please check my updated answer. This is just an example. Hope you understand from this</p>

```<code>  ImageView profile_pic;
    private static final int SELECT_PICTURE1 = 100;
    private static final int SELECT_PICTURE2 = 101;
    private static final int SELECT_PICTURE3 = 102;
    private static final int SELECT_PICTURE4 = 103;

picture1 = (ImageView) view.findViewById(R.id.picture1);
picture2 = (ImageView) view.findViewById(R.id.picture2);
picture3 = (ImageView) view.findViewById(R.id.picture3);
picture4 = (ImageView) view.findViewById(R.id.picture4);
picture1.setOnClickListener(this);
picture2.setOnClickListener(this);
picture3.setOnClickListener(this);
picture4.setOnClickListener(this);

@Override
    public void onClick(View v) {
        if (v.getId() == R.id.picture1) {
             Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE1);
        }

         if (v.getId() == R.id.picture2) {
             Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE2);
        }
         if (v.getId() == R.id.picture3) {
             Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE3);
        }

         if (v.getId() == R.id.picture4) {
             Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE4);
        }

    }

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_PICTURE1) {
            Uri selectedImageUri = data.getData();
            if (null != selectedImageUri) {
                String path = selectedImageUri.getPath();
                Log.e("image path", path + "");
                pricture1.setImageURI(selectedImageUri);
            }
        }

        if (requestCode == SELECT_PICTURE2) {
            Uri selectedImageUri = data.getData();
            if (null != selectedImageUri) {
                String path = selectedImageUri.getPath();
                Log.e("image path", path + "");
                picture2.setImageURI(selectedImageUri);
            }
        }

        if (requestCode == SELECT_PICTURE3) {
            Uri selectedImageUri = data.getData();
            if (null != selectedImageUri) {
                String path = selectedImageUri.getPath();
                Log.e("image path", path + "");
                picture3.setImageURI(selectedImageUri);
            }
        }

        if (requestCode == SELECT_PICTURE4) {
            Uri selectedImageUri = data.getData();
            if (null != selectedImageUri) {
                String path = selectedImageUri.getPath();
                Log.e("image path", path + "");
                picture4.setImageURI(selectedImageUri);
            }
        }
    }
}
</code>```

Body:
Please check my updated answer. This is just an example. Hope you understand from this

  ImageView profile_pic;
    private static final int SELECT_PICTURE1 = 100;
    private static final int SELECT_PICTURE2 = 101;
    private static final int SELECT_PICTURE3 = 102;
    private static final int SELECT_PICTURE4 = 103;

picture1 = (ImageView) view.findViewById(R.id.picture1);
picture2 = (ImageView) view.findViewById(R.id.picture2);
picture3 = (ImageView) view.findViewById(R.id.picture3);
picture4 = (ImageView) view.findViewById(R.id.picture4);
picture1.setOnClickListener(this);
picture2.setOnClickListener(this);
picture3.setOnClickListener(this);
picture4.setOnClickListener(this);

@Override
    public void onClick(View v) {
        if (v.getId() == R.id.picture1) {
             Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE1);
        }

         if (v.getId() == R.id.picture2) {
             Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE2);
        }
         if (v.getId() == R.id.picture3) {
             Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE3);
        }

         if (v.getId() == R.id.picture4) {
             Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE4);
        }

    }

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_PICTURE1) {
            Uri selectedImageUri = data.getData();
            if (null != selectedImageUri) {
                String path = selectedImageUri.getPath();
                Log.e("image path", path + "");
                pricture1.setImageURI(selectedImageUri);
            }
        }

        if (requestCode == SELECT_PICTURE2) {
            Uri selectedImageUri = data.getData();
            if (null != selectedImageUri) {
                String path = selectedImageUri.getPath();
                Log.e("image path", path + "");
                picture2.setImageURI(selectedImageUri);
            }
        }

        if (requestCode == SELECT_PICTURE3) {
            Uri selectedImageUri = data.getData();
            if (null != selectedImageUri) {
                String path = selectedImageUri.getPath();
                Log.e("image path", path + "");
                picture3.setImageURI(selectedImageUri);
            }
        }

        if (requestCode == SELECT_PICTURE4) {
            Uri selectedImageUri = data.getData();
            if (null != selectedImageUri) {
                String path = selectedImageUri.getPath();
                Log.e("image path", path + "");
                picture4.setImageURI(selectedImageUri);
            }
        }
    }
}


问:
Opening a Modal Window "using" PHP
I am creating a log in system in PHP and I'm trying to make it a little nicer.

When you log out, you get redirected back to index.php. Like this:

```<code>header("loaction: index.php?logout=true")
</code>```

This makes the url look like www.mysite.com/index.php?logout=true. I then use the following code:

```<code>if(isset($_GET['logout'])) {

$logoutvalue = $_GET['logout'];

if($logoutvalue = "true") {
$notification = "You've been logged out!";
}
</code>```

to get the value of logout from the URL and do something with it.

I have a small popout window that will display the notification variable's value. In this case it's "You've been logged out!" My question is how do I get the modal window to display when the page loads and when the url equals /index.php?logout=true ?

All comments, answers, and suggestions are greatly appreciated!

Thanks!
- Ryan

答:
Best way to get done this by using the PRG pattern.

index.php

1. Create the element for modal content in HTML

```<code><div id=modal></div>
</code>```

2. Style your #modal element

```<code>#modal {
    position: fixed;
    display: none; /*important*/
    color: white;
    text-align: center;
    z-index: 1000;
    width: 100%;
    height: 80px;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    background: crimson;
    line-height: 2;
}
</code>```

3. Define function how to show and disappear the modal box using jQuery

```<code>'use strict'

window.jQuery ?

    $.fn.notify = function(interval) {
        let el = $(this),
            text = el.text(),

            modal =()=> { // this will fire after the interval has expired
                el.fadeOut(),
                clearInterval(timer)
            },

            timer = setInterval(modal,interval)

        !text.match(/\S+/) || el.text('') // this will fire when modal box contains text
            .append(`<h3>${text}</h3>`)
            .show()
    }

: alert('jQuery required.')
</code>```

4. Attach .notify() to the jQuery selector

```<code>$(()=>{
    $('#modal').notify(1500) // 1500 is the interval in milliseconds
})
</code>```

5. Insert the notification sent from PHP inside the #modal element

```<code><div id=modal>
    <?=
        @$_SESSION["notify"]; // if this variable is not set, nothing will happen
        unset($_SESSION["notify"]);
    ?>
</div>
</code>```

6. Perform a simple $_GET request

```<code><a href=parse.php?logout>Logout</a>
</code>```

parse.php

7. Return a value using PHP in a $_SESSION variable

```<code>if (isset($_GET["logout"])) {
    $_SESSION["notify"] = "You have been logged out.";
    header("Location: index.php");
}
</code>```

This is good practice. Once the logout request is sent to PHP, it will redirect to the index page with the result in a session variable. The PRG pattern does not always require a POST request. This example sends a GET request which is ok for logouts. Note that you have to place session_start(); at the top of your files.

Title: Opening a Modal Window "using" PHP

Body:
I am creating a log in system in PHP and I'm trying to make it a little nicer.

When you log out, you get redirected back to index.php. Like this:

header("loaction: index.php?logout=true")

This makes the url look like www.mysite.com/index.php?logout=true. I then use the following code:

if(isset($_GET['logout'])) {

$logoutvalue = $_GET['logout'];

if($logoutvalue = "true") {
$notification = "You've been logged out!";
}

to get the value of logout from the URL and do something with it.

I have a small popout window that will display the notification variable's value. In this case it's "You've been logged out!" My question is how do I get the modal window to display when the page loads and when the url equals /index.php?logout=true ?

All comments, answers, and suggestions are greatly appreciated!

Thanks!
- Ryan

Body:
Best way to get done this by using the PRG pattern.

index.php

1. Create the element for modal content in HTML

<div id=modal></div>

2. Style your #modal element

#modal {
    position: fixed;
    display: none; /*important*/
    color: white;
    text-align: center;
    z-index: 1000;
    width: 100%;
    height: 80px;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    background: crimson;
    line-height: 2;
}

3. Define function how to show and disappear the modal box using jQuery

'use strict'

window.jQuery ?

    $.fn.notify = function(interval) {
        let el = $(this),
            text = el.text(),

            modal =()=> { // this will fire after the interval has expired
                el.fadeOut(),
                clearInterval(timer)
            },

            timer = setInterval(modal,interval)

        !text.match(/\S+/) || el.text('') // this will fire when modal box contains text
            .append(`<h3>${text}</h3>`)
            .show()
    }

: alert('jQuery required.')

4. Attach .notify() to the jQuery selector

$(()=>{
    $('#modal').notify(1500) // 1500 is the interval in milliseconds
})

5. Insert the notification sent from PHP inside the #modal element

<div id=modal>
    <?=
        @$_SESSION["notify"]; // if this variable is not set, nothing will happen
        unset($_SESSION["notify"]);
    ?>
</div>

6. Perform a simple $_GET request

<a href=parse.php?logout>Logout</a>

parse.php

7. Return a value using PHP in a $_SESSION variable

if (isset($_GET["logout"])) {
    $_SESSION["notify"] = "You have been logged out.";
    header("Location: index.php");
}

This is good practice. Once the logout request is sent to PHP, it will redirect to the index page with the result in a session variable. The PRG pattern does not always require a POST request. This example sends a GET request which is ok for logouts. Note that you have to place session_start(); at the top of your files.


问:
Prevent an UIAlertView from closing on PositiveButton click
I am developing mobile application using Xamarin.Forms. I have requirement of getting input in the dialog box. So, i have used UIAlertView for getting text input as like below.

I need to prevent an UIAlertView from closing on button click. I need to retain the UIAlertView dialog box even after the action initiated.

Can anyone please help me on this?

Regards,

Karthikeyan

答:
You could create a custom UIView for this using a Xib file, however if you have no objection to the dialog closing and reopening should it encounter a validation issue then the following would work fine.

EDIT: Adjusted to allow you to pass back the validation message, as the primary message on the UIAlertView.

```<code>private string message = string.Empty();

public void recursiveDialog()
{
    string input = string.Empty();

    if(message == string.Empty()) { message = "Please enter the view name"}

    var alert = UIAlertController.Create ("Save View", message, UIAlertControllerStyle.Alert);

    alert.AddTextField ((field) => {
    field.Placeholder = "view name";});

    alert.AddAction (UIAlertAction.Create ("Cancel", UIAlertActionStyle.Cancel, null));

    alert.AddAction (UIAlertAction.Create ("Save", UIAlertActionStyle.Default, action => {
               input = alert.TextFields[0].Text
    }));

    if (alert.PopoverPresentationController != null)
        alert.PopoverPresentationController.BarButtonItem = myItem;

    PresentViewController (alert, animated: true,
    action => {

        // when a dialog is selected and returns, run validation

        if(input == [whatever you want to use to validate it against])
        {
                    // it failed because it already exists for example so change our message

                    message = "That view name already exists, try again.";

            // already exists, so re-run method.
            recursiveDialog();
        }
        else
        {
            // doesn't alread exist so carry on with whatever you want to do with the name provided.

                    // clear your message variable
                    message = string.Empty();
        }
    });
}
</code>```

Body:
You could create a custom UIView for this using a Xib file, however if you have no objection to the dialog closing and reopening should it encounter a validation issue then the following would work fine.

EDIT: Adjusted to allow you to pass back the validation message, as the primary message on the UIAlertView.

private string message = string.Empty();

public void recursiveDialog()
{
    string input = string.Empty();

    if(message == string.Empty()) { message = "Please enter the view name"}

    var alert = UIAlertController.Create ("Save View", message, UIAlertControllerStyle.Alert);

    alert.AddTextField ((field) => {
    field.Placeholder = "view name";});

    alert.AddAction (UIAlertAction.Create ("Cancel", UIAlertActionStyle.Cancel, null));

    alert.AddAction (UIAlertAction.Create ("Save", UIAlertActionStyle.Default, action => {
               input = alert.TextFields[0].Text
    }));

    if (alert.PopoverPresentationController != null)
        alert.PopoverPresentationController.BarButtonItem = myItem;

    PresentViewController (alert, animated: true,
    action => {

        // when a dialog is selected and returns, run validation

        if(input == [whatever you want to use to validate it against])
        {
                    // it failed because it already exists for example so change our message

                    message = "That view name already exists, try again.";

            // already exists, so re-run method.
            recursiveDialog();
        }
        else
        {
            // doesn't alread exist so carry on with whatever you want to do with the name provided.

                    // clear your message variable
                    message = string.Empty();
        }
    });
}


问:
Angular2 *ngIf inside *ngFor
In angular 2 I want to loop through an array and show options in drop-down on the basis of some conditions. According to my search I can place a condition in ng-container directive above loop. How can I do that inside loop. (Please note that If I place what inside loop a blank space will be shown instead of option).
Thanks!</p>

```<code><md-autocomplete #package="mdAutocomplete" [displayWith]="displayPackage">
    <md-option (onSelectionChange)="packageSelection($event, package) *ngFor="let package of (reactivePackages | async)"" [value]="package">
          {{ package.packageName }}
          {{package.serviceId}}
          {{service.serviceId}}
    </md-option>
</md-autocomplete>
</code>```

答:
You can loop through the array using ng-container and can use ngif on md-options like this:

```<code>  <md-autocomplete #package="mdAutocomplete" [displayWith]="displayPackage">
    <ng-container *ngFor="let package of (reactivePackages | async)">
        <md-option (onSelectionChange)="packageSelection($event, package)" [value]="package" *ngIf="your-condition" >
            {{ package.packageName }} {{package.serviceId}} {{service.serviceId}}
        </md-option>
    </ng-container>
</md-autocomplete>
</code>```

Hope this helps.

Title: Angular2 *ngIf inside *ngFor

Body:
In angular 2 I want to loop through an array and show options in drop-down on the basis of some conditions. According to my search I can place a condition in ng-container directive above loop. How can I do that inside loop. (Please note that If I place what inside loop a blank space will be shown instead of option).
Thanks!

<md-autocomplete #package="mdAutocomplete" [displayWith]="displayPackage">
    <md-option (onSelectionChange)="packageSelection($event, package) *ngFor="let package of (reactivePackages | async)"" [value]="package">
          {{ package.packageName }}
          {{package.serviceId}}
          {{service.serviceId}}
    </md-option>
</md-autocomplete>

Body:
You can loop through the array using ng-container and can use ngif on md-options like this:

  <md-autocomplete #package="mdAutocomplete" [displayWith]="displayPackage">
    <ng-container *ngFor="let package of (reactivePackages | async)">
        <md-option (onSelectionChange)="packageSelection($event, package)" [value]="package" *ngIf="your-condition" >
            {{ package.packageName }} {{package.serviceId}} {{service.serviceId}}
        </md-option>
    </ng-container>
</md-autocomplete>

Hope this helps.


问:
TMS320C64x Quick start reference for programmers
Is thare any quickstart guide for programmers for writing DSP-accelerated appliations for TMS320C64x?

I have a program with custom algorythm (not the fft, or usial filtering) and I want to accelerate it using multi-DSP coprocessor. So, how should I modify source to move computation from main CPU to DSPs? What limitations are there for DSP-running code?

I have some experience with CUDA. In CUDA I should mark every function as being host, device, or entry point for device (kernel). There are also functions to start kernels and to upload/download data to/from GPU. There are also some limitations, for device code, described in CUDA Reference manual. I hope, there is an similar interface and a documentation for DSP.

答:
Please consider doing a search "TMS320C64x programmer's guide" - here is what I think is the most appropriate link

focus.ti.com/lit/ug/spru565b/spru565b.pdf

Also check this book - to help you get started (uses the previous generation)

Embedded image processing on the TMS320C6000 DSP : examples in code composer studio and MATLAB

ContentLicense: CC BY-SA 2.5


问:
How to deploy a Rails app with GitLab CI + Docker + Ansible?
I have a hosted GitLab with some Ruby on Rails project on it. I have a CI script, that builds a Docker image with the project and push it to the GitLab registry. Finally, I need to deploy that image to the staging server.

```<code>stages:
  - test
  - build
  - deploy

# ...

build_image:
  stage: build
  image: docker:latest
  services:
    - docker:dind
  variables:
    DOCKER_DRIVER: overlay
  script:
    - docker login -u gitlab-ci-token -p $CI_BUILD_TOKEN gitlab.host.com:4567
    - docker build -t gitlab.host.com:4567/group/app:$CI_BUILD_REF_NAME .
    - docker push gitlab.host.com:4567/group/app:$CI_BUILD_REF_NAME
  only:
    - master
</code>```

I was thinking to do it with Ansible, but can't figure how to do it. Maybe somebody can recommend what to look for or what to read? Thanx

答:
I'd recommend to not use Ansible in the CI. That usually complicates things since the container running your CI would need to have Ansible installed for this to work. This is doable however and I have a setup like this. Another downside is that Ansible 'eats' the output and if there is an error, prints it in an unformatted way.

If your intention was not to use Ansible in the CI and to just deploy it yourself with Ansible I have to advise against this as well. This will cause everyone who wants an update on the staging server to contact you, or they would need access to both the staging server and the ansible playbook. They will also ask themselves when the last update took place.

Better to put your code in a different step that does an ssh into the machine, pulls the image, stops the previous and launches the new. You can even define a 'staging' environment in Gitlab and it will inform you when the last update was done. This can be handy for the other developers.

You can put your private ssh key in the Gitlab secret variable and put it in ~/.ssh/id_rsa as a first deploy step. This will then give you access to your staging machine. You should call his user 'gitlab-staging' or something similar so you can track the access logs on the host back to this config.

Hope this helps, if you have any questions let me know.

Body:
I have a hosted GitLab with some Ruby on Rails project on it. I have a CI script, that builds a Docker image with the project and push it to the GitLab registry. Finally, I need to deploy that image to the staging server.

stages:
  - test
  - build
  - deploy

# ...

build_image:
  stage: build
  image: docker:latest
  services:
    - docker:dind
  variables:
    DOCKER_DRIVER: overlay
  script:
    - docker login -u gitlab-ci-token -p $CI_BUILD_TOKEN gitlab.host.com:4567
    - docker build -t gitlab.host.com:4567/group/app:$CI_BUILD_REF_NAME .
    - docker push gitlab.host.com:4567/group/app:$CI_BUILD_REF_NAME
  only:
    - master

I was thinking to do it with Ansible, but can't figure how to do it. Maybe somebody can recommend what to look for or what to read? Thanx


问:
Error using std::cout
When I try to print text to the Windows console (in a Console Application) I get

Compiler Error C2679 - Binary '<<' : no operator found which takes a right-hand operand of type 'std::basic_string<_Elem,_Traits,_Ax>' (or there is no acceptable conversion).

The code that generates this error is: (where str_var is any variable of type std::string)

std::cout << str_var << endl;

It highlights the first '<<' as the error. Could anybody help with this? I can't figure out why that doesnt work.

答: OK! problem solved! I reinstalled Visual Studio and now it works. So, it was just a problem with VS, not anything about the code.</p>

Title: Error using std::cout


问:
Hide automatically generated CTest targets
I'm using CMake and CTest in CLion. Annoyingly, CTest generates a load of targets that I don't care about:

Continuous

ContinuousBuild

ContinuousConfigure

ContinuousCoverage

ContinuousMemCheck

ContinuousStart

ContinuousSubmit

ContinuousTest

ContinuousUpdate

Experimental

ExperimentalBuild

ExperimentalConfigure

ExperimentalCoverage

ExperimentalMemCheck

ExperimentalStart

ExperimentalSubmit

ExperimentalTest

ExperimentalUpdate

Nightly

NightlyBuild

NightlyConfigure

NightlyCoverage

NightlyMemCheck

NightlyStart

NightlySubmit

NightlyTest

NightlyUpdate

These all show up in CLion. Quite annoying as I'm sure you'll agree. Is there solution to remove them? I'm open to any solution:

Get CTest to not generate them in the first place.

Delete the targets after CTest has created them.

A setting in CLion to hide them.

答:
A possible solution that I'm not sure works 100% is to go to Run->Edit Configurations... in CLion and simply delete all the targets you don't want.

This seems to survive reloading the CMake configuration, and make clean.


问:
Image and several lines of text in bootstrap dropdown-menu
It's probably a silly question, but I don't understand why it doesn't work.
I need to create a bootstrap menu where each item is an image on the left and several lines of text on the right.

I wrote the following HTML for this:

```<code><div class="btn-group">
    <ul class="dropdown-menu" style="display: block;">
        <li>
            <a href="#" class="clearfix">
                <div class="pull-left">
                    <span>My image</span>
                </div>
                <div class="pull-left">
                    <div>Text on the right</div>
                    <div>Second line of text</div>
                </div>
            </a>
        </li>
    </ul>
</div>
</code>```

Link to jsfiddle: https://jsfiddle.net/brucecat5/rr71xmry/

However, width is not calculated properly and the second floated block is moved below the first block.

I don't understand why it happens and what to do to fix this.

P.S. I know I can implement it with display: table-cell, but I just don't understand the reason why my approach doesn't work.

答:
I think problem is how you use dropdown-menu class, try this:

```<code><div class="btn-group">
<ul style="display: block;">
    <li>
        <a href="#" class="clearfix">
            <div class="pull-left">
                <img src="smiley.gif" alt="Smiley face" width="42" height="42">
            </div>
            <div class="pull-right">
                <p>Text on the right</p>
                <p>Second line of text</p>
            </div>
        </a>
    </li>
</ul>
</code>```

If you want use a dropdown-menu, you can look an example in this page:
https://www.w3schools.com/bootstrap/bootstrap_button_groups.asp

Hope it helps.

Body:
It's probably a silly question, but I don't understand why it doesn't work.
I need to create a bootstrap menu where each item is an image on the left and several lines of text on the right.

I wrote the following HTML for this:

                    My image

Text on the right

Second line of text

Link to jsfiddle: https://jsfiddle.net/brucecat5/rr71xmry/

However, width is not calculated properly and the second floated block is moved below the first block.

I don't understand why it happens and what to do to fix this.

P.S. I know I can implement it with display: table-cell, but I just don't understand the reason why my approach doesn't work.

Body:
I think problem is how you use dropdown-menu class, try this:

<div class="btn-group">
<ul style="display: block;">
    <li>
        <a href="#" class="clearfix">
            <div class="pull-left">
                <img src="smiley.gif" alt="Smiley face" width="42" height="42">
            </div>
            <div class="pull-right">
                <p>Text on the right</p>
                <p>Second line of text</p>
            </div>
        </a>
    </li>
</ul>

If you want use a dropdown-menu, you can look an example in this page:
https://www.w3schools.com/bootstrap/bootstrap_button_groups.asp

Hope it helps.


问:
Getting different product id for different categories
I am trying to add a link on my website's product pages and redirect the users based on the category that the product belongs to. For example, I have a category chairs which is having a Category Id of 39 and I am having another category desks for which the category id is 52.

Now my issue with the above scenario is when I am moving into the product page through category pages I am getting the above-mentioned category Id's properly and the URL will be

```<code>http://example.com/chairs/wood-chair.html
</code>```

but when I am trying to search for the product directly from the search box and move into the product page from there the URL becomes

```<code>http://example.com/wood-chair.html
</code>```

the category id becomes 2 and this happens with every category and it shows the category name as default category when I go to the product page through search box. How can I resolve this? kindly let me know if there is any parameter that doesn't change on the product page which can enable me to display the content based on the category the product belongs to.

答:
You can force magento to set a category with adding an observer on catalog_controller_product_view:

```<code>class My_Module_Model_Observer extends Mage_Core_Model_Observer
{
    public function addCategoryToBreadcrumbs(Varien_Event_Observer $observer)
    {
        if (Mage::registry('current_category')) {
            return;
        }

        $product = $observer->getProduct();

        $product->setDoNotUseCategoryId(false);
        $categoryIds = $product->getCategoryIds();

        if (count($categoryIds)) {
            $categories = Mage::getModel('catalog/category')->getCollection()
                ->addAttributeToFilter('entity_id', $categoryIds)
                ->addAttributeToFilter('is_active', 1);

            $categories->getSelect()->order('level DESC')->limit(1);

            Mage::register('current_category', $categories->getFirstItem());
        }
    }
}
</code>```

Full code here: https://magento.stackexchange.com/questions/178268/add-category-path-to-breadcrumbs-on-product-view-page/178592#178592

Body:
I am trying to add a link on my website's product pages and redirect the users based on the category that the product belongs to. For example, I have a category chairs which is having a Category Id of 39 and I am having another category desks for which the category id is 52.

Now my issue with the above scenario is when I am moving into the product page through category pages I am getting the above-mentioned category Id's properly and the URL will be

http://example.com/chairs/wood-chair.html

but when I am trying to search for the product directly from the search box and move into the product page from there the URL becomes

http://example.com/wood-chair.html

the category id becomes 2 and this happens with every category and it shows the category name as default category when I go to the product page through search box. How can I resolve this? kindly let me know if there is any parameter that doesn't change on the product page which can enable me to display the content based on the category the product belongs to.

Body:
You can force magento to set a category with adding an observer on catalog_controller_product_view:

class My_Module_Model_Observer extends Mage_Core_Model_Observer
{
    public function addCategoryToBreadcrumbs(Varien_Event_Observer $observer)
    {
        if (Mage::registry('current_category')) {
            return;
        }

        $product = $observer->getProduct();

        $product->setDoNotUseCategoryId(false);
        $categoryIds = $product->getCategoryIds();

        if (count($categoryIds)) {
            $categories = Mage::getModel('catalog/category')->getCollection()
                ->addAttributeToFilter('entity_id', $categoryIds)
                ->addAttributeToFilter('is_active', 1);

            $categories->getSelect()->order('level DESC')->limit(1);

            Mage::register('current_category', $categories->getFirstItem());
        }
    }
}

Full code here: https://magento.stackexchange.com/questions/178268/add-category-path-to-breadcrumbs-on-product-view-page/178592#178592


问:
Add days to business day calendar in Python
I am trying to add days to a business day calendar. Somehow I should receive the date 28.04.2015 but using my code I am getting 24.04.2015. I am using holiday calender and only weekdays (Monday to Friday). The code looks like the following:</p>

```<code>from datetime import datetime, timedelta, date
import holidays

def getNextBusinessDays(date, num):
    for i in range(0, num):
        date = getNextBusinessDay(date)
    return date

def getNextBusinessDay(fromDate):

    Holiday = holidays.DE()

    nextBuinessDate = datetime.strptime(fromDate, "%Y-%m-%d")
    nextBuinessDate = nextBuinessDate + timedelta(days=1)
    if date.weekday(nextBuinessDate) not in range(0, 5) and nextBuinessDate not in Holiday:
        nextBuinessDate = nextBuinessDate + timedelta(days=1)
    if date.weekday(nextBuinessDate) not in range(0, 5) and nextBuinessDate not in Holiday:
        nextBuinessDate = nextBuinessDate + timedelta(days=1)
    return nextBuinessDate.strftime('%Y-%m-%d')

if __name__ == '__main__':

    dateshift = getNextBusinessDays('2015-02-01', 60)
    print(dateshift)
</code>```

答:
Here is final working solution</p>

```<code>import datetime as dt
import holidays

Holiday = holidays.DE()

def getNextBusinessDay(date, n):
    for i in range(n):
        nextday = date1 + dt.timedelta(days=1)
        while nextday.weekday() > 4 or nextday in Holiday:
            nextday += dt.timedelta(days=1)
        date = nextday
    return date

#test
datetest = dt.datetime.strptime('02-04-15', '%d-%m-%y')
print(getNextBusinessDay(datetest,1))
</code>```

Body:
I am trying to add days to a business day calendar. Somehow I should receive the date 28.04.2015 but using my code I am getting 24.04.2015. I am using holiday calender and only weekdays (Monday to Friday). The code looks like the following:

from datetime import datetime, timedelta, date
import holidays

def getNextBusinessDays(date, num):
    for i in range(0, num):
        date = getNextBusinessDay(date)
    return date

def getNextBusinessDay(fromDate):

    Holiday = holidays.DE()

    nextBuinessDate = datetime.strptime(fromDate, "%Y-%m-%d")
    nextBuinessDate = nextBuinessDate + timedelta(days=1)
    if date.weekday(nextBuinessDate) not in range(0, 5) and nextBuinessDate not in Holiday:
        nextBuinessDate = nextBuinessDate + timedelta(days=1)
    if date.weekday(nextBuinessDate) not in range(0, 5) and nextBuinessDate not in Holiday:
        nextBuinessDate = nextBuinessDate + timedelta(days=1)
    return nextBuinessDate.strftime('%Y-%m-%d')

if __name__ == '__main__':

    dateshift = getNextBusinessDays('2015-02-01', 60)
    print(dateshift)

Body:
Here is final working solution

import datetime as dt
import holidays

Holiday = holidays.DE()

def getNextBusinessDay(date, n):
    for i in range(n):
        nextday = date1 + dt.timedelta(days=1)
        while nextday.weekday() > 4 or nextday in Holiday:
            nextday += dt.timedelta(days=1)
        date = nextday
    return date

#test
datetest = dt.datetime.strptime('02-04-15', '%d-%m-%y')
print(getNextBusinessDay(datetest,1))


问:
How can I change the background color for the active tab in PhpStorm?
I know how to change the file colors in Appearance & Behavior, but how can I change the background color of the active tab? It's probably somewhere in the theme section, but how do I change that?</p>

答:
The ActiveTabHighlighterPlugin now solves this problem.

It's compatible with: IntelliJ IDEA PhpStorm WebStorm PyCharm RubyMine AppCode CLion Gogland DataGrip Rider Android Studio.


问:
Assigning objects to an array C#
Struggling to assign objects to an array in C#.

The output of the code is unexpected because I get the nameOfProject.ClassName(?) x3 rather than name and life points of 3 monsters i added using my for loop.
Debug suggests monsters aren't being assigned.  Is there a logical flaw that people like me should be looking out for?

```<code>class Monsters
{
    public Monsters(string name, int points)
    {
        var monsterName = name;
        var monsterLifePoints = points;
    }
}
class Program
{
    static void Main(string[] args)
    {
        Monsters[] monster = new Monsters[3];

        for (int i = 0; i < monster.Length; i++)
        {
            Console.WriteLine("Please enter a name");
            string name = Console.ReadLine();
            Console.WriteLine("Please enter life points");
            int points = Convert.ToInt32(Console.ReadLine());
            monster[i] = new Monsters(name,points);
            Console.Clear();
        }
        foreach (var element in monster)
        {
            Console.WriteLine(element);
        }
        Console.ReadKey();

    }
</code>```

答:
Assignment works just fine. The problem is that you never asign the monster's name and points to a field or property:

```<code>class Monsters
{
    public Monsters(string name, int points)
    {
        var monsterName = name;
        var monsterLifePoints = points;
    }
}
</code>```

This code just assigns the input to local values and then discards them.

Your class should look like this:

```<code>class Monsters
{
    public string Name {get;set;}
    public int Points {get;set;}
    public Monsters(string name, int points)
    {
        Name = name;
        Points = points;
    }
}
</code>```

This line still won't print the details :

```<code>Console.WriteLine(element);
</code>```

You need to either create a string from the properties :

```<code>Console.WriteLine($"{element.Name} {element.Points}");
</code>```

Or override the ToString() method of your class :

```<code> public override string ToString()
{
    return $"{element.Name} {element.Points}";
}
</code>```

Title: Assigning objects to an array C#

Body:
Struggling to assign objects to an array in C#.

The output of the code is unexpected because I get the nameOfProject.ClassName(?) x3 rather than name and life points of 3 monsters i added using my for loop.
Debug suggests monsters aren't being assigned.  Is there a logical flaw that people like me should be looking out for?

class Monsters
{
    public Monsters(string name, int points)
    {
        var monsterName = name;
        var monsterLifePoints = points;
    }
}
class Program
{
    static void Main(string[] args)
    {
        Monsters[] monster = new Monsters[3];

        for (int i = 0; i < monster.Length; i++)
        {
            Console.WriteLine("Please enter a name");
            string name = Console.ReadLine();
            Console.WriteLine("Please enter life points");
            int points = Convert.ToInt32(Console.ReadLine());
            monster[i] = new Monsters(name,points);
            Console.Clear();
        }
        foreach (var element in monster)
        {
            Console.WriteLine(element);
        }
        Console.ReadKey();

    }

Body:
Assignment works just fine. The problem is that you never asign the monster's name and points to a field or property:

class Monsters
{
    public Monsters(string name, int points)
    {
        var monsterName = name;
        var monsterLifePoints = points;
    }
}

This code just assigns the input to local values and then discards them.

Your class should look like this:

class Monsters
{
    public string Name {get;set;}
    public int Points {get;set;}
    public Monsters(string name, int points)
    {
        Name = name;
        Points = points;
    }
}

This line still won't print the details :

Console.WriteLine(element);

You need to either create a string from the properties :

Console.WriteLine($"{element.Name} {element.Points}");

Or override the ToString() method of your class :

 public override string ToString()
{
    return $"{element.Name} {element.Points}";
}


问:
Rails helper method that works differently in different environments
In a Ruby on Rails application, I have a controller where I'd like some functionality to conditionally run, where the condition is dependent on the environment the application is running in. As a contrived example, in development mode I'd like it to do:

```<code>if foo == 5:
    ...
end
</code>```

And in production mode, I'd like:

```<code>if foo > 6:
    ...
end
</code>```

The difference between the two conditions is more complicated than a single constant (5 or 6 in the example above).

What is the most idiomatic way to do this in Rails? Would I write helper methods directly in the environments/ files? Or add a method to the application controller that checks the current environment? Or something else?

答:
I would just add a check for ENV['RAILS_ENV'] in the logic statements.

http://guides.rubyonrails.org/configuring.html#rails-environment-settings

I would change your code to:

```<code>if foo == 5 && ENV['RAILS_ENV'] == "development" then
    ...
elsif foo > 6 && ENV['RAILS_ENV'] == "production" then
    ...
end
</code>```

It is just another condition in you flow-control, no need to complicate it.

If you need to do it a lot, a few methods in application.rb could help:

```<code>def isDev
    ENV['RAILS_ENV'] == "development"
end

def isProd
    ENV['RAILS_ENV'] == "production"
end
</code>```

Body:
In a Ruby on Rails application, I have a controller where I'd like some functionality to conditionally run, where the condition is dependent on the environment the application is running in. As a contrived example, in development mode I'd like it to do:

if foo == 5:
    ...
end

And in production mode, I'd like:

if foo > 6:
    ...
end

The difference between the two conditions is more complicated than a single constant (5 or 6 in the example above).

What is the most idiomatic way to do this in Rails? Would I write helper methods directly in the environments/ files? Or add a method to the application controller that checks the current environment? Or something else?

Body:
I would just add a check for ENV['RAILS_ENV'] in the logic statements.

http://guides.rubyonrails.org/configuring.html#rails-environment-settings

I would change your code to:

if foo == 5 && ENV['RAILS_ENV'] == "development" then
    ...
elsif foo > 6 && ENV['RAILS_ENV'] == "production" then
    ...
end

It is just another condition in you flow-control, no need to complicate it.

If you need to do it a lot, a few methods in application.rb could help:

def isDev
    ENV['RAILS_ENV'] == "development"
end

def isProd
    ENV['RAILS_ENV'] == "production"
end


问:
Get element height with Vuejs
I want to get the height of a div in order to make the height of another div matching it. I used the method clientHeight, but It doesn't return me the good value (smaller value). Actually, It seems to return a height before all elements are charged.
After some research online, I tried to put a window.load() to delay until everything is charged but it doesn't work as well. Some ideas ?

mounted () {
  this.matchHeight()
},
matchHeight () {
  let height = document.getElementById('info-box').clientHeight
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="columns">
  <div class="left-column" id="context">
  <p>Some text</p>
  </div>
  <div class="right-column" id="info-box">
    <img />
    <ul>
      some list
    </ul>
  </div>
</div></code>```

答:
The way you are doing it is fine.  But there is another vue specific way via a ref attribute.

```<code> mounted () {
   this.matchHeight()
 },
 matchHeight () {
   let height = this.$refs.infoBox.clientHeight;
 }
</code>```

```<code>    <div class="columns">
        <div class="left-column" id="context">
            <p>Some text</p>
        </div>
        <div class="right-column" id="info-box" ref="infoBox"></>
            <img />
            <ul>
                some list
            </ul>
        </div>
    </div>
</code>```

In this case, since you are just getting the value it really doesn't matter whether you use your original getElementById approach or the vue specific ref approach. However if you were setting the value on the element then it's much better to use the ref approach so that vue understands that the value has changed and won't possibly overwrite the value with the original value if it needs to update that node in the DOM.

You can learn more here: https://v2.vuejs.org/v2/api/#vm-refs

Update

A few people had left comments that the above solution didn't work for them.  That solution provided the concepts but not full working code as example, so I have augmented my answer with the code below which demonstrates the concepts.

var app = new Vue({
    el: '#app',
    data: function () {
        return {
            leftColStyles: { },
            lines: ['one', 'two','three']
        }
    },
    methods: {
        matchHeight() {
            var heightString = this.$refs.infoBox.clientHeight + 'px';
            Vue.set(this.leftColStyles, 'height', heightString);
        }
    },
    mounted() {
        this.matchHeight();
    }

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.columns{width:300px}
.left-column {float:left; width:200px; border:solid 1px black}
.right-column {float:right; border:solid 1px blue; }</code>```

Some text

 ```

Here is a screenshot of the results in the browser:

Note:

My answer assumes that you are loading vue.js from a cdn or locally into the browser and executing it there.  If instead you are running your code via the cli and my answer is not working for you, please see @mayank1513's answer instead.

Title: Get element height with Vuejs

Body:
I want to get the height of a div in order to make the height of another div matching it. I used the method clientHeight, but It doesn't return me the good value (smaller value). Actually, It seems to return a height before all elements are charged.
After some research online, I tried to put a window.load() to delay until everything is charged but it doesn't work as well. Some ideas ?

mounted () {
  this.matchHeight()
},
matchHeight () {
  let height = document.getElementById('info-box').clientHeight
}

Some text

      some list

Body:
The way you are doing it is fine.  But there is another vue specific way via a ref attribute.

 mounted () {
   this.matchHeight()
 },
 matchHeight () {
   let height = this.$refs.infoBox.clientHeight;
 }

    <div class="columns">
        <div class="left-column" id="context">
            <p>Some text</p>
        </div>
        <div class="right-column" id="info-box" ref="infoBox"></>
            <img />
            <ul>
                some list
            </ul>
        </div>
    </div>

In this case, since you are just getting the value it really doesn't matter whether you use your original getElementById approach or the vue specific ref approach. However if you were setting the value on the element then it's much better to use the ref approach so that vue understands that the value has changed and won't possibly overwrite the value with the original value if it needs to update that node in the DOM.

You can learn more here: https://v2.vuejs.org/v2/api/#vm-refs

Update

A few people had left comments that the above solution didn't work for them.  That solution provided the concepts but not full working code as example, so I have augmented my answer with the code below which demonstrates the concepts.

var app = new Vue({
    el: '#app',
    data: function () {
        return {
            leftColStyles: { },
            lines: ['one', 'two','three']
        }
    },
    methods: {
        matchHeight() {
            var heightString = this.$refs.infoBox.clientHeight + 'px';
            Vue.set(this.leftColStyles, 'height', heightString);
        }
    },
    mounted() {
        this.matchHeight();
    }

});

.columns{width:300px}
.left-column {float:left; width:200px; border:solid 1px black}
.right-column {float:right; border:solid 1px blue; }

<div id="app">
    <div class="columns">
        <div class="left-column" id="context" v-bind:style="leftColStyles">
            <p>Some text</p>
        </div>
        <div class="right-column" id="info-box" ref="infoBox">
            <img />
            <ul>
                <li v-for="line in lines" v-text="line"></li>
            </ul>
        </div>
    </div>

</div>

 <script src="https://unpkg.com/vue@2.6.12/dist/vue.min.js"></script>

Here is a screenshot of the results in the browser:

Note:

My answer assumes that you are loading vue.js from a cdn or locally into the browser and executing it there.  If instead you are running your code via the cli and my answer is not working for you, please see @mayank1513's answer instead.

ContentLicense: CC BY-SA 4.0


问:
My delegate is nil when trying to remove child from parent IOS swift 3
I have a child view which takes over the entire parent view. I want the child to be removed from the parent by call a method from the parent using a protocol but my delegate is nil every time. I add my sample work below if you need more information just let me know

```<code>protocol childDelegate: class {
           func removeFromParent()
        }
        class ChildAction: UITableViewController {
           @IBAction func btnRemove(_sender: Any){
              if(delegate != nil){
               self.delegate?.removeFromParent()
            }
          }
        }
        class ParentClass: UIViewController:childDelegate {

         var delegate:childDelegate?
         private ChildActionView:ChildAction{
             let storyboard = UIStoryBoard(name: "Main", bundle: Bundle.main)
             let viewC = storyboard.instantiateViewController(withIdentifier: "ChildAction") as! ChildAction
              self.delegate = viewC as? childDelegate
              self.addChildViewController(viewC)
              return viewC

         }
        @IBAction func btnAddChild(_sender: Any){
              addChild(child:ChildActionView)
            }

        func addChild(child: UIViewController){
            self.addChildViewController(child)
            view.addSubview(child.view)
            child.didMove(toParentViewController: self)
        }

          func removeFromParent(){
              //remove from parent

          }
        }
</code>```

Child view controller
parent view controller image

答:
I strongly recommend you read an article or tutorial or two about the  Delegate pattern. Things will be much easier if you have a basic understanding of how it is supposed to work.

Compare this code to what you posted. See if it makes sense.

```<code>protocol childDelegate: class {
    func removeFromParent()
}

class ChildAction: UIViewController {

    // this class gets the delegate, because it wants to "call back" to a delegated function
    var delegate:childDelegate?

    @IBAction func btnRemove(_sender: Any){
        // IF delegate has been assigned, call its function
        delegate?.removeFromParent()
    }
}

class ParentClass: UIViewController, childDelegate {

    // bad naming... would be much clearer if it was "childActionViewController" or "childActionVC"
    private let ChildActionView: ChildAction = {
        let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
        let viewC = storyboard.instantiateViewController(withIdentifier: "ChildAction") as! ChildAction
        return viewC

    }()

    @IBAction func btnAddChild(_sender: Any){
        // add the child view controller
        self.addChildViewController(ChildActionView)
        // set its delegate to self
        ChildActionView.delegate = self
        // add its view to the hierarchy
        view.addSubview(ChildActionView.view)
        // finish the process
        ChildActionView.didMove(toParentViewController: self)
    }

    func removeFromParent() {
        //remove from parent
        print("removeFromParent() called...")
    }

}
</code>```

Body:
I have a child view which takes over the entire parent view. I want the child to be removed from the parent by call a method from the parent using a protocol but my delegate is nil every time. I add my sample work below if you need more information just let me know

protocol childDelegate: class {
           func removeFromParent()
        }
        class ChildAction: UITableViewController {
           @IBAction func btnRemove(_sender: Any){
              if(delegate != nil){
               self.delegate?.removeFromParent()
            }
          }
        }
        class ParentClass: UIViewController:childDelegate {

         var delegate:childDelegate?
         private ChildActionView:ChildAction{
             let storyboard = UIStoryBoard(name: "Main", bundle: Bundle.main)
             let viewC = storyboard.instantiateViewController(withIdentifier: "ChildAction") as! ChildAction
              self.delegate = viewC as? childDelegate
              self.addChildViewController(viewC)
              return viewC

         }
        @IBAction func btnAddChild(_sender: Any){
              addChild(child:ChildActionView)
            }

        func addChild(child: UIViewController){
            self.addChildViewController(child)
            view.addSubview(child.view)
            child.didMove(toParentViewController: self)
        }

          func removeFromParent(){
              //remove from parent

          }
        }

Child view controller
parent view controller image

Body:
I strongly recommend you read an article or tutorial or two about the  Delegate pattern. Things will be much easier if you have a basic understanding of how it is supposed to work.

Compare this code to what you posted. See if it makes sense.

protocol childDelegate: class {
    func removeFromParent()
}

class ChildAction: UIViewController {

    // this class gets the delegate, because it wants to "call back" to a delegated function
    var delegate:childDelegate?

    @IBAction func btnRemove(_sender: Any){
        // IF delegate has been assigned, call its function
        delegate?.removeFromParent()
    }
}

class ParentClass: UIViewController, childDelegate {

    // bad naming... would be much clearer if it was "childActionViewController" or "childActionVC"
    private let ChildActionView: ChildAction = {
        let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
        let viewC = storyboard.instantiateViewController(withIdentifier: "ChildAction") as! ChildAction
        return viewC

    }()

    @IBAction func btnAddChild(_sender: Any){
        // add the child view controller
        self.addChildViewController(ChildActionView)
        // set its delegate to self
        ChildActionView.delegate = self
        // add its view to the hierarchy
        view.addSubview(ChildActionView.view)
        // finish the process
        ChildActionView.didMove(toParentViewController: self)
    }

    func removeFromParent() {
        //remove from parent
        print("removeFromParent() called...")
    }

}


问:
how to take all tweets in a hashtag with tweepy?
I'm trying to take every open tweets in a hashtag but my code does not go further than 299 tweets.

I also trying to take tweets from a specific time line like tweets only in May 2015 and July 2016. Are there any way to do it in the main process or should I write a little code for it?

Here is my code:

```<code># if this is the first time, creates a new array which
# will store max id of the tweets for each keyword
if not os.path.isfile("max_ids.npy"):
    max_ids = np.empty(len(keywords))
    # every value is initialized as -1 in order to start from the beginning the first time program run
    max_ids.fill(-1)
else:
    max_ids = np.load("max_ids.npy")  # loads the previous max ids

# if there is any new keywords added, extends the max_ids array in order to correspond every keyword
if len(keywords) > len(max_ids):
    new_indexes = np.empty(len(keywords) - len(max_ids))
    new_indexes.fill(-1)
    max_ids = np.append(arr=max_ids, values=new_indexes)

count = 0
for i in range(len(keywords)):
    since_date="2015-01-01"
    sinceId = None
    tweetCount = 0
    maxTweets = 5000000000000000000000  # maximum tweets to find per keyword
    tweetsPerQry = 100
    searchQuery = "#{0}".format(keywords[i])
    while tweetCount < maxTweets:
        if max_ids[i] < 0:
                if (not sinceId):
                    new_tweets = api.search(q=searchQuery, count=tweetsPerQry)
                else:
                    new_tweets = api.search(q=searchQuery, count=tweetsPerQry,
                                            since_id=sinceId)
        else:
                if (not sinceId):
                    new_tweets = api.search(q=searchQuery, count=tweetsPerQry,
                                            max_id=str(max_ids - 1))
                else:
                    new_tweets = api.search(q=searchQuery, count=tweetsPerQry,
                                            max_id=str(max_ids - 1),
                                            since_id=sinceId)
        if not new_tweets:
            print("Keyword: {0}      No more tweets found".format(searchQuery))
            break
        for tweet in new_tweets:
            count += 1
            print(count)

            file_write.write(
                       .
                       .
                       .
                         )

            item = {
                .
                .
                .
                .
                .
            }

            # instead of using mongo's id for _id, using tweet's id
            raw_data = tweet._json
            raw_data["_id"] = tweet.id
            raw_data.pop("id", None)

            try:
                db["Tweets"].insert_one(item)
            except pymongo.errors.DuplicateKeyError as e:
                print("Already exists in 'Tweets' collection.")
            try:
                db["RawTweets"].insert_one(raw_data)
            except pymongo.errors.DuplicateKeyError as e:
                print("Already exists in 'RawTweets' collection.")

        tweetCount += len(new_tweets)
        print("Downloaded {0} tweets".format(tweetCount))
        max_ids[i] = new_tweets[-1].id

np.save(arr=max_ids, file="max_ids.npy")  # saving in order to continue mining from where left next time program run
</code>```

答:
Have a look at this: https://tweepy.readthedocs.io/en/v3.5.0/cursor_tutorial.html

And try this:

```<code>import tweepy

auth = tweepy.OAuthHandler(CONSUMER_TOKEN, CONSUMER_SECRET)
api = tweepy.API(auth)

for tweet in tweepy.Cursor(api.search, q='#python', rpp=100).items():
    # Do something
    pass
</code>```

In your case you have a max number of tweets to get, so as per the linked tutorial you could do:

```<code>import tweepy

MAX_TWEETS = 5000000000000000000000

auth = tweepy.OAuthHandler(CONSUMER_TOKEN, CONSUMER_SECRET)
api = tweepy.API(auth)

for tweet in tweepy.Cursor(api.search, q='#python', rpp=100).items(MAX_TWEETS):
    # Do something
    pass
</code>```

If you want tweets after a given ID, you can also pass that argument.

Body:
I'm trying to take every open tweets in a hashtag but my code does not go further than 299 tweets.

I also trying to take tweets from a specific time line like tweets only in May 2015 and July 2016. Are there any way to do it in the main process or should I write a little code for it?

Here is my code:

# if this is the first time, creates a new array which
# will store max id of the tweets for each keyword
if not os.path.isfile("max_ids.npy"):
    max_ids = np.empty(len(keywords))
    # every value is initialized as -1 in order to start from the beginning the first time program run
    max_ids.fill(-1)
else:
    max_ids = np.load("max_ids.npy")  # loads the previous max ids

# if there is any new keywords added, extends the max_ids array in order to correspond every keyword
if len(keywords) > len(max_ids):
    new_indexes = np.empty(len(keywords) - len(max_ids))
    new_indexes.fill(-1)
    max_ids = np.append(arr=max_ids, values=new_indexes)

count = 0
for i in range(len(keywords)):
    since_date="2015-01-01"
    sinceId = None
    tweetCount = 0
    maxTweets = 5000000000000000000000  # maximum tweets to find per keyword
    tweetsPerQry = 100
    searchQuery = "#{0}".format(keywords[i])
    while tweetCount < maxTweets:
        if max_ids[i] < 0:
                if (not sinceId):
                    new_tweets = api.search(q=searchQuery, count=tweetsPerQry)
                else:
                    new_tweets = api.search(q=searchQuery, count=tweetsPerQry,
                                            since_id=sinceId)
        else:
                if (not sinceId):
                    new_tweets = api.search(q=searchQuery, count=tweetsPerQry,
                                            max_id=str(max_ids - 1))
                else:
                    new_tweets = api.search(q=searchQuery, count=tweetsPerQry,
                                            max_id=str(max_ids - 1),
                                            since_id=sinceId)
        if not new_tweets:
            print("Keyword: {0}      No more tweets found".format(searchQuery))
            break
        for tweet in new_tweets:
            count += 1
            print(count)

            file_write.write(
                       .
                       .
                       .
                         )

            item = {
                .
                .
                .
                .
                .
            }

            # instead of using mongo's id for _id, using tweet's id
            raw_data = tweet._json
            raw_data["_id"] = tweet.id
            raw_data.pop("id", None)

            try:
                db["Tweets"].insert_one(item)
            except pymongo.errors.DuplicateKeyError as e:
                print("Already exists in 'Tweets' collection.")
            try:
                db["RawTweets"].insert_one(raw_data)
            except pymongo.errors.DuplicateKeyError as e:
                print("Already exists in 'RawTweets' collection.")

        tweetCount += len(new_tweets)
        print("Downloaded {0} tweets".format(tweetCount))
        max_ids[i] = new_tweets[-1].id

np.save(arr=max_ids, file="max_ids.npy")  # saving in order to continue mining from where left next time program run

Body:
Have a look at this: https://tweepy.readthedocs.io/en/v3.5.0/cursor_tutorial.html

And try this:

import tweepy

auth = tweepy.OAuthHandler(CONSUMER_TOKEN, CONSUMER_SECRET)
api = tweepy.API(auth)

for tweet in tweepy.Cursor(api.search, q='#python', rpp=100).items():
    # Do something
    pass

In your case you have a max number of tweets to get, so as per the linked tutorial you could do:

import tweepy

MAX_TWEETS = 5000000000000000000000

auth = tweepy.OAuthHandler(CONSUMER_TOKEN, CONSUMER_SECRET)
api = tweepy.API(auth)

for tweet in tweepy.Cursor(api.search, q='#python', rpp=100).items(MAX_TWEETS):
    # Do something
    pass

If you want tweets after a given ID, you can also pass that argument.


问:
PresentationSource.FromVisual(this) returns null value in WPF
I'm using the following code for my:

```<code>protected override void OnSourceInitialized(EventArgs e)
{
...
....
HwndSource source = PresentationSource.FromVisual(this) as HwndSource;
...
...
}
</code>```

In some systems the "source" value comes out to be null and i cant find the reason why...

答:
Starting with .Net 4.0, you can access HwndSource without having to show the window first:

```<code>var helper = new WindowInteropHelper(this);
var hwndSource = HwndSource.FromHwnd(helper.EnsureHandle());
</code>```

Body:
I'm using the following code for my:

protected override void OnSourceInitialized(EventArgs e)
{
...
....
HwndSource source = PresentationSource.FromVisual(this) as HwndSource;
...
...
}

In some systems the "source" value comes out to be null and i cant find the reason why...

Body:
Starting with .Net 4.0, you can access HwndSource without having to show the window first:

var helper = new WindowInteropHelper(this);
var hwndSource = HwndSource.FromHwnd(helper.EnsureHandle());