问:
App has stopped while trying to display data from database. Android Studio
I'm currently trying to display a data from my database which I currently created. But when I try to run it in my phone, it always stops. This is my code

Edit Users Screen.java

```<code>    TextView textView;
    String text = " ";
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_users);

        // added

        textView = (TextView) findViewById(R.id.textView);

        DatabaseHelper db = new DatabaseHelper(this);

        // inserting users
        db.addUsers(new Users("1", "Julian", "juliankurtseguiran@gmail.com",      "seguiran"));

        // reading and displaying all users (you can remove it on where it should be placed

        List<Users> users = db.getAllUsers();

        for (Users u : users)
        {
            String log = "ID number:" + u.getIDnumber() + "Name:" + u.getName() +
                    "Email:" + u.getEmail() + "Password:" + u.getPassword();

            text = text + log;
        }

        textView.setText(text);
    }
</code>```

DatabaseHelper.java

```<code>    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_USERS_TABLE = "CREATE TABLE" + TABLE_USERS + "("
                + KEY_IDNUMBER + "INTEGER PRIMARY KEY," + KEY_NAME + "TEXT,"
                +  KEY_EMAIL + "TEXT," + KEY_PASSWORD + "TEXT," + ")";

        db.execSQL(CREATE_USERS_TABLE);

    }

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

    }

    void addUsers (Users users) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values  =  new ContentValues();
        values.put("KEY_NAME", users.getName());
        values.put("KEY_EMAIL", users.getEmail());
        values.put("KEY_PASSWORD", users.getPassword());

        db.insert(TABLE_USERS, null, values);
        db.close();

    }

    Users getUsers (int idnumber) {
        SQLiteDatabase db = this.getWritableDatabase();

        Cursor cursor = db.query(TABLE_USERS, new String[] {KEY_IDNUMBER, KEY_NAME, KEY_EMAIL, KEY_PASSWORD}, KEY_IDNUMBER
         + "=?", new String[] {String.valueOf(idnumber)}, null, null, null, null);

        if (cursor != null ){
            cursor.moveToFirst();
        }

        Users users = new Users (Integer.parseInt(cursor.getString(0)),       cursor.getString(1), cursor.getString(2), cursor.getString(3));

        return users;

    }

    public List<Users> getAllUsers(){
        List<Users> usersList = new ArrayList<>();

        String selectQuery ="SELECT * FROM " + TABLE_USERS;

        SQLiteDatabase db  = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        if (cursor.moveToFirst()) {
            do {
                Users users = new Users();
                users.setIDnumber(Integer.parseInt(cursor.getString(0)));
                users.setName(cursor.getString(1));
                users.setEmail(cursor.getString(2));
                users.setPassword(cursor.getString(3));

                usersList.add(users);
            } while (cursor.moveToNext());
        }

        return usersList;
    }

    public int updateUsers (Users users) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put("KEY_NAME", users.getName());
        values.put("KEY_EMAIL", users.getEmail());
        values.put("KEY_PASSWORD", users.getPassword());

        return db.update(TABLE_USERS, values, KEY_IDNUMBER + "=?",
                new String[]{String.valueOf(users.getIDnumber())});

    }

    public void deleteUsers (Users users) {

        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_USERS, KEY_IDNUMBER + "=?",
        new String[]{String.valueOf(users.getIDnumber())});

        db.close();
    }

    public int getUsersCount() {

        String countQuery = "SELECT * FROM " + TABLE_USERS;
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        cursor.close();

        return cursor.getCount();
    }
</code>```

Users.java

```<code>    public class Users
    {
        int IDnumber;
        String Name;
        String Email;
        String Password;

        public Users(int i, String string, String cursorString, String s) {
            this.Name = Name;
            this.Email = Email;
            this.Password = Password;
        }

        public Users() {

        }

        public Users(String s, String julian, String cursorString, String seguiran) {
        }

        public int getIDnumber() {
            return IDnumber;
        }

        public void setIDnumber(int IDnumber) {
            this.IDnumber = IDnumber;
        }

        public String getName() {
            return Name;
        }

        public void setName(String name) {
            Name = name;
        }

        public String getEmail() {
            return Email;
        }

        public void setEmail(String email) {
            Email = email;
        }

        public String getPassword() {
            return Password;
        }

        public void setPassword(String password) {
            Password = password;
        }
    }
</code>```

Logcat

```<code>4-03 12:14:14.591 2418-2418/com.example.aadre.saferhomeph V/FA: onActivityCreated
04-03 12:14:14.651 2418-2418/com.example.aadre.saferhomeph E/SQLiteLog: (1) near "TABLEusers": syntax error
04-03 12:14:14.651 2418-2418/com.example.aadre.saferhomeph D/AndroidRuntime: Shutting down VM
04-03 12:14:14.651 2418-2418/com.example.aadre.saferhomeph W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x41d85c08)
04-03 12:14:14.671 2418-2418/com.example.aadre.saferhomeph E/AndroidRuntime: FATAL EXCEPTION: main
                                                                             Process: com.example.aadre.saferhomeph, PID: 2418
                                                                             java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.aadre.saferhomeph/com.example.aadre.saferhomeph.Edit_Users_Screen}: android.database.sqlite.SQLiteException: near "TABLEusers": syntax error (code 1): , while compiling: CREATE TABLEusers(idnumber INTEGER PRIMARY KEY, nameTEXT, email TEXT, password TEXT )
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2339)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2391)
                                                                                at android.app.ActivityThread.access$900(ActivityThread.java:166)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1281)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:146)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5511)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:515)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
                                                                                at dalvik.system.NativeStart.main(Native Method)
                                                                              Caused by: android.database.sqlite.SQLiteException: near "TABLEusers": syntax error (code 1): , while compiling: CREATE TABLEusers(idnumber INTEGER PRIMARY KEY, nameTEXT, email TEXT, password TEXT )
                                                                                at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                                                                                at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1113)
                                                                                at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:690)
                                                                                at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                                                                                at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
                                                                                at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
                                                                                at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1806)
                                                                                at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1737)
                                                                                at com.example.aadre.saferhomeph.DatabaseHelper.onCreate(DatabaseHelper.java:38)
                                                                                at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:252)
                                                                                at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
                                                                                at com.example.aadre.saferhomeph.DatabaseHelper.addUsers(DatabaseHelper.java:50)
                                                                                at com.example.aadre.saferhomeph.Edit_Users_Screen.onCreate(Edit_Users_Screen.java:33)
                                                                                at android.app.Activity.performCreate(Activity.java:5322)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2303)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2391)
                                                                                at android.app.ActivityThread.access$900(ActivityThread.java:166)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1281)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:146)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5511)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:515)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
                                                                                at dalvik.system.NativeStart.main(Native Method)
04-03 12:14:14.791 2418-2430/com.example.aadre.saferhomeph V/MediaPlayer: message received msg=2, ext1=0, ext2=0
04-03 12:14:14.791 2418-2430/com.example.aadre.saferhomeph V/MediaPlayer: playback complete
04-03 12:14:14.791 2418-2430/com.example.aadre.saferhomeph V/MediaPlayer: callback application
04-03 12:14:14.791 2418-2430/com.example.aadre.saferhomeph V/MediaPlayer: back from callback
04-03 12:14:14.791 2418-2430/com.example.aadre.saferhomeph V/MediaPlayer: message received msg=7, ext1=0, ext2=0
04-03 12:14:14.791 2418-2430/com.example.aadre.saferhomeph V/MediaPlayer: unrecognized message: (7, 0, 0)
04-03 12:14:14.791 2418-2430/com.example.aadre.saferhomeph V/MediaPlayer: callback application
04-03 12:14:14.791 2418-2430/com.example.aadre.saferhomeph V/MediaPlayer: back from callback
04-03 12:14:19.561 2418-2456/com.example.aadre.saferhomeph W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.
</code>```

pls help

答:
Remove "," after TEXT from create table

```<code>String CREATE_USERS_TABLE = "CREATE TABLE " + TABLE_USERS + "("
        + KEY_IDNUMBER + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
        +  KEY_EMAIL + " TEXT," + KEY_PASSWORD + " TEXT" + ")";

db.execSQL(CREATE_USERS_TABLE);
</code>```

Body:
I'm currently trying to display a data from my database which I currently created. But when I try to run it in my phone, it always stops. This is my code

Edit Users Screen.java

    TextView textView;
    String text = " ";
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_users);

        // added

        textView = (TextView) findViewById(R.id.textView);

        DatabaseHelper db = new DatabaseHelper(this);

        // inserting users
        db.addUsers(new Users("1", "Julian", "juliankurtseguiran@gmail.com",      "seguiran"));

        // reading and displaying all users (you can remove it on where it should be placed

        List<Users> users = db.getAllUsers();

        for (Users u : users)
        {
            String log = "ID number:" + u.getIDnumber() + "Name:" + u.getName() +
                    "Email:" + u.getEmail() + "Password:" + u.getPassword();

            text = text + log;
        }

        textView.setText(text);
    }

DatabaseHelper.java

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_USERS_TABLE = "CREATE TABLE" + TABLE_USERS + "("
                + KEY_IDNUMBER + "INTEGER PRIMARY KEY," + KEY_NAME + "TEXT,"
                +  KEY_EMAIL + "TEXT," + KEY_PASSWORD + "TEXT," + ")";

        db.execSQL(CREATE_USERS_TABLE);

    }

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

    }

    void addUsers (Users users) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values  =  new ContentValues();
        values.put("KEY_NAME", users.getName());
        values.put("KEY_EMAIL", users.getEmail());
        values.put("KEY_PASSWORD", users.getPassword());

        db.insert(TABLE_USERS, null, values);
        db.close();

    }

    Users getUsers (int idnumber) {
        SQLiteDatabase db = this.getWritableDatabase();

        Cursor cursor = db.query(TABLE_USERS, new String[] {KEY_IDNUMBER, KEY_NAME, KEY_EMAIL, KEY_PASSWORD}, KEY_IDNUMBER
         + "=?", new String[] {String.valueOf(idnumber)}, null, null, null, null);

        if (cursor != null ){
            cursor.moveToFirst();
        }

        Users users = new Users (Integer.parseInt(cursor.getString(0)),       cursor.getString(1), cursor.getString(2), cursor.getString(3));

        return users;

    }

    public List<Users> getAllUsers(){
        List<Users> usersList = new ArrayList<>();

        String selectQuery ="SELECT * FROM " + TABLE_USERS;

        SQLiteDatabase db  = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        if (cursor.moveToFirst()) {
            do {
                Users users = new Users();
                users.setIDnumber(Integer.parseInt(cursor.getString(0)));
                users.setName(cursor.getString(1));
                users.setEmail(cursor.getString(2));
                users.setPassword(cursor.getString(3));

                usersList.add(users);
            } while (cursor.moveToNext());
        }

        return usersList;
    }

    public int updateUsers (Users users) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put("KEY_NAME", users.getName());
        values.put("KEY_EMAIL", users.getEmail());
        values.put("KEY_PASSWORD", users.getPassword());

        return db.update(TABLE_USERS, values, KEY_IDNUMBER + "=?",
                new String[]{String.valueOf(users.getIDnumber())});

    }

    public void deleteUsers (Users users) {

        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_USERS, KEY_IDNUMBER + "=?",
        new String[]{String.valueOf(users.getIDnumber())});

        db.close();
    }

    public int getUsersCount() {

        String countQuery = "SELECT * FROM " + TABLE_USERS;
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        cursor.close();

        return cursor.getCount();
    }

Users.java

    public class Users
    {
        int IDnumber;
        String Name;
        String Email;
        String Password;

        public Users(int i, String string, String cursorString, String s) {
            this.Name = Name;
            this.Email = Email;
            this.Password = Password;
        }

        public Users() {

        }

        public Users(String s, String julian, String cursorString, String seguiran) {
        }

        public int getIDnumber() {
            return IDnumber;
        }

        public void setIDnumber(int IDnumber) {
            this.IDnumber = IDnumber;
        }

        public String getName() {
            return Name;
        }

        public void setName(String name) {
            Name = name;
        }

        public String getEmail() {
            return Email;
        }

        public void setEmail(String email) {
            Email = email;
        }

        public String getPassword() {
            return Password;
        }

        public void setPassword(String password) {
            Password = password;
        }
    }

Logcat

4-03 12:14:14.591 2418-2418/com.example.aadre.saferhomeph V/FA: onActivityCreated
04-03 12:14:14.651 2418-2418/com.example.aadre.saferhomeph E/SQLiteLog: (1) near "TABLEusers": syntax error
04-03 12:14:14.651 2418-2418/com.example.aadre.saferhomeph D/AndroidRuntime: Shutting down VM
04-03 12:14:14.651 2418-2418/com.example.aadre.saferhomeph W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x41d85c08)
04-03 12:14:14.671 2418-2418/com.example.aadre.saferhomeph E/AndroidRuntime: FATAL EXCEPTION: main
                                                                             Process: com.example.aadre.saferhomeph, PID: 2418
                                                                             java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.aadre.saferhomeph/com.example.aadre.saferhomeph.Edit_Users_Screen}: android.database.sqlite.SQLiteException: near "TABLEusers": syntax error (code 1): , while compiling: CREATE TABLEusers(idnumber INTEGER PRIMARY KEY, nameTEXT, email TEXT, password TEXT )
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2339)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2391)
                                                                                at android.app.ActivityThread.access$900(ActivityThread.java:166)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1281)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:146)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5511)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:515)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
                                                                                at dalvik.system.NativeStart.main(Native Method)
                                                                              Caused by: android.database.sqlite.SQLiteException: near "TABLEusers": syntax error (code 1): , while compiling: CREATE TABLEusers(idnumber INTEGER PRIMARY KEY, nameTEXT, email TEXT, password TEXT )
                                                                                at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                                                                                at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1113)
                                                                                at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:690)
                                                                                at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                                                                                at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
                                                                                at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
                                                                                at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1806)
                                                                                at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1737)
                                                                                at com.example.aadre.saferhomeph.DatabaseHelper.onCreate(DatabaseHelper.java:38)
                                                                                at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:252)
                                                                                at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
                                                                                at com.example.aadre.saferhomeph.DatabaseHelper.addUsers(DatabaseHelper.java:50)
                                                                                at com.example.aadre.saferhomeph.Edit_Users_Screen.onCreate(Edit_Users_Screen.java:33)
                                                                                at android.app.Activity.performCreate(Activity.java:5322)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2303)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2391)
                                                                                at android.app.ActivityThread.access$900(ActivityThread.java:166)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1281)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:146)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5511)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:515)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
                                                                                at dalvik.system.NativeStart.main(Native Method)
04-03 12:14:14.791 2418-2430/com.example.aadre.saferhomeph V/MediaPlayer: message received msg=2, ext1=0, ext2=0
04-03 12:14:14.791 2418-2430/com.example.aadre.saferhomeph V/MediaPlayer: playback complete
04-03 12:14:14.791 2418-2430/com.example.aadre.saferhomeph V/MediaPlayer: callback application
04-03 12:14:14.791 2418-2430/com.example.aadre.saferhomeph V/MediaPlayer: back from callback
04-03 12:14:14.791 2418-2430/com.example.aadre.saferhomeph V/MediaPlayer: message received msg=7, ext1=0, ext2=0
04-03 12:14:14.791 2418-2430/com.example.aadre.saferhomeph V/MediaPlayer: unrecognized message: (7, 0, 0)
04-03 12:14:14.791 2418-2430/com.example.aadre.saferhomeph V/MediaPlayer: callback application
04-03 12:14:14.791 2418-2430/com.example.aadre.saferhomeph V/MediaPlayer: back from callback
04-03 12:14:19.561 2418-2456/com.example.aadre.saferhomeph W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.

pls help

Body:
Remove "," after TEXT from create table

String CREATE_USERS_TABLE = "CREATE TABLE " + TABLE_USERS + "("
        + KEY_IDNUMBER + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
        +  KEY_EMAIL + " TEXT," + KEY_PASSWORD + " TEXT" + ")";

db.execSQL(CREATE_USERS_TABLE);


来源: stackexchange

问:
Realm Xamarin.Android Unit Test System.PlatformNotSupportedException
I'm trying to unit tests my Realm (1.1.0) implementation using a Xamarin.Android Unit Test project since I cannot unit test a PCL library.

When I invoke

```<code>_realm = Realm.GetInstance();
</code>```

I get the following error:

```<code>Fail [FAIL] : System.PlatformNotSupportedException : The PCL build of Realm is being linked which probably means you need to use NuGet or otherwise link a platform-specific Realm.dll to your main application.
          at Realms.RealmPCLHelpers.ThrowProxyShouldNeverBeUsed () [0x00000] in <a0bdda658c634b1e932b3ea414073102>:0
          at Realms.Realm.GetInstance (Realms.RealmConfigurationBase config) [0x00000] in <a0bdda658c634b1e932b3ea414073102>:0
          at DrifterApps.FeedTheHole.Core.Realms.TestRealmQueries.Setup () [0x00003] in /Users/patrick/Projects/FeedTheHole/Core.Realms.Tests/Realms/TestRealmQueries.cs:17
          at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (System.Reflection.MonoMethod,object,object[],System.Exception&)
          at System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00038] in /Users/builder/data/lanes/3511/77cb8568/source/mono/mcs/class/corlib/System.Reflection/MonoMethod.cs:305
    Ignore [INFO] : another time
</code>```

My project includes the Realm library as such:

```<code><Reference Include="Remotion.Linq">
  <HintPath>..\packages\Remotion.Linq.2.1.1\lib\portable-net45+win+wpa81+wp80\Remotion.Linq.dll</HintPath>
</Reference>
<Reference Include="Realm">
  <HintPath>..\packages\Realm.Database.1.1.0\lib\MonoAndroid44\Realm.dll</HintPath>
</Reference>
<Reference Include="Realm.Sync">
  <HintPath>..\packages\Realm.1.1.0\lib\MonoAndroid44\Realm.Sync.dll</HintPath>
</Reference>
<Reference Include="DotNetCross.Memory.Unsafe">
  <HintPath>..\packages\DotNetCross.Memory.Unsafe.0.2.3.4\lib\netstandard1.0\DotNetCross.Memory.Unsafe.dll</HintPath>
</Reference>
</code>```

Any ideas??

答: The Realm team fixed the issue with release 1.1.1</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to unit tests my Realm (1.1.0) implementation using a Xamarin.Android Unit Test project since I cannot unit test a PCL library.

When I invoke

_realm = Realm.GetInstance();

I get the following error:

Fail [FAIL] : System.PlatformNotSupportedException : The PCL build of Realm is being linked which probably means you need to use NuGet or otherwise link a platform-specific Realm.dll to your main application.
          at Realms.RealmPCLHelpers.ThrowProxyShouldNeverBeUsed () [0x00000] in <a0bdda658c634b1e932b3ea414073102>:0
          at Realms.Realm.GetInstance (Realms.RealmConfigurationBase config) [0x00000] in <a0bdda658c634b1e932b3ea414073102>:0
          at DrifterApps.FeedTheHole.Core.Realms.TestRealmQueries.Setup () [0x00003] in /Users/patrick/Projects/FeedTheHole/Core.Realms.Tests/Realms/TestRealmQueries.cs:17
          at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (System.Reflection.MonoMethod,object,object[],System.Exception&)
          at System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00038] in /Users/builder/data/lanes/3511/77cb8568/source/mono/mcs/class/corlib/System.Reflection/MonoMethod.cs:305
    Ignore [INFO] : another time

My project includes the Realm library as such:

<Reference Include="Remotion.Linq">
  <HintPath>..\packages\Remotion.Linq.2.1.1\lib\portable-net45+win+wpa81+wp80\Remotion.Linq.dll</HintPath>
</Reference>
<Reference Include="Realm">
  <HintPath>..\packages\Realm.Database.1.1.0\lib\MonoAndroid44\Realm.dll</HintPath>
</Reference>
<Reference Include="Realm.Sync">
  <HintPath>..\packages\Realm.1.1.0\lib\MonoAndroid44\Realm.Sync.dll</HintPath>
</Reference>
<Reference Include="DotNetCross.Memory.Unsafe">
  <HintPath>..\packages\DotNetCross.Memory.Unsafe.0.2.3.4\lib\netstandard1.0\DotNetCross.Memory.Unsafe.dll</HintPath>
</Reference>

Any ideas??


问:
Why does the JButton becomes inactive after it has been clicked?
After I have entered the username and password for the user, then click the button to send the stream to the server to determine if the user should be authenticated. The button stops working as though it has been disabled.</p>

```<code>public class EmployeeSignIn extends JFrame implements ActionListener {
    private JLabel lblUsername, lblPassword;
    private JTextField txtUsername;
    private JPasswordField jpfPassword;
    private JButton btnSubmit;
    private JPanel pnlButton, pnlLogo, pnlComponents1, pnlComponents2;
    private Socket socket;
    private ObjectOutputStream oos;
    private ObjectInputStream ois;

    private void initializeStreamComponents() {
        try {
            socket = new Socket("localhost", 4200);
            oos = new ObjectOutputStream(socket.getOutputStream());
            ois = new ObjectInputStream(socket.getInputStream());
        } catch (IOException e) {
            System.err.println(e.getMessage());
        }
    }

    private void initComponent() {
        initializeStreamComponents();

        lblUsername = new JLabel("Username");
        lblPassword = new JLabel("Password");

        txtUsername = new JTextField();

        jpfPassword = new JPasswordField();

        btnSubmit = new JButton("Sign In");

        pnlButton = new JPanel();
        pnlLogo = new JPanel(new GridLayout(1, 2));
        pnlComponents1 = new JPanel(new GridLayout(1, 2, 3, 3));
        pnlComponents2 = new JPanel(new GridLayout(1, 2, 3, 3));
    }

    private void addComponentsToPanel() {

        pnlLogo.add(new JLabel(new ImageIcon("img/app.png")));

        pnlComponents1.add(lblUsername);
        pnlComponents1.add(txtUsername);

        pnlComponents2.add(lblPassword);
        pnlComponents2.add(jpfPassword);

        pnlButton.add(btnSubmit);
    }

    private void addPanelsToWindow() {
        Container container = getContentPane();
        container.add(pnlLogo);
        container.add(pnlComponents1);
        container.add(pnlComponents2);
        container.add(pnlButton);
    }

    private void registerListeners() {
        btnSubmit.addActionListener(this);
    }

    private void setWindowProperties() {
        this.setTitle("ARD-Employee");
        this.setLayout(new GridLayout(4, 2));
        this.setVisible(true);
        this.setSize(450, 200);
        this.setResizable(false);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLocationRelativeTo(null);
    }

    public EmployeeSignIn() {
        this.initComponent();
        this.addComponentsToPanel();
        this.addPanelsToWindow();
        this.registerListeners();
        this.setWindowProperties();
    }

    private boolean validateFields() {
        if (!textFieldCheck(txtUsername)) {
            txtUsername.grabFocus();
            System.out.println(1);
            System.out.println("Please enter your username");
            System.out.println(2);
            return false;
        }

        if (!textFieldCharacterCheck(txtUsername)) {
            txtUsername.grabFocus();
            System.out.println("No Special Characters Allowed in Username!");
            return false;
        }

        if (!passwordFieldCheck(jpfPassword)) {
            jpfPassword.grabFocus();
            System.out.println("Please Enter your Password!");
            return false;
        }
        return true;
    }

    private boolean textFieldCheck(JTextField field) {
        if (field.getText().trim().isEmpty()) {
            field.grabFocus();
            return false;
        }
        return true;
    }

    private boolean passwordFieldCheck(JPasswordField field) {
        String password = new String(field.getPassword());
        if (password.trim().isEmpty()) {
            return false;
        }
        return true;
    }

    private boolean textFieldCharacterCheck(JTextField field) {
        return field.getText().matches("^\\d+$");
    }

    public String getUsername() {
        return txtUsername.getText();
    }

    public String getPassword() {
        return new String(jpfPassword.getPassword());
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        JButton src = (JButton) e.getSource();

        new Thread() {
            @Override
            public void run() {
                if (src.equals(btnSubmit)) {
                    if (validateFields()) {
                        sendStreamsToServer();
                    }
                }
            }
        }.start();
    }

    private void sendStreamsToServer() {
        try {

            String userType = "employee";
            oos.writeObject(userType);

            oos.writeObject(this.getUsername());
            System.out.println("USERNAME: " + this.getUsername());
            oos.writeObject(this.getPassword());
            System.out.println("PASSWORD: " + this.getPassword());

            String readObj = (String) ois.readObject();
            System.out.println("READ OBJECT: " + readObj);

            boolean validationCheck = (boolean) ois.readObject();
            System.out.println("Employee/VALIDATION CHECK: " + validationCheck);

        } catch (IOException e1) {
            System.err.println(e1.getMessage());
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private void closeConnection() {
        try {
            oos.close();
            ois.close();
        } catch (IOException e) {
            System.err.println(e.getMessage());
        }
    }

    public static void main(String[] args) {
        new EmployeeSignIn();
    }
}
</code>```

答:
Your ActionListener is connecting to a Socket. A Socket blocks waiting for input. Since this code is executed on the Event Dispatch Thread (EDT), the GUI freezes.

The solution is to connect to your Socket in a separate Thread.

Read the section from the Swing tutorial on Concurrency for more information on the EDT. You may want to consider using the SwingWorker as your Thread. The SwingWorker API makes it easier to update the GUI when required.

Body:
After I have entered the username and password for the user, then click the button to send the stream to the server to determine if the user should be authenticated. The button stops working as though it has been disabled.

public class EmployeeSignIn extends JFrame implements ActionListener {
    private JLabel lblUsername, lblPassword;
    private JTextField txtUsername;
    private JPasswordField jpfPassword;
    private JButton btnSubmit;
    private JPanel pnlButton, pnlLogo, pnlComponents1, pnlComponents2;
    private Socket socket;
    private ObjectOutputStream oos;
    private ObjectInputStream ois;

    private void initializeStreamComponents() {
        try {
            socket = new Socket("localhost", 4200);
            oos = new ObjectOutputStream(socket.getOutputStream());
            ois = new ObjectInputStream(socket.getInputStream());
        } catch (IOException e) {
            System.err.println(e.getMessage());
        }
    }

    private void initComponent() {
        initializeStreamComponents();

        lblUsername = new JLabel("Username");
        lblPassword = new JLabel("Password");

        txtUsername = new JTextField();

        jpfPassword = new JPasswordField();

        btnSubmit = new JButton("Sign In");

        pnlButton = new JPanel();
        pnlLogo = new JPanel(new GridLayout(1, 2));
        pnlComponents1 = new JPanel(new GridLayout(1, 2, 3, 3));
        pnlComponents2 = new JPanel(new GridLayout(1, 2, 3, 3));
    }

    private void addComponentsToPanel() {

        pnlLogo.add(new JLabel(new ImageIcon("img/app.png")));

        pnlComponents1.add(lblUsername);
        pnlComponents1.add(txtUsername);

        pnlComponents2.add(lblPassword);
        pnlComponents2.add(jpfPassword);

        pnlButton.add(btnSubmit);
    }

    private void addPanelsToWindow() {
        Container container = getContentPane();
        container.add(pnlLogo);
        container.add(pnlComponents1);
        container.add(pnlComponents2);
        container.add(pnlButton);
    }

    private void registerListeners() {
        btnSubmit.addActionListener(this);
    }

    private void setWindowProperties() {
        this.setTitle("ARD-Employee");
        this.setLayout(new GridLayout(4, 2));
        this.setVisible(true);
        this.setSize(450, 200);
        this.setResizable(false);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLocationRelativeTo(null);
    }

    public EmployeeSignIn() {
        this.initComponent();
        this.addComponentsToPanel();
        this.addPanelsToWindow();
        this.registerListeners();
        this.setWindowProperties();
    }

    private boolean validateFields() {
        if (!textFieldCheck(txtUsername)) {
            txtUsername.grabFocus();
            System.out.println(1);
            System.out.println("Please enter your username");
            System.out.println(2);
            return false;
        }

        if (!textFieldCharacterCheck(txtUsername)) {
            txtUsername.grabFocus();
            System.out.println("No Special Characters Allowed in Username!");
            return false;
        }

        if (!passwordFieldCheck(jpfPassword)) {
            jpfPassword.grabFocus();
            System.out.println("Please Enter your Password!");
            return false;
        }
        return true;
    }

    private boolean textFieldCheck(JTextField field) {
        if (field.getText().trim().isEmpty()) {
            field.grabFocus();
            return false;
        }
        return true;
    }

    private boolean passwordFieldCheck(JPasswordField field) {
        String password = new String(field.getPassword());
        if (password.trim().isEmpty()) {
            return false;
        }
        return true;
    }

    private boolean textFieldCharacterCheck(JTextField field) {
        return field.getText().matches("^\\d+$");
    }

    public String getUsername() {
        return txtUsername.getText();
    }

    public String getPassword() {
        return new String(jpfPassword.getPassword());
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        JButton src = (JButton) e.getSource();

        new Thread() {
            @Override
            public void run() {
                if (src.equals(btnSubmit)) {
                    if (validateFields()) {
                        sendStreamsToServer();
                    }
                }
            }
        }.start();
    }

    private void sendStreamsToServer() {
        try {

            String userType = "employee";
            oos.writeObject(userType);

            oos.writeObject(this.getUsername());
            System.out.println("USERNAME: " + this.getUsername());
            oos.writeObject(this.getPassword());
            System.out.println("PASSWORD: " + this.getPassword());

            String readObj = (String) ois.readObject();
            System.out.println("READ OBJECT: " + readObj);

            boolean validationCheck = (boolean) ois.readObject();
            System.out.println("Employee/VALIDATION CHECK: " + validationCheck);

        } catch (IOException e1) {
            System.err.println(e1.getMessage());
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private void closeConnection() {
        try {
            oos.close();
            ois.close();
        } catch (IOException e) {
            System.err.println(e.getMessage());
        }
    }

    public static void main(String[] args) {
        new EmployeeSignIn();
    }
}


问:
wxWidgets include files all in same folder?
I'm on a Xubuntu machine. I've downloaded and compiled the source, did the make install.

I'm trying to create a simple wxFrame class, but when I include <wx-3.0/wx/frame.h>, it says Can't resolve type wxFrame. When I look inside frame.h, it includes a reference to <wx/toplevel.h>. Both frame.h and toplevel.h are in the same folder. Why does the compilation place the include files all in the same folder, but the paths to the files are different?

I am using CLion IDE and the include/lib paths are set by cmake's FIND_PACKAGE().

答:
@ShrimpCrackers,

It is generally advisable to start you project by copying one of the sample code into you project and then set you project properties to the output of wx-config --cxxflags and wx-config --libs.

So what you should do is to copy the wxWidgets/samples/minimal/minimal.cpp over to the directory where you project is, fix the project properties and recompile.

BTW, you don't have to do make install. You might want to compile debug and release versions of the library on one machine which defeats the purpose of installing. You just use the compiled version of the library


问:
How to Combine CSS in one class make usable for Blogger template
I'm trying to create a text box mixture of HTML/CSS. I have CSS code for designing of text box. I want to use this code in blogger but I'm unable to combine the CSS in one class so that use in blogger. Someone help me please. Thanks.

CSS and HTML:

body {
 background-color: #f1f1f1;
 font-family: Helvetica,Arial,Verdana;
}
.link-box,.link-wrapper {
 position: relative;
 padding: 10px;
}
.link-wrapper {
 width: 500px;
 margin: auto;
 margin-top: 50px;
}
.link-box {
 width: 80%;
 border: 1px solid #ccc;
  outline: 0;
  border-radius: 15px;
}
.link-box:focus {
 box-shadow: 0 0 15px 5px #b0e0ee;
 border: 1px solid #0AA700;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="link-wrapper">
 <input type="text" onClick="this.select();" name="focus" required class="link-box" value="www.google.com"  readonly/>
</div></code>```

答:
Not entirely what you mean by one class. But if you mean you can only have a class on the parent div and not on the input, this would work.</p>

```<code>.link-wrapper {
  position: relative;
  width: 500px;
  margin: auto;
  margin-top: 50px;
  padding: 10px;
}
.link-wrapper input {
  width: 80%;
  border: 1px solid #ccc;
  outline: 0;
  border-radius: 15px;
  padding: 10px;
}
.link-wrapper input:focus {
  box-shadow: 0 0 15px 5px #b0e0ee;
  border: 1px solid #0AA700;
}
</code>```

Body:
I'm trying to create a text box mixture of HTML/CSS. I have CSS code for designing of text box. I want to use this code in blogger but I'm unable to combine the CSS in one class so that use in blogger. Someone help me please. Thanks.

CSS and HTML:

body {
 background-color: #f1f1f1;
 font-family: Helvetica,Arial,Verdana;
}
.link-box,.link-wrapper {
 position: relative;
 padding: 10px;
}
.link-wrapper {
 width: 500px;
 margin: auto;
 margin-top: 50px;
}
.link-box {
 width: 80%;
 border: 1px solid #ccc;
  outline: 0;
  border-radius: 15px;
}
.link-box:focus {
 box-shadow: 0 0 15px 5px #b0e0ee;
 border: 1px solid #0AA700;
}

 <input type="text" onClick="this.select();" name="focus" required class="link-box" value="www.google.com"  readonly/>

Body:
Not entirely what you mean by one class. But if you mean you can only have a class on the parent div and not on the input, this would work.

.link-wrapper {
  position: relative;
  width: 500px;
  margin: auto;
  margin-top: 50px;
  padding: 10px;
}
.link-wrapper input {
  width: 80%;
  border: 1px solid #ccc;
  outline: 0;
  border-radius: 15px;
  padding: 10px;
}
.link-wrapper input:focus {
  box-shadow: 0 0 15px 5px #b0e0ee;
  border: 1px solid #0AA700;
}


问:
Convert vb.net static method call on object
I am having more problems with my converting of vb.net to c#.net.

I have some files in vb.net that have "Option Strict Off" to allow for bad programming.  When I convert to c# I use "dynamic" until I come back and fix problems, and this works in all cases

But now I have this code:

```<code>Public Class ContractResults
   'Big class definition
   Public Shared Sub CleanCache()
       'Code here
   End Sub
End Class
</code>```

And in a file with Option Strict Off:

```<code>Public Sub VerifyResults(result as Object)
   'Here, result is normally ContractResults
   'first it check for that then call this:
   result.CleanCache()
End Sub
</code>```

In c# I use "dynamic", but a runtime error pops up when I call "static" method with dynamic reference.  In vb.net, I can called "shared" sub from instance, but in c# this is not allowed

Exception:
   "Microsoft.CSharp.RuntimeBinder.RuntimeBinderException"
   "Member 'ContractTypes.ContractResults.CleanCache()' cannot be accessed with an instance reference; qualify it with a type name instead"

It seems I must convert code to use actual type, but then this means much rewriting of more parts.  Is anyone able to show another way?

I want to make sure you do not think I can use

```<code>(result as ContractResults).CleanCache();
</code>```

Because all types that may be passed in have "CleanCache()" method, but do not inherits from anything the same other than "Object".  There are many types (30!) that have this "static" method and so that is why it uses Option Strict Off

答:
You could use reflection:

```<code>result.GetType().InvokeMember("CleanCache", BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy, null, null, new object[0]);
</code>```

(untested)

ContentLicense: CC BY-SA 2.5

Body:
I am having more problems with my converting of vb.net to c#.net.

I have some files in vb.net that have "Option Strict Off" to allow for bad programming.  When I convert to c# I use "dynamic" until I come back and fix problems, and this works in all cases

But now I have this code:

Public Class ContractResults
   'Big class definition
   Public Shared Sub CleanCache()
       'Code here
   End Sub
End Class

And in a file with Option Strict Off:

Public Sub VerifyResults(result as Object)
   'Here, result is normally ContractResults
   'first it check for that then call this:
   result.CleanCache()
End Sub

In c# I use "dynamic", but a runtime error pops up when I call "static" method with dynamic reference.  In vb.net, I can called "shared" sub from instance, but in c# this is not allowed

Exception:
   "Microsoft.CSharp.RuntimeBinder.RuntimeBinderException"
   "Member 'ContractTypes.ContractResults.CleanCache()' cannot be accessed with an instance reference; qualify it with a type name instead"

It seems I must convert code to use actual type, but then this means much rewriting of more parts.  Is anyone able to show another way?

I want to make sure you do not think I can use

(result as ContractResults).CleanCache();

Because all types that may be passed in have "CleanCache()" method, but do not inherits from anything the same other than "Object".  There are many types (30!) that have this "static" method and so that is why it uses Option Strict Off

Body:
You could use reflection:

result.GetType().InvokeMember("CleanCache", BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy, null, null, new object[0]);

(untested)


问:
Failed import of Mapbox features, trying to make a Geocoding Autocomplete query
Let me explain my issue.
I am really newbie in terms of Mapbox handling, but however im getting really good experiences with it. Today, I got an issue which I couldn't solve for hours and hours, which is related to some imports I fail to get from mapbox android services library.

I am compiling the following services in my build.gradle file:

```<code>compile('com.mapbox.mapboxsdk:mapbox-android-sdk:5.0.1@aar') {
    transitive=true
}
compile ('com.mapbox.mapboxsdk:mapbox-android-geocoder:1.0.+@aar'){
    transitive=true
}
compile ('com.mapbox.mapboxsdk:mapbox-android-services:2.0.0-beta.1@aar'){
    transitive=true
}
</code>```

And everything works fine with the map, it shows me the map, I can add markers, modify parameters, and more stuff. My problem is, that when I try to make a geocoding automatic-fill query, the following lines in the import section are marked in grey and for no apparent reason, the imports aren't being done correctly.

```<code>import com.mapbox.services.android.geocoder.ui.GeocoderAutoCompleteView;
import com.mapbox.services.geocoding.v5.GeocodingCriteria;
import com.mapbox.services.geocoding.v5.models.CarmenFeature;
</code>```

So, in the call into the java class, i'm getting a few errors related to lack of references.

```<code>// Set up autocomplete widget
GeocoderAutoCompleteView autocomplete = (GeocoderAutoCompleteView) findViewById(R.id.query);
autocomplete.setAccessToken(MapboxAccountManager.getInstance().getAccessToken());
autocomplete.setType(GeocodingCriteria.TYPE_POI);
autocomplete.setOnFeatureListener(new GeocoderAutoCompleteView.OnFeatureListener() {
    @Override
    public void OnFeatureClick(CarmenFeature feature) {
        Position position = feature.asPosition();
        updateMap(position.getLatitude(), position.getLongitude());
    }
});
</code>```

Any idea? Thank you in advance!

答:
Have a look at the new documentation for the geocoding widget along with the getting started guide. This should be your XML file:

```<code><com.mapbox.services.android.ui.geocoder.GeocoderAutoCompleteView
</code>```

android:id="@+id/autoCompleteWidget"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:hint="Search Location"
  android:maxLines="1"/>

Also you should upgrade to not using the beta. Stable 2.0.0 has been released.

Body:
Let me explain my issue.
I am really newbie in terms of Mapbox handling, but however im getting really good experiences with it. Today, I got an issue which I couldn't solve for hours and hours, which is related to some imports I fail to get from mapbox android services library.

I am compiling the following services in my build.gradle file:

compile('com.mapbox.mapboxsdk:mapbox-android-sdk:5.0.1@aar') {
    transitive=true
}
compile ('com.mapbox.mapboxsdk:mapbox-android-geocoder:1.0.+@aar'){
    transitive=true
}
compile ('com.mapbox.mapboxsdk:mapbox-android-services:2.0.0-beta.1@aar'){
    transitive=true
}

And everything works fine with the map, it shows me the map, I can add markers, modify parameters, and more stuff. My problem is, that when I try to make a geocoding automatic-fill query, the following lines in the import section are marked in grey and for no apparent reason, the imports aren't being done correctly.

import com.mapbox.services.android.geocoder.ui.GeocoderAutoCompleteView;
import com.mapbox.services.geocoding.v5.GeocodingCriteria;
import com.mapbox.services.geocoding.v5.models.CarmenFeature;

So, in the call into the java class, i'm getting a few errors related to lack of references.

// Set up autocomplete widget
GeocoderAutoCompleteView autocomplete = (GeocoderAutoCompleteView) findViewById(R.id.query);
autocomplete.setAccessToken(MapboxAccountManager.getInstance().getAccessToken());
autocomplete.setType(GeocodingCriteria.TYPE_POI);
autocomplete.setOnFeatureListener(new GeocoderAutoCompleteView.OnFeatureListener() {
    @Override
    public void OnFeatureClick(CarmenFeature feature) {
        Position position = feature.asPosition();
        updateMap(position.getLatitude(), position.getLongitude());
    }
});

Any idea? Thank you in advance!

Body:
Have a look at the new documentation for the geocoding widget along with the getting started guide. This should be your XML file:

<com.mapbox.services.android.ui.geocoder.GeocoderAutoCompleteView

android:id="@+id/autoCompleteWidget"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:hint="Search Location"
  android:maxLines="1"/>

Also you should upgrade to not using the beta. Stable 2.0.0 has been released.


问:
the auto urldecode in apache mod_rewrite
this is my apache .htaccess setting with a search page redirect

(RewriteRule ^search/(.*)$ /index.php?c=index&m=search&keywords=$1 [L,QSA]),

if I set the search query in url without %, it works success request without '%' but if a % char added to the string, apache with return a bad request with % , howerver instead of adding % but %25, the urlencoded string of %, success request when pre encode % to %25

I want to know about the reason of this situation. I guess in the RewriteRule of .htaccess an urldecode function worked from Pattern to Substitution, that's why % char cannot be recognized by the server, but %25 can. How can I disable this urldecode function?

答:
Because the percent ("%") character serves as the indicator for percent-encoded octets, it must be percent-encoded as "%25" for that octet to be used as data within a URI (RFC 3986)

I think it's because Apache follows the standards, mod_rewrite has to unescape URLs before mapping them.. (https://httpd.apache.org/docs/current/rewrite/flags.html#flag_b)

Easy workaround for "disable" auto url decoding is to use Server-Variables like REQUEST_URI or THE_REQUEST in RewriteCond Directive (http://httpd.apache.org/docs/current/mod/mod_rewrite.html#RewriteCond)

```<code>RewriteEngine on
RewriteCond %{REQUEST_URI} /search/(.*)
RewriteRule . test.php?c=index&m=search&keywords=%1 [L,QSA]
</code>```

If you use REQUEST_URI, in PHP you must use $_SERVER['REQUEST_URI']. Do not use $_SERVER['QUERY_STRING'] or $_GET, otherwise you will get the decoded url.
If you want all $_SERVER doing what you need, use THE_REQUEST instead:

```<code>RewriteEngine on
RewriteCond %{THE_REQUEST} \s/search/([^\s]*)
RewriteRule . test.php?c=index&m=search&keywords=%1 [L,QSA]
</code>```

And we just need to put . (dot) in RewriteRule pattern and use %1 instead of $1

Body:
Because the percent ("%") character serves as the indicator for percent-encoded octets, it must be percent-encoded as "%25" for that octet to be used as data within a URI (RFC 3986)

I think it's because Apache follows the standards, mod_rewrite has to unescape URLs before mapping them.. (https://httpd.apache.org/docs/current/rewrite/flags.html#flag_b)

Easy workaround for "disable" auto url decoding is to use Server-Variables like REQUEST_URI or THE_REQUEST in RewriteCond Directive (http://httpd.apache.org/docs/current/mod/mod_rewrite.html#RewriteCond)

RewriteEngine on
RewriteCond %{REQUEST_URI} /search/(.*)
RewriteRule . test.php?c=index&m=search&keywords=%1 [L,QSA]

If you use REQUEST_URI, in PHP you must use $_SERVER['REQUEST_URI']. Do not use $_SERVER['QUERY_STRING'] or $_GET, otherwise you will get the decoded url.
If you want all $_SERVER doing what you need, use THE_REQUEST instead:

RewriteEngine on
RewriteCond %{THE_REQUEST} \s/search/([^\s]*)
RewriteRule . test.php?c=index&m=search&keywords=%1 [L,QSA]

And we just need to put . (dot) in RewriteRule pattern and use %1 instead of $1


问:
transfer data from fragment A -> fragment B - > fragment C. When user click Back button, I want to return to fragment A and data
I'm a newbie in android developer. I have a question about transfer with 3 fragments.

I have 3 fragments (A - B - C). I want o transfer data from A -> B -> C.

In each the fragment, data was been changed.
When user click BACK BUTTON, user want to return A with the updated data.
How to return fragment A with the update data?
Thanks.

答:
You can use Interface class to communicate between fragment but it must make sure all the fragment is alive.

You can use SharedPreferences where you can save the data and retrieve it anywhere you like


问:
Printing multiple lines with the same "largest" value using awk
I have a file that looks like this:

```<code>3, abc, x
2, def, y
3, ghi, z
</code>```

I want to find the highest value in $1 and print all rows that contain this highest value in $1.

```<code>sort -t, -k1,1n| tail -n1
</code>```

would just give one of the rows that contain 3 in $1, but I need both.

Any suggestions are appreciated (:

答:
In awk, only one pass over the data:</p>

```<code>$ awk -F, '
$1>m {                   # when new max is found
    delete a; m=$1; i=0  # reset all
}
a[1]=="" || $1==m {      # if $1 equals max or we're processing the first record
    a[++i]=$0            # store the record to a
}
END {                    # in the end
    for(j=1;j<=i;j++)
        print a[j]       # print a with stored records
}
' file
3, abc, x
3, ghi, z
</code>```

Body:
I have a file that looks like this:

3, abc, x
2, def, y
3, ghi, z

I want to find the highest value in $1 and print all rows that contain this highest value in $1.

sort -t, -k1,1n| tail -n1

would just give one of the rows that contain 3 in $1, but I need both.

Any suggestions are appreciated (:

Body:
In awk, only one pass over the data:

$ awk -F, '
$1>m {                   # when new max is found
    delete a; m=$1; i=0  # reset all
}
a[1]=="" || $1==m {      # if $1 equals max or we're processing the first record
    a[++i]=$0            # store the record to a
}
END {                    # in the end
    for(j=1;j<=i;j++)
        print a[j]       # print a with stored records
}
' file
3, abc, x
3, ghi, z


问:
execute javascript after focused on an element
I need to run execFunc(); not only when the user moves onto the next field, but also runs when the user remains focused on the same field for 5 seconds.

```<code>$('input[name="email"]').bind('blur', function () {
 execFunc();
});
</code>```

答:
This should suffice</p>

```<code>var g_timeout = null;

$('input[name="email"]')
      .blur(function () {
           execFunc();
      })
      .focus(function(){
           if (g_timeout) clearTimeout(g_timeout);
           g_timeout= setTimeout(execFunc, 5000);
      });
</code>```

Body:
I need to run execFunc(); not only when the user moves onto the next field, but also runs when the user remains focused on the same field for 5 seconds.

$('input[name="email"]').bind('blur', function () {
 execFunc();
});

Body:
This should suffice

var g_timeout = null;

$('input[name="email"]')
      .blur(function () {
           execFunc();
      })
      .focus(function(){
           if (g_timeout) clearTimeout(g_timeout);
           g_timeout= setTimeout(execFunc, 5000);
      });


问:
xpath union operator with VTD XML Parser
Can someone please post an example for using union operator (|) with VTD XML parser ?
Below is not working in VTD XML parser but works in jxpath parser.
/a | /b</p>

答:
Ok, this is a quick example of union expression in action.</p>

```<code>import com.ximpleware.AutoPilot;
import com.ximpleware.NavException;
import com.ximpleware.VTDException;
import com.ximpleware.VTDGen;
import com.ximpleware.VTDNav;

/**
 * An issue that seems to exist in VTD-XML 2.12 and 2.13 (but not 2.11) that causes lookups for default namespace nodes
 * to also pickup non-default namespaced nodes.
 */
public class VtdAutoPilotXpathIssueTest {

  private static final String XML = "<a xmlns:x=\"" + "urn:test" + "\"><b id=\"1\"/><x:b id=\"2\"/><b id=\"3\"/></a>";
  public static void main(String[] s) throws VTDException{
      VTDGen vg = new VTDGen();
      vg.setDoc(XML.getBytes());
      vg.parse(false);
      VTDNav vn = vg.getNav();
      AutoPilot ap = new AutoPilot(vn);
      ap.declareXPathNameSpace("abc", "urn:test");
      ap.selectXPath("//b|/a");
      int i=0;
      while((i=ap.evalXPath())!=-1){
          System.out.println(" token "+ vn.toRawString(i));
      }
  }
}
</code>```

Body:
Ok, this is a quick example of union expression in action.

import com.ximpleware.AutoPilot;
import com.ximpleware.NavException;
import com.ximpleware.VTDException;
import com.ximpleware.VTDGen;
import com.ximpleware.VTDNav;

/**
 * An issue that seems to exist in VTD-XML 2.12 and 2.13 (but not 2.11) that causes lookups for default namespace nodes
 * to also pickup non-default namespaced nodes.
 */
public class VtdAutoPilotXpathIssueTest {

  private static final String XML = "<a xmlns:x=\"" + "urn:test" + "\"><b id=\"1\"/><x:b id=\"2\"/><b id=\"3\"/></a>";
  public static void main(String[] s) throws VTDException{
      VTDGen vg = new VTDGen();
      vg.setDoc(XML.getBytes());
      vg.parse(false);
      VTDNav vn = vg.getNav();
      AutoPilot ap = new AutoPilot(vn);
      ap.declareXPathNameSpace("abc", "urn:test");
      ap.selectXPath("//b|/a");
      int i=0;
      while((i=ap.evalXPath())!=-1){
          System.out.println(" token "+ vn.toRawString(i));
      }
  }
}


问:
AngularJs plunker not working? New to Plunker
I am relatively new to plunker, what am I doing wrong? There are errors in the console, and the live preview is not working. The code works perfectly fine in my localhost.

Here's the link for it. http://plnkr.co/edit/cZ48oeBBDthtVqXMRJPy?p=preview

```<code>    <html ng-app="myApp">

  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.1/angular.min.js"></script>
    <script data-require="jquery@*" data-semver="3.1.1" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script data-require="less.js@*" data-semver="2.6.1" src="https://cdnjs.cloudflare.com/ajax/libs/less.js/2.6.1/less.min.js"></script>
    <link rel="stylesheet" href="style.less" />
    <script src="script.js"></script>
  </head>

  <body ng-controller="mainCtrl">
    <div class="container">
      <!-- Parent scope -->
      <div class="">
        <div prevent="" visible="isVisible" object-data="objectData">
          <table class="datatable">
            <tbody>
              <tr ng-repeat="t in templateData">
                <td class="haseebtesting" ng-click="current.selected = t; confusedFunction(t)" id="{{'test ' + $index}}">{{t.templateName}}</td>
                <td>{{t.templatePath}}</td>
              </tr>
            </tbody>
          </table>
          <div ng-show="isVisible" class="parented">
            <form class="haseebform">
              <input type="text" ng-model="objectData.entername" placeholder="Enter name" />
              <br />
              <input type="text" ng-model="objectData.entercomment" placeholder="Enter comment" />
              <input type="button" class="btn btn-info" ng-click="addT(objectData)" value="Submit" />
            </form>
          </div>
        </div>
      </div>
    </div>
    <script src="script.js"></script>
  </body>

</html>
</code>```

答: You need to move the jquery script above the angular script. When angular loads, if jquery is not present,  jqlite is used instead even if jquery is loaded subsequently.</p>

Body:
I am relatively new to plunker, what am I doing wrong? There are errors in the console, and the live preview is not working. The code works perfectly fine in my localhost.

Here's the link for it. http://plnkr.co/edit/cZ48oeBBDthtVqXMRJPy?p=preview

    <link rel="stylesheet" href="style.less" />

                {{t.templateName}}
                {{t.templatePath}}

            <form class="haseebform">
              <input type="text" ng-model="objectData.entername" placeholder="Enter name" />

              <input type="text" ng-model="objectData.entercomment" placeholder="Enter comment" />
              <input type="button" class="btn btn-info" ng-click="addT(objectData)" value="Submit" />
            </form>


问:
selecting all wpf datagrid checkboxes only selects items in view
I have the following method to select all the checkboxes within my datagrid:

```<code>   private void CheckboxSelectAll(int column)
    {

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

            var row = (DataGridRow)dGrid.ItemContainerGenerator.ContainerFromIndex(i);

            if (row == null) continue;
            var chk = (System.Windows.Controls.CheckBox)dGrid.Columns[column].GetCellContent(row);
            chk.IsChecked = true;
        }
    }
</code>```

This only works so long as all the columns are in view. If, for example, the amount of checkboxes exceeds the height of the datagrid, it will not select those. I will have to scroll down, expose them to the view, and then reinvoke my method to finally select the remaining checkboxes.

What am I missing? These checkboxes are already databound.

If I change the height of the datagrid to expose more checkboxes, this allows me to select more. This is only a workaround and I would like to understand why and what about my code makes the checkboxes being exposed to the view important.

答:
The solution can be found here:

WPF Toolkit DataGrid Checkbox Issues

The solution is to disable RowVirtualization

```<code>EnableRowVirtualization="False"
</code>```

Body:
I have the following method to select all the checkboxes within my datagrid:

   private void CheckboxSelectAll(int column)
    {

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

            var row = (DataGridRow)dGrid.ItemContainerGenerator.ContainerFromIndex(i);

            if (row == null) continue;
            var chk = (System.Windows.Controls.CheckBox)dGrid.Columns[column].GetCellContent(row);
            chk.IsChecked = true;
        }
    }

This only works so long as all the columns are in view. If, for example, the amount of checkboxes exceeds the height of the datagrid, it will not select those. I will have to scroll down, expose them to the view, and then reinvoke my method to finally select the remaining checkboxes.

What am I missing? These checkboxes are already databound.

If I change the height of the datagrid to expose more checkboxes, this allows me to select more. This is only a workaround and I would like to understand why and what about my code makes the checkboxes being exposed to the view important.

Body:
The solution can be found here:

WPF Toolkit DataGrid Checkbox Issues

The solution is to disable RowVirtualization

EnableRowVirtualization="False"


问:
Why is my ListBox8.value listed as Null?
When using a ComboBox the code worked perfectly, but when using ListBox the C variable is set to null even when a value is selected. I receive an error message "Invalid use of Null".

I need a ListBox because I need to select multiple values from the drop down.

Any help would be much appreciated I have been banging my head about this for most of the day.

```<code>Public Sub CommandButton1_Click()

    Dim C As String
    Dim LastTarget As range
    Dim LastTarget2 As range

    Set LastTarget = ActiveCell
    Set LastTarget2 = ActiveCell.Offset(0, 3)

    Set wb1 = Workbooks("Premium Billing Report TemplateListBox.xlsm")

    'LastRow = wb1.Sheets("CGIBill").range("A:A").Find("Overall - Total", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

    C = ListBox8.value

    'For i = 11 To LastRow

    'Counts & Coverages based on plan code selection
    LastTarget = Application.CountIf(wb1.Sheets("Carrier").range("BG:BG"), C)
    LastTarget2 = Application.SumProduct(Application.SumIf(wb1.Sheets("Carrier").range("BG:BG"), C, wb1.Sheets("Carrier").range("BK:BK")))

    'Next

    Unload Me

End Sub
</code>```

With Sheets("Carrier").range("BG10:BG10000") v = .value End With With CreateObject("scripting.dictionary") .comparemode = 1 For Each e In v If Not .exists(e) Then .Add e, Nothing Next If .Count Then Me.ListBox8.List = Application.Transpose(.keys) End With

答:
This little snippet will get around the error:</p>

```<code>If IsNull(ListBox8.Value) Then
C = ""
Else

C = CStr(ListBox8.Value)
End If
</code>```

Body:
When using a ComboBox the code worked perfectly, but when using ListBox the C variable is set to null even when a value is selected. I receive an error message "Invalid use of Null".

I need a ListBox because I need to select multiple values from the drop down.

Any help would be much appreciated I have been banging my head about this for most of the day.

Public Sub CommandButton1_Click()

    Dim C As String
    Dim LastTarget As range
    Dim LastTarget2 As range

    Set LastTarget = ActiveCell
    Set LastTarget2 = ActiveCell.Offset(0, 3)

    Set wb1 = Workbooks("Premium Billing Report TemplateListBox.xlsm")

    'LastRow = wb1.Sheets("CGIBill").range("A:A").Find("Overall - Total", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

    C = ListBox8.value

    'For i = 11 To LastRow

    'Counts & Coverages based on plan code selection
    LastTarget = Application.CountIf(wb1.Sheets("Carrier").range("BG:BG"), C)
    LastTarget2 = Application.SumProduct(Application.SumIf(wb1.Sheets("Carrier").range("BG:BG"), C, wb1.Sheets("Carrier").range("BK:BK")))

    'Next

    Unload Me

End Sub

With Sheets("Carrier").range("BG10:BG10000") v = .value End With With CreateObject("scripting.dictionary") .comparemode = 1 For Each e In v If Not .exists(e) Then .Add e, Nothing Next If .Count Then Me.ListBox8.List = Application.Transpose(.keys) End With

Body:
This little snippet will get around the error:

If IsNull(ListBox8.Value) Then
C = ""
Else

C = CStr(ListBox8.Value)
End If


问:
REST API : Passing Colon (:) in url using attribute Routing doesn't work
I am using swagger ui to test a POST method. I am passing the parameter in URL but it doesn't work.

swagger-ui:

I enter this
 Date: 2017-03-03T12:12:12
 this is how it goes
  in
 url: https://servername/Results/2017-03-03T12%3A12%3A12

 This doesn't work. it return 404 error

but when i pass just the date it works.

Date: 2017-03-03

my method:

[Route("{Results/{date}"), HttpPost]
 public
  Common.CallDetails StartTCISCall(DateTime date)

I have tried this also but it doesn't even catch it as a string.

[Route("{Results/{*date}"), HttpPost]
 public
  Common.CallDetails StartTCISCall(string date)

as soon as i take the colons out it starts to work. What can i do?

Also, for my friend it works locally on VS but when he publishes to IIS it doesn't work and we tried 3 different servers. Why is this?

Many thanks, Please help.

答:
It turns out that it was an IIS issue where the server is configured to deny : or % so that's why the encoded URL wasn't getting through either.

After changing the settings on IIS it works.

I hope this helps!


问:
Save DOM as xml in a file with javascript
In my javascript I have the following:

```<code>let person = document.createElement('person');
let name = document.createElement('name');
let surname = document.createElement('surname');
person.appendChild(name);
person.appendChild(surname);

let xml = person;
</code>```

How do I save my "xml" variable in a file (using javascript only)?
OBS: The content should not be presented in a single line, but in the tree structure:

```<code><person>
    <name></name>
    <surname></surname>
</person>
</code>```

答:
You can use .outerHTML to get string containing person node and child nodes, data URI representation of file, set a href of  element with download attribute set.

let person = document.createElement('person');
let name = document.createElement('name');
let surname = document.createElement('surname');
person.appendChild(name);
person.appendChild(surname);

let xml = `data:application/xml,<?xml version="1.0" encoding="UTF-8"?>${encodeURIComponent(person.outerHTML)}`;

console.log(person, xml);

window.onload = () => {
  let a = document.createElement("a");
  let filename = "xmlfile.xml";
  a.download = a.textContent =  "xmlfile.xml";
  a.href = xml;
  document.body.appendChild(a);
}```
</div>
</div>
</p>

<p>You can alternatively create a <code>Blob</code> or <code>File</code> instance representing <code>XML</code> data</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let person = document.createElement('person');
let name = document.createElement('name');
let surname = document.createElement('surname');
person.appendChild(name);
person.appendChild(surname);

let xml = `<?xml version="1.0" encoding="UTF-8"?>${person.outerHTML}`;

let file = new File([xml]
           , "xmlfile.xml", {type:"application/xml"});

console.log(person, xml, file);

let url;

window.onload = () => {
  let a = document.createElement("a");
  let filename = "xmlfile.xml";
  a.download = a.textContent =  "xmlfile.xml";
  url = URL.createObjectURL(file);
  a.href = url;
  document.body.appendChild(a);
  a.onclick = () => {
    window.onfocus = () => {
      window.onfocus = null;
      URL.revokeObjectURL(url);
      if ("close" in file && !file.isClosed) file.close();
    }
  }
}</code>```

See also How to download a file without using  element with download attribute or a server?

Body:
In my javascript I have the following:

let person = document.createElement('person');
let name = document.createElement('name');
let surname = document.createElement('surname');
person.appendChild(name);
person.appendChild(surname);

let xml = person;

How do I save my "xml" variable in a file (using javascript only)?
OBS: The content should not be presented in a single line, but in the tree structure:

<person>
    <name></name>
    <surname></surname>
</person>

Body:
You can use .outerHTML to get string containing person node and child nodes, data URI representation of file, set a href of <a> element with download attribute set.

let person = document.createElement('person');
let name = document.createElement('name');
let surname = document.createElement('surname');
person.appendChild(name);
person.appendChild(surname);

let xml = `data:application/xml,<?xml version="1.0" encoding="UTF-8"?>${encodeURIComponent(person.outerHTML)}`;

console.log(person, xml);

window.onload = () => {
  let a = document.createElement("a");
  let filename = "xmlfile.xml";
  a.download = a.textContent =  "xmlfile.xml";
  a.href = xml;
  document.body.appendChild(a);
}

You can alternatively create a Blob or File instance representing XML data

let person = document.createElement('person');
let name = document.createElement('name');
let surname = document.createElement('surname');
person.appendChild(name);
person.appendChild(surname);

let xml = `<?xml version="1.0" encoding="UTF-8"?>${person.outerHTML}`;

let file = new File([xml]
           , "xmlfile.xml", {type:"application/xml"});

console.log(person, xml, file);

let url;

window.onload = () => {
  let a = document.createElement("a");
  let filename = "xmlfile.xml";
  a.download = a.textContent =  "xmlfile.xml";
  url = URL.createObjectURL(file);
  a.href = url;
  document.body.appendChild(a);
  a.onclick = () => {
    window.onfocus = () => {
      window.onfocus = null;
      URL.revokeObjectURL(url);
      if ("close" in file && !file.isClosed) file.close();
    }
  }
}

See also How to download a file without using <a> element with download attribute or a server?


答:
This will do it, assuming that you can load the data from your first query into a intermediate temporary table:</p>

```<code>DECLARE @t TABLE
    (
      ProductClass INT
    , InspectDays INT
    , ProcessDays INT
    , ShipDays INT
    )

INSERT  INTO @t
        SELECT  1
              , 2
              , 4
              , 8
        UNION ALL
        SELECT  1
              , 4
              , 5
              , 2
        UNION ALL
        SELECT  5
              , 2
              , 4
              , 8
        UNION ALL
        SELECT  10
              , 3
              , 5
              , 2

SELECT  'Avg Inspect'
      , [01] = AVG(CASE WHEN ProductClass = 1 THEN InspectDays
                   END)
      , [05] = AVG(CASE WHEN ProductClass = 5 THEN InspectDays
                   END)
      , [10] = AVG(CASE WHEN ProductClass = 10 THEN InspectDays
                   END)
FROM    @t
UNION ALL
SELECT  'Avg Process'
      , [01] = AVG(CASE WHEN ProductClass = 1 THEN ProcessDays
                   END)
      , [05] = AVG(CASE WHEN ProductClass = 5 THEN ProcessDays
                   END)
      , [10] = AVG(CASE WHEN ProductClass = 10 THEN ProcessDays
                   END)
FROM    @t
</code>```

Title: How to Pivot/Unpivot Something with SQL2000

Body:
I'm querying a table which essentially a bunch of dates.

FRECDCUST              DTRECDCUST              DTINSPECTED             DTRECDCUSTPO           DTADDEDSO                 DTSHIPPEDSUP                  DTQUOTEDCUST
1/1/1900 12:00:00 AM    7/27/2010 12:00:00 AM   7/30/2010 12:00:00 AM   7/26/2010 12:00:00 AM   8/6/2010 12:00:00 AM    1/1/1900 12:00:00 AM    8/6/2010 12:00:00 AM
1/1/1900 12:00:00 AM    7/27/2010 12:00:00 AM   7/30/2010 12:00:00 AM   7/26/2010 12:00:00 AM   8/6/2010 12:00:00 AM    1/1/1900 12:00:00 AM    1/1/1900 12:00:00 AM
1/1/1900 12:00:00 AM    1/1/1900 12:00:00 AM    1/1/1900 12:00:00 AM    1/1/1900 12:00:00 AM    1/1/1900 12:00:00 AM    1/1/1900 12:00:00 AM    1/1/1900 12:00:00 AM
1/1/1900 12:00:00 AM    1/1/1900 12:00:00 AM    1/1/1900 12:00:00 AM    1/1/1900 12:00:00 AM    1/1/1900 12:00:00 AM    1/1/1900 12:00:00 AM    1/1/1900 12:00:00 AM
1/1/1900 12:00:00 AM    1/1/1900 12:00:00 AM    1/1/1900 12:00:00 AM    1/1/1900 12:00:00 AM    1/1/1900 12:00:00 AM    1/1/1900 12:00:00 AM    1/1/1900 12:00:00 AM
1/1/1900 12:00:00 AM    3/12/2010 12:00:00 AM   3/15/2010 12:00:00 AM   3/11/2010 12:00:00 AM   3/16/2010 12:00:00 AM   3/24/2010 12:00:00 AM   4/13/2010 12:00:00 AM
1/1/1900 12:00:00 AM    11/6/2009 12:00:00 AM   11/6/2009 12:00:00 AM   11/3/2009 12:00:00 AM   11/9/2009 12:00:00 AM   11/20/2009 12:00:00 AM  12/7/2009 12:00:00 AM

I am taking the date difference between two dates on each line. For example, the days to inspect is found like this:

SELECT (CASE
          WHEN year(SYC_ext.DTRECDCUST) <> 1900
               AND year(SYC_ext.DTINSPECTED) <> 1900
          THEN
            DATEDIFF(dd, SYC_ext.DTRECDCUST, SYC_ext.DTINSPECTED)
          ELSE
            NULL
        END)
         AS [AverageDaystoInspect]
Blah blah...

This creates a row of different DateDiff calcuations which end up looking like this:

Product Class   Average Days to Inspect Average Days to Process SO  Average Days to Ship to Affiliate   Average Days to Quote   Average Days to Receive Ammended PO
01  2   4   8   27  21
01  2   4   8   27  21
01  3   5   2   88  8
01  3   5   2   88  8
01  1   8   11  72  1
01  3   2   7   27  0
01  5   2   7   27  0

Please forgive the spacing problems.

So, each of these rows in the data set starts with a number which represents a product category in this case 01 and is followed by a series of day calculations.

I can average these values and give you an average for each category per product class. However, they want the day calculations along the left side of a table or matrix with the product classes along the top, exactly opposite of what I have here. If I pivot them in Excel, I get the following:

                          01    05     10
Avg Days to Inspect       5      3      5
Avg Days to Process PO    4      5      5
Avg Days to Ship          20     18     19

I hope this makes sense. Any idea how I can perform this in SSRS or t-sql?

Body:
This will do it, assuming that you can load the data from your first query into a intermediate temporary table:

DECLARE @t TABLE
    (
      ProductClass INT
    , InspectDays INT
    , ProcessDays INT
    , ShipDays INT
    )

INSERT  INTO @t
        SELECT  1
              , 2
              , 4
              , 8
        UNION ALL
        SELECT  1
              , 4
              , 5
              , 2
        UNION ALL
        SELECT  5
              , 2
              , 4
              , 8
        UNION ALL
        SELECT  10
              , 3
              , 5
              , 2

SELECT  'Avg Inspect'
      , [01] = AVG(CASE WHEN ProductClass = 1 THEN InspectDays
                   END)
      , [05] = AVG(CASE WHEN ProductClass = 5 THEN InspectDays
                   END)
      , [10] = AVG(CASE WHEN ProductClass = 10 THEN InspectDays
                   END)
FROM    @t
UNION ALL
SELECT  'Avg Process'
      , [01] = AVG(CASE WHEN ProductClass = 1 THEN ProcessDays
                   END)
      , [05] = AVG(CASE WHEN ProductClass = 5 THEN ProcessDays
                   END)
      , [10] = AVG(CASE WHEN ProductClass = 10 THEN ProcessDays
                   END)
FROM    @t


问:
OAuthException using Socialite with facebook - "message": "An active access token must be used to query information about the current user.",
I have been using Socialite for a few days with Facebook without issue. Today, I started getting this error.

```<code>{ "error":
    {
       "message": "An active access token must be used to query information
        about the current user.", "type": "OAuthException",
        "code": 2500, "fbtrace_id": "FTvIz9t1LT+"
   }
}
</code>```

The error seems straight forward but I can't seem to see a solution online. Is there a way to reset my access_token using Socialite.

Please note: I pretty much followed this tutorial

The error is in the callback when I try and get the

```<code>$userProvider try {
    $userProvider = Socialite::driver('facebook')->user();
} catch (Exception $e) {
   Log::info('Callback Error ' . $e->getMessage());
   return Redirect::to('redirect');
}
</code>```

Thanks, Rich

答:
It is because v2.2 of Facebook API is no longer available. Update the laravel/socialite package:

composer update laravel/socialite

This way it won't affect your other packages.

Body:
I have been using Socialite for a few days with Facebook without issue. Today, I started getting this error.

{ "error":
    {
       "message": "An active access token must be used to query information
        about the current user.", "type": "OAuthException",
        "code": 2500, "fbtrace_id": "FTvIz9t1LT+"
   }
}

The error seems straight forward but I can't seem to see a solution online. Is there a way to reset my access_token using Socialite.

Please note: I pretty much followed this tutorial

The error is in the callback when I try and get the

$userProvider try {
    $userProvider = Socialite::driver('facebook')->user();
} catch (Exception $e) {
   Log::info('Callback Error ' . $e->getMessage());
   return Redirect::to('redirect');
}

Thanks, Rich


问:
C2084 - function already has a body
I'm running into an error "C2084 - function 'void Pet::display(void)' already has a body". Error occurs on Dog.cpp file. Slightly confused about the issue. Any help would be appreciated.

Pet.h

```<code>#ifndef _PET_H_
#define _PET_H_

#include <string>
using namespace std;

enum Type { dog = 0, cat };

class Pet {
private:
    string name, breed; // private local variables
    Type type;

public:
    Pet(string pet_name, string pet_breed, Type pet_type); // constructor

    // accessor methods
    string getName();
    string getBreed();
    Type getType();

    virtual void display() {};
};

#endif // _PET_H_
</code>```

Dog.h

```<code>#ifndef _DOG_H_
#define _DOG_H_

#include "Pet.h"
#include <string>

using namespace std;

class Dog : public Pet {
public:
    Dog(string pet_name, string pet_breed, Type pet_type) : Pet(pet_name, pet_breed, pet_type) {
    } // constructor

    virtual void display() = 0;

};

#endif
</code>```

Dog.cpp

```<code>#include "Dog.h"
#include "Pet.h"
#include <iostream>

void Pet::display() {
    cout << "Name: " << name << endl;
    cout << "Breed: " << breed << endl;
    cout << "Type: Dog" << endl;
}
</code>```

答:
It seems that you wanted to define Dog::display and have forgotten to rename Pet to Dog:

```<code>void Dog::display() {
    cout << "Name: " << name << endl;
    cout << "Breed: " << breed << endl;
    cout << "Type: Dog" << endl;
}
</code>```

Also remove " = 0" from:

```<code>virtual void display() = 0;
</code>```

in "Dog.h".

In "Pet.h" file having " = 0" after function prototype is ok, it means that you shouldn't instantiate the Pet class directly (Abstract class).

Title: C2084 - function already has a body

Body:
I'm running into an error "C2084 - function 'void Pet::display(void)' already has a body". Error occurs on Dog.cpp file. Slightly confused about the issue. Any help would be appreciated.

Pet.h

#ifndef _PET_H_
#define _PET_H_

#include <string>
using namespace std;

enum Type { dog = 0, cat };

class Pet {
private:
    string name, breed; // private local variables
    Type type;

public:
    Pet(string pet_name, string pet_breed, Type pet_type); // constructor

    // accessor methods
    string getName();
    string getBreed();
    Type getType();

    virtual void display() {};
};

#endif // _PET_H_

Dog.h

#ifndef _DOG_H_
#define _DOG_H_

#include "Pet.h"
#include <string>

using namespace std;

class Dog : public Pet {
public:
    Dog(string pet_name, string pet_breed, Type pet_type) : Pet(pet_name, pet_breed, pet_type) {
    } // constructor

    virtual void display() = 0;

};

#endif

Dog.cpp

#include "Dog.h"
#include "Pet.h"
#include <iostream>

void Pet::display() {
    cout << "Name: " << name << endl;
    cout << "Breed: " << breed << endl;
    cout << "Type: Dog" << endl;
}

Body:
It seems that you wanted to define Dog::display and have forgotten to rename Pet to Dog:

void Dog::display() {
    cout << "Name: " << name << endl;
    cout << "Breed: " << breed << endl;
    cout << "Type: Dog" << endl;
}

Also remove " = 0" from:

virtual void display() = 0;

in "Dog.h".

In "Pet.h" file having " = 0" after function prototype is ok, it means that you shouldn't instantiate the Pet class directly (Abstract class).


问:
Winston logger.info is not a function
I've set up Winston with transports to MySQL and console and put it in a module called logger. Like so...

```<code>// modules/logger.js

/* require statements */

exports.logger = new (winston.Logger)({
    transports: [
        new winstonMysql(winstonMysqlConfig),
        new (winston.transports.Console)
    ]
});
</code>```

And then in /modules

```<code>// modules/index.js

/* grab other modules */

exports.logger = require('./logger.js');
</code>```

When I do console.log(modules.logger), I get this

```<code>{ logger:
    EventEmitter {
        ...
        error: [Function],
        warn: [Function],
        info: [Function],
        verbose: [Function],
        debug: [Function],
        silly: [Function],
        ...
    }
 }
</code>```

But when I call modules.logger.info() it throws modules.logger.info is not a function error. What's wrong?

答:
You aren't exporting the logger properly in modules.js.

```<code>exports.logger = require('./logger.js').logger;
</code>```

Title: Winston logger.info is not a function

Body:
I've set up Winston with transports to MySQL and console and put it in a module called logger. Like so...

// modules/logger.js

/* require statements */

exports.logger = new (winston.Logger)({
    transports: [
        new winstonMysql(winstonMysqlConfig),
        new (winston.transports.Console)
    ]
});

And then in /modules

// modules/index.js

/* grab other modules */

exports.logger = require('./logger.js');

When I do console.log(modules.logger), I get this

{ logger:
    EventEmitter {
        ...
        error: [Function],
        warn: [Function],
        info: [Function],
        verbose: [Function],
        debug: [Function],
        silly: [Function],
        ...
    }
 }

But when I call modules.logger.info() it throws modules.logger.info is not a function error. What's wrong?

Body:
You aren't exporting the logger properly in modules.js.

exports.logger = require('./logger.js').logger;


问:
VisualEditor in Java - dynamically build sub-panel?
I'm using the "Visual Editor" to "paint" my Swing GUI. Can I dynamically build the contents of a sub-panel with VE or do I have to use a predefined sub-class of JPanel (and build that with VE)?</p>

答:
You can dynamically build the contents of a sub panel - say based on a file or soemthing - the visual editor is not going to stop you.

Generally, VE is intelligent enough to see that you are dynamically build the panel and show the contents (say contents of a file in a JList)

Sometimes, VE fails to render the items because 'The control is too complex' - but this does not happen frequently.

OwnerDisplayName: IronGoofy

LastEditorDisplayName: IronGoofy

OwnerDisplayName: Nivas


问:
Most efficient/secure way to implement trial period in cocoa
I am finishing a Cocoa App which will use CocoaFob for licensing and I am wondering about the "most" efficient and secure way to implement a trial period in cocoa.

Thanks in advance for your help,

Regards,

答:
If your going to implement a time based demo consider using one based on processor time and not an absolute date.The idea being, the user can use your application fully for, say 4 hours, of CPU time. That way they are not locked into a 'must decide by date'. I often have downloaded soomething to look at, then later tried to really use it only to have the trial date expired.

It's not that hard to implement and I'm sure users would appreceiate more.


问:
textAlignent to right in cellForRowAt in Swift 3.0
I cannot manage to get my text to align to the right side of my table view. My code sets the text alignment to right but it only justifies the text if there is more that 1 line. Here is my cellforRowAt code

```<code>    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = UITableViewCell(style: .subtitle, reuseIdentifier: cellId)
    cell.textLabel?.text = self.messages[indexPath.row]
    cell.textLabel?.numberOfLines = 0
    cell.textLabel?.textAlignment = .right
    return cell
}
</code>```

How can I fix this?

答:
Let change the style of cell to default:

```<code>let cell = UITableViewCell(style: .default, reuseIdentifier: cellId)
</code>```

I created a subtitle cell in the storyboard and I realized the textLabel's size is fit to its content. So you can't align the text of textLabel. But you can do this with basic cell, its size is matched to the cell.

Body:
I cannot manage to get my text to align to the right side of my table view. My code sets the text alignment to right but it only justifies the text if there is more that 1 line. Here is my cellforRowAt code

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = UITableViewCell(style: .subtitle, reuseIdentifier: cellId)
    cell.textLabel?.text = self.messages[indexPath.row]
    cell.textLabel?.numberOfLines = 0
    cell.textLabel?.textAlignment = .right
    return cell
}

How can I fix this?

Body:
Let change the style of cell to default:

let cell = UITableViewCell(style: .default, reuseIdentifier: cellId)

I created a subtitle cell in the storyboard and I realized the textLabel's size is fit to its content. So you can't align the text of textLabel. But you can do this with basic cell, its size is matched to the cell.


问:
How to get the image of a transparent element without source?
I see an element in a HTML5 game which can be rotated, hidden and moved.
But it has a background... And the element is transparent.

For example, this moves the element:

```<code>$("#elementr2").animate({left: '650px'});
</code>```

I can capture it perfectly because it is transparent.

What could I do?

答:
Do you mean that you want to download the image asset?
You could check the network tab and find the resource there. It will probably be on its own or in a sprite sheet. Just filter the list by .png then right click on the asset, open in new window, right click, save as.</p>

ContentLicense: CC BY-SA 4.0

Body:
I see an element in a HTML5 game which can be rotated, hidden and moved.
But it has a background... And the element is transparent.

For example, this moves the element:

$("#elementr2").animate({left: '650px'});

I can capture it perfectly because it is transparent.

What could I do?