问:
How to select multiple rows based on header values?
I wish to iterate over rows of a Pandas dataframe while only checking for similarity within a few columns among the rows. Then, I want to check for a similarity condition, followed by a date comparison (which one is earlier/later) and apply corresponding changes to one element of the row selected.

For selecting particular rows, I kind of want something like this:

```<code>p=z["product_name", "Category 1", "Category 2", "Features"].iloc[i-1:i]
</code>```

I know it's not correct, but it's just to give an idea. Select a row with only a few particular headers out of many.

i=1
while (i<=len(z)):
    j=i+1
    p=z["product_name", "Category 1", "Category 2", "Features"].iloc[i-1:i]
    p=p.to_string(index=False)
    while(j<=len(z)):
        q=z["product_name", "Category 1", "Category 2", "Features"].iloc[j-1:j]
        q=q.to_string(index=False)
        if (p==q):
            if(z["Update Date"].iloc[i-1:i]>z["Update Date"].iloc[j-1:j]):
                 z.drop(j, axis=0)
        j=j+1
    i=i+1
```

I know that most of this code is actually wrong but this is the approach I'm trying. Please suggest a better approach/function that solves this problem.

答:
I don't know your question exactly, But there are Basic Issue in your code when you start i-1:i, it gives only one value why you use this line instead of directly one variable

```<code>p=z["product_name", "Category 1", "Category 2", "Features"].iloc[i-1:i]
</code>```

try This:

```<code>p=z[["product_name", "Category 1", "Category 2", "Features"]].iloc[i-1:i]
</code>```

Body:
I wish to iterate over rows of a Pandas dataframe while only checking for similarity within a few columns among the rows. Then, I want to check for a similarity condition, followed by a date comparison (which one is earlier/later) and apply corresponding changes to one element of the row selected.

For selecting particular rows, I kind of want something like this:

p=z["product_name", "Category 1", "Category 2", "Features"].iloc[i-1:i]

I know it's not correct, but it's just to give an idea. Select a row with only a few particular headers out of many.

i=1
while (i<=len(z)):
    j=i+1
    p=z["product_name", "Category 1", "Category 2", "Features"].iloc[i-1:i]
    p=p.to_string(index=False)
    while(j<=len(z)):
        q=z["product_name", "Category 1", "Category 2", "Features"].iloc[j-1:j]
        q=q.to_string(index=False)
        if (p==q):
            if(z["Update Date"].iloc[i-1:i]>z["Update Date"].iloc[j-1:j]):
                 z.drop(j, axis=0)
        j=j+1
    i=i+1

I know that most of this code is actually wrong but this is the approach I'm trying. Please suggest a better approach/function that solves this problem.

Body:
I don't know your question exactly, But there are Basic Issue in your code when you start i-1:i, it gives only one value why you use this line instead of directly one variable

p=z["product_name", "Category 1", "Category 2", "Features"].iloc[i-1:i]

try This:

p=z[["product_name", "Category 1", "Category 2", "Features"]].iloc[i-1:i]


来源: stackexchange

问:
What method of OOP would be appropriate for periodic table properties?
I'm trying to code in java a pet project using the periodic table. What's the best/efficient way to make a data set out of periodic element properties. Should I make a class of all the elements individually? or make an array  or objects?

Initial plan was to just create redundant classes with properties for each individual element. (ex. class for hydrogen, class for carbon, class for nitrogen... etc). with each class having attributes such as atomic number, weight, name, etc.. It's a lot of work, but wondering if there are efficient ways lol. The goal is to make this as modular as possible so i can add more property values or conditions if I choose to do so

I am pretty new to java, so please suggest anything. Also let me know if someone has already done this or has made a library for this. :)

答: I was wondering why don't you go with inheritance, create a class with general attributes i mean name,atomic weight,name etc, and inherit those attributes for where you want...</p>

ContentLicense: CC BY-SA 4.0


问:
sqlstate 42s22 column not found 1054 unknown column in 'field list'
Mates, im getting error sqlstate 42s22 columnactivity_post_commentsnot found 1054 unknown column in 'field list'

But this column name exists in my database.

I have checked my database and i have checked for spelling mistakes but im still getting this error

```<code>public function storecomments(Request $request, $id)
{
    // Create Comment
    $activity_post = new ActivityPost;
    $activity_post->activity_post_comments = $request->input('activity_post_comments');
    $activity_post->activity_post_id = $id;
    $activity_post->user_id = auth()->user()->id;
    $activity_post->save();

    return redirect()->back()->with('success', 'Comment Added');
}
</code>```

Not sure why im getting this error so i cant save this values in my database

Model:

class ActivityPostComment extends Model
{
 use SoftDeletes;

    // Table Name
    protected $table = 'activity_post_comments';
    // Primary Key
    public $primaryKey = 'id';
    // Timestamps
    public $timestamps = true;

    /**
     * The attributes that should be mutated to dates.
     *
     * @var array
     */
    protected $dates = ['deleted_at'];

    public function post(){
        return $this->belongsTo('App\ActivityPost');
    }
}```

答:
As per above code that you have posted . your calling wrong model your model class name is

ActivityPostComment

while you are using

ActivityPost

Body:
Mates, im getting error sqlstate 42s22 columnactivity_post_commentsnot found 1054 unknown column in 'field list'

But this column name exists in my database.

I have checked my database and i have checked for spelling mistakes but im still getting this error

public function storecomments(Request $request, $id)
{
    // Create Comment
    $activity_post = new ActivityPost;
    $activity_post->activity_post_comments = $request->input('activity_post_comments');
    $activity_post->activity_post_id = $id;
    $activity_post->user_id = auth()->user()->id;
    $activity_post->save();

    return redirect()->back()->with('success', 'Comment Added');
}

Not sure why im getting this error so i cant save this values in my database

Model:

class ActivityPostComment extends Model
{
 use SoftDeletes;

    // Table Name
    protected $table = 'activity_post_comments';
    // Primary Key
    public $primaryKey = 'id';
    // Timestamps
    public $timestamps = true;

    /**
     * The attributes that should be mutated to dates.
     *
     * @var array
     */
    protected $dates = ['deleted_at'];

    public function post(){
        return $this->belongsTo('App\ActivityPost');
    }
}


问:
Fullscreen android
When i click a button, i have to set my activity fullscreen.
searching in internet i found the code for do this.

```<code>container.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                                | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                                | View.SYSTEM_UI_FLAG_IMMERSIVE);
</code>```

But i do something wrong because status bar and navigation bar disappears and my activity ramain with the same height.

before

after

This is the video.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".VideoActivity">

    <include layout="@layout/content_video" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/close"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|center_horizontal"
        android:layout_marginBottom="70dp"
        android:layout_marginRight="80dp"
        android:src="@drawable/phone"
        app:elevation="0dp"
        app:backgroundTint="#44FF0000" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/screen"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|center_horizontal"
        android:layout_marginBottom="70dp"
        android:layout_marginLeft="80dp"
        android:src="@drawable/fullscreen"
        app:elevation="0dp"
        app:backgroundTint="#44000000"/>

</android.support.design.widget.CoordinatorLayout>
</code>```

And this content_video.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".VideoActivity"
    tools:showIn="@layout/video"
    android:id="@+id/layout"
    android:orientation="horizontal">

    <RelativeLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#000000">
    </RelativeLayout>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="@string/string_video_id"
        android:id="@+id/conference_id"
        android:textColor="@android:color/white"
        android:enabled="false"
        android:focusable="false"
        android:alpha="0.5"
        android:background="@color/button_background"
        android:paddingLeft="10dip"
        android:paddingTop="5dip"
        android:paddingRight="10dip"
        android:paddingBottom="5dip"
        android:layout_marginBottom="20dp"
        android:layout_marginLeft="10dp"
        android:gravity="bottom"
        android:layout_alignParentBottom="true"/>

</RelativeLayout>
</code>```

Can someone help me plase?
Thanks

答:
```<code> @Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    if (hasFocus) {
        getWindow().getDecorView().setSystemUiVisibility(5894);

    }
}
</code>```

or

```<code>requestWindowFeature(1);
getWindow().setFlags(1024, 1024);
//above setContentView(R.layout.xyz);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Fullscreen android

Body:
When i click a button, i have to set my activity fullscreen.
searching in internet i found the code for do this.

container.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                                | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                                | View.SYSTEM_UI_FLAG_IMMERSIVE);

But i do something wrong because status bar and navigation bar disappears and my activity ramain with the same height.

before

after

This is the video.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".VideoActivity">

    <include layout="@layout/content_video" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/close"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|center_horizontal"
        android:layout_marginBottom="70dp"
        android:layout_marginRight="80dp"
        android:src="@drawable/phone"
        app:elevation="0dp"
        app:backgroundTint="#44FF0000" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/screen"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|center_horizontal"
        android:layout_marginBottom="70dp"
        android:layout_marginLeft="80dp"
        android:src="@drawable/fullscreen"
        app:elevation="0dp"
        app:backgroundTint="#44000000"/>

</android.support.design.widget.CoordinatorLayout>

And this content_video.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".VideoActivity"
    tools:showIn="@layout/video"
    android:id="@+id/layout"
    android:orientation="horizontal">

    <RelativeLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#000000">
    </RelativeLayout>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="@string/string_video_id"
        android:id="@+id/conference_id"
        android:textColor="@android:color/white"
        android:enabled="false"
        android:focusable="false"
        android:alpha="0.5"
        android:background="@color/button_background"
        android:paddingLeft="10dip"
        android:paddingTop="5dip"
        android:paddingRight="10dip"
        android:paddingBottom="5dip"
        android:layout_marginBottom="20dp"
        android:layout_marginLeft="10dp"
        android:gravity="bottom"
        android:layout_alignParentBottom="true"/>

</RelativeLayout>

Can someone help me plase?
Thanks

Body:
 @Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    if (hasFocus) {
        getWindow().getDecorView().setSystemUiVisibility(5894);

    }
}

or

requestWindowFeature(1);
getWindow().setFlags(1024, 1024);
//above setContentView(R.layout.xyz);


问:
"Length cannot be less than zero." on a blank line
I keep getting the above error message, even if I comment out the line that the error is occurring on.  Any idea what could be causing this?  I've tried re-writing the lines with test values, but I still get the same error.

This works perfectly in debug mode, it's only in the deployment that this came up.

Original code:

```<code>Line 21:             string domain, username;
Line 22:             string text = Page.User.Identity.Name;
Line 23:
Line 24:             domain = text.Substring(0, text.IndexOf("\\"));
Line 25:             username = text.Substring(text.IndexOf("\\") + 1, text.Length - text.IndexOf("\\") - 1);

Source File: F:\<file path>\Default.aspx.cs    Line: 23
</code>```

Test code (same error):

```<code>Line 21:             string domain, username;
Line 22:             //string text = "TEST"; // Page.User.Identity.Name;
Line 23:             // this line is blank
Line 24:             domain = "TEST"; //text.Substring(0, text.IndexOf("\\"));
Line 25:             username = "TEST"; // text.Substring(text.IndexOf("\\") + 1,

Source File: F:\<file path>\Default.aspx.cs    Line: 23
</code>```

Here's the stack trace if it helps at all:

```<code>[ArgumentOutOfRangeException: Length cannot be less than zero.
Parameter name: length]
System.String.InternalSubStringWithChecks(Int32 startIndex, Int32 length, Boolean fAlwaysCopy) +12681546
Insufficiencies._Default.Page_Load(Object sender, EventArgs e) in F:\<file path>\Default.aspx.cs:23
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +25
System.Web.UI.Control.LoadRecursive() +71
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3048
</code>```

答:
The variable text contains no \\ substring thus text.IndexOf("\\") returns -1 which is indeed invalid argument for Substring.

To fix this, you can use such code that will assign the whole text when backslash is not found.

```<code>int backSlashIndex = text.IndexOf("\\");
domain = (backSlashIndex >= 0) ? text.Substring(0, backSlashIndex) : text;
</code>```

Body:
I keep getting the above error message, even if I comment out the line that the error is occurring on.  Any idea what could be causing this?  I've tried re-writing the lines with test values, but I still get the same error.

This works perfectly in debug mode, it's only in the deployment that this came up.

Original code:

Line 21:             string domain, username;
Line 22:             string text = Page.User.Identity.Name;
Line 23:
Line 24:             domain = text.Substring(0, text.IndexOf("\\"));
Line 25:             username = text.Substring(text.IndexOf("\\") + 1, text.Length - text.IndexOf("\\") - 1);

Source File: F:\<file path>\Default.aspx.cs    Line: 23

Test code (same error):

Line 21:             string domain, username;
Line 22:             //string text = "TEST"; // Page.User.Identity.Name;
Line 23:             // this line is blank
Line 24:             domain = "TEST"; //text.Substring(0, text.IndexOf("\\"));
Line 25:             username = "TEST"; // text.Substring(text.IndexOf("\\") + 1,

Source File: F:\<file path>\Default.aspx.cs    Line: 23

Here's the stack trace if it helps at all:

[ArgumentOutOfRangeException: Length cannot be less than zero.
Parameter name: length]
System.String.InternalSubStringWithChecks(Int32 startIndex, Int32 length, Boolean fAlwaysCopy) +12681546
Insufficiencies._Default.Page_Load(Object sender, EventArgs e) in F:\<file path>\Default.aspx.cs:23
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +25
System.Web.UI.Control.LoadRecursive() +71
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3048

Body:
The variable text contains no \\ substring thus text.IndexOf("\\") returns -1 which is indeed invalid argument for Substring.

To fix this, you can use such code that will assign the whole text when backslash is not found.

int backSlashIndex = text.IndexOf("\\");
domain = (backSlashIndex >= 0) ? text.Substring(0, backSlashIndex) : text;


问:
preg_replace_callback for this expression
I have a preg_replace code in my php file:-

```<code>preg_replace('/<([^>]+)>/es', "'<'.sanitize('\\1',5).'>'",strip_tags($var, $allowable_tags))
</code>```

I want to convert it into preg_replace_callback.

```<code>preg_replace_callback('/<([^>]+)>/s', function($m){return '<'.sanitize($m,5).'>';},strip_tags($var, $allowable_tags))
</code>```

But it is not giving the same results. Can someone help?

答:
You can also use clean interface of T-Regx library</p>

```<code>pattern('<([^>]+)>', 's')->replace($input)->callback(function (Match $m) {
    return '<' . sanitize($m, 5) . '>';
});
</code>```

Body:
I have a preg_replace code in my php file:-

preg_replace('/<([^>]+)>/es', "'<'.sanitize('\\1',5).'>'",strip_tags($var, $allowable_tags))

I want to convert it into preg_replace_callback.

preg_replace_callback('/<([^>]+)>/s', function($m){return '<'.sanitize($m,5).'>';},strip_tags($var, $allowable_tags))

But it is not giving the same results. Can someone help?

Body:
You can also use clean interface of T-Regx library

pattern('<([^>]+)>', 's')->replace($input)->callback(function (Match $m) {
    return '<' . sanitize($m, 5) . '>';
});


问:
Connecting Marklogic Database
I'm tryng to connect jmeter and marklogic using postgresql-42.1.4.jar or mljdbc-42.1.4.jar.
My app-servers:

My Configuration of JDBC:

And i received the error:  "Cannot create PoolableConnectionFactory (The connection attempt failed.)"

What i do wrong? help?

答:
As far as I can remember the default postgresql validation query used to validate the JDBC connection is not a valid SQL statement for MarkLogic. JMeter uses apache commons dbcp for its connection pooling which in turn uses a validation query to validate the connections.

Not sure what the query is (I'm sure this is somewhere in the source code) but you need to change that.

Go to "JDBC Connection Configuration" and set "Validation Query" to select 1.

For reference the complete exception message is:

java.sql.SQLException: Cannot create PoolableConnectionFactory
  (isValid() returned false)

Title: Connecting Marklogic Database


问:
Room Persistence Library: attempt to re-open an already-closed object
Everything was working fine when I was using 1.0.0-alpha5 version of Room Persistence Library. But, after updating to 1.0.0-alpha9 version, I am getting this error:

java.lang.IllegalStateException: attempt to re-open an already-closed
  object: SQLiteDatabase: /data/data/package_name/databases/app_db

How can I solve this?

EDIT:

I am using MVP architecture with dagger 2. I have got DatabaseHelper class which initializes RoomDatabase:

```<code>@Singleton
public class DatabaseHelper {

private final AppDatabase appDatabase;

@Inject
public DatabaseHelper(@ApplicationContext Context context) {
    appDatabase = Room.databaseBuilder(context, AppDatabase.class, "app_db").build();
}

public List<DifficultyEntity> getAllDifficulties() {
        return appDatabase.difficultyDao().getAllDifficulties();
}
</code>```

My RoomDatabase:

```<code>@Database(version = 22, entities = {
        DifficultyEntity.class, // ....
})
@Singleton
public abstract class AppDatabase extends RoomDatabase {

    public abstract DifficultyDao difficultyDao();
    //....
}
</code>```

When I call getAllDifficulties method, I am getting that error.

Here's logcat:

```<code>java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase: /data/data/package_name/databases/app_db
       at android.database.sqlite.SQLiteClosable.acquireReference(SQLiteClosable.java:55)
       at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1783)
       at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1729)
       at android.arch.persistence.db.framework.FrameworkSQLiteDatabase.execSQL(FrameworkSQLiteDatabase.java:241)
       at android.arch.persistence.room.RoomOpenHelper.createMasterTableIfNotExists(RoomOpenHelper.java:130)
       at android.arch.persistence.room.RoomOpenHelper.checkIdentity(RoomOpenHelper.java:106)
       at android.arch.persistence.room.RoomOpenHelper.onOpen(RoomOpenHelper.java:99)
       at android.arch.persistence.db.framework.FrameworkSQLiteOpenHelper$1.onOpen(FrameworkSQLiteOpenHelper.java:64)
       at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:266)
       at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
       at android.arch.persistence.db.framework.FrameworkSQLiteOpenHelper$OpenHelper.getWritableSupportDatabase(FrameworkSQLiteOpenHelper.java:106)
       at android.arch.persistence.db.framework.FrameworkSQLiteOpenHelper.getWritableDatabase(FrameworkSQLiteOpenHelper.java:82)
       at android.arch.persistence.room.RoomDatabase.query(RoomDatabase.java:191)
       at uz.iumarov.ieltsspeaking.data.local.database.daos.RecordingDao_Impl.getAllRecordings(RecordingDao_Impl.java:167)
       at uz.iumarov.ieltsspeaking.data.local.database.DatabaseHelper.getAllRecording(DatabaseHelper.java:361)
       at uz.iumarov.ieltsspeaking.ui.main.recordingsFragment.RecordingsPresenter$1.call(RecordingsPresenter.java:77)
       at uz.iumarov.ieltsspeaking.ui.main.recordingsFragment.RecordingsPresenter$1.call(RecordingsPresenter.java:74)
       at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:46)
       at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:35)
       at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)
       at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
       at rx.Observable.unsafeSubscribe(Observable.java:10151)
       at rx.internal.operators.OnSubscribeMap.call(OnSubscribeMap.java:48)
       at rx.internal.operators.OnSubscribeMap.call(OnSubscribeMap.java:33)
       at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)
       at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
       at rx.Observable.unsafeSubscribe(Observable.java:10151)
       at rx.internal.operators.OperatorSubscribeOn$1.call(OperatorSubscribeOn.java:94)
       at rx.internal.schedulers.EventLoopsScheduler$EventLoopWorker$1.call(EventLoopsScheduler.java:172)
       at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:55)
       at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
       at java.util.concurrent.FutureTask.run(FutureTask.java:237)
       at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:152)
       at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:265)
       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
       at java.lang.Thread.run(Thread.java:818)
</code>```

EDIT 2:

After some time, I started getting different error:

```<code>java.lang.IllegalStateException: Room cannot verify the data integrity. Looks like you've changed schema but forgot to update the version number. You can simply fix this by increasing the version number.
       at android.arch.persistence.room.RoomOpenHelper.checkIdentity(RoomOpenHelper.java:118)
       at android.arch.persistence.room.RoomOpenHelper.onOpen(RoomOpenHelper.java:99)
       at android.arch.persistence.db.framework.FrameworkSQLiteOpenHelper$1.onOpen(FrameworkSQLiteOpenHelper.java:64)
       at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:266)
       at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
       at android.arch.persistence.db.framework.FrameworkSQLiteOpenHelper$OpenHelper.getWritableSupportDatabase(FrameworkSQLiteOpenHelper.java:106)
       at android.arch.persistence.db.framework.FrameworkSQLiteOpenHelper.getWritableDatabase(FrameworkSQLiteOpenHelper.java:82)
       at android.arch.persistence.room.RoomDatabase.query(RoomDatabase.java:191)
       at uz.iumarov.ieltsspeaking.data.local.database.daos.RecordingDao_Impl.getAllRecordings(RecordingDao_Impl.java:167)
       at uz.iumarov.ieltsspeaking.data.local.database.DatabaseHelper.getAllRecording(DatabaseHelper.java:361)
       at uz.iumarov.ieltsspeaking.ui.main.recordingsFragment.RecordingsPresenter$1.call(RecordingsPresenter.java:77)
       at uz.iumarov.ieltsspeaking.ui.main.recordingsFragment.RecordingsPresenter$1.call(RecordingsPresenter.java:74)
       at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:46)
       at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:35)
       at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)
       at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
       at rx.Observable.unsafeSubscribe(Observable.java:10151)
       at rx.internal.operators.OnSubscribeMap.call(OnSubscribeMap.java:48)
       at rx.internal.operators.OnSubscribeMap.call(OnSubscribeMap.java:33)
       at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)
       at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
       at rx.Observable.unsafeSubscribe(Observable.java:10151)
       at rx.internal.operators.OperatorSubscribeOn$1.call(OperatorSubscribeOn.java:94)
       at rx.internal.schedulers.EventLoopsScheduler$EventLoopWorker$1.call(EventLoopsScheduler.java:172)
       at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:55)
       at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
       at java.util.concurrent.FutureTask.run(FutureTask.java:237)
       at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:152)
       at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:265)
       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
       at java.lang.Thread.run(Thread.java:818)
</code>```

And when I updated the version number, I am getting Migration error:

```<code>java.lang.IllegalStateException: A migration from 22 to 23 is necessary. Please provide a Migration in the builder or call fallbackToDestructiveMigration in the builder in which case Room will re-create all of the tables.
       at android.arch.persistence.room.RoomOpenHelper.onUpgrade(RoomOpenHelper.java:81)
       at android.arch.persistence.db.framework.FrameworkSQLiteOpenHelper$1.onUpgrade(FrameworkSQLiteOpenHelper.java:49)
       at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:256)
       at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
       at android.arch.persistence.db.framework.FrameworkSQLiteOpenHelper$OpenHelper.getWritableSupportDatabase(FrameworkSQLiteOpenHelper.java:106)
       at android.arch.persistence.db.framework.FrameworkSQLiteOpenHelper.getWritableDatabase(FrameworkSQLiteOpenHelper.java:82)
       at android.arch.persistence.room.RoomDatabase.query(RoomDatabase.java:191)
       at uz.iumarov.ieltsspeaking.data.local.database.daos.RecordingDao_Impl.getAllRecordings(RecordingDao_Impl.java:167)
       at uz.iumarov.ieltsspeaking.data.local.database.DatabaseHelper.getAllRecording(DatabaseHelper.java:361)
       at uz.iumarov.ieltsspeaking.ui.main.recordingsFragment.RecordingsPresenter$1.call(RecordingsPresenter.java:77)
       at uz.iumarov.ieltsspeaking.ui.main.recordingsFragment.RecordingsPresenter$1.call(RecordingsPresenter.java:74)
       at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:46)
       at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:35)
       at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)
       at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
       at rx.Observable.unsafeSubscribe(Observable.java:10151)
       at rx.internal.operators.OnSubscribeMap.call(OnSubscribeMap.java:48)
       at rx.internal.operators.OnSubscribeMap.call(OnSubscribeMap.java:33)
       at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)
       at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
       at rx.Observable.unsafeSubscribe(Observable.java:10151)
       at rx.internal.operators.OperatorSubscribeOn$1.call(OperatorSubscribeOn.java:94)
       at rx.internal.schedulers.EventLoopsScheduler$EventLoopWorker$1.call(EventLoopsScheduler.java:172)
       at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:55)
       at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
       at java.util.concurrent.FutureTask.run(FutureTask.java:237)
       at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:152)
       at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:265)
       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
       at java.lang.Thread.run(Thread.java:818)
</code>```

Please, somebody help me!

SOLVED

I deleted my app and reinstalled. Now, everything is working fine with alpha9 verison.

答:
Had the same issue.
Be aware that database may persist after uninstall.

In manifest you need to do

```<code>    android:allowBackup="false"
</code>```

Body:
Everything was working fine when I was using 1.0.0-alpha5 version of Room Persistence Library. But, after updating to 1.0.0-alpha9 version, I am getting this error:

java.lang.IllegalStateException: attempt to re-open an already-closed
  object: SQLiteDatabase: /data/data/package_name/databases/app_db

How can I solve this?

EDIT:

I am using MVP architecture with dagger 2. I have got DatabaseHelper class which initializes RoomDatabase:

@Singleton
public class DatabaseHelper {

private final AppDatabase appDatabase;

@Inject
public DatabaseHelper(@ApplicationContext Context context) {
    appDatabase = Room.databaseBuilder(context, AppDatabase.class, "app_db").build();
}

public List<DifficultyEntity> getAllDifficulties() {
        return appDatabase.difficultyDao().getAllDifficulties();
}

My RoomDatabase:

@Database(version = 22, entities = {
        DifficultyEntity.class, // ....
})
@Singleton
public abstract class AppDatabase extends RoomDatabase {

    public abstract DifficultyDao difficultyDao();
    //....
}

When I call getAllDifficulties method, I am getting that error.

Here's logcat:

java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase: /data/data/package_name/databases/app_db
       at android.database.sqlite.SQLiteClosable.acquireReference(SQLiteClosable.java:55)
       at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1783)
       at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1729)
       at android.arch.persistence.db.framework.FrameworkSQLiteDatabase.execSQL(FrameworkSQLiteDatabase.java:241)
       at android.arch.persistence.room.RoomOpenHelper.createMasterTableIfNotExists(RoomOpenHelper.java:130)
       at android.arch.persistence.room.RoomOpenHelper.checkIdentity(RoomOpenHelper.java:106)
       at android.arch.persistence.room.RoomOpenHelper.onOpen(RoomOpenHelper.java:99)
       at android.arch.persistence.db.framework.FrameworkSQLiteOpenHelper$1.onOpen(FrameworkSQLiteOpenHelper.java:64)
       at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:266)
       at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
       at android.arch.persistence.db.framework.FrameworkSQLiteOpenHelper$OpenHelper.getWritableSupportDatabase(FrameworkSQLiteOpenHelper.java:106)
       at android.arch.persistence.db.framework.FrameworkSQLiteOpenHelper.getWritableDatabase(FrameworkSQLiteOpenHelper.java:82)
       at android.arch.persistence.room.RoomDatabase.query(RoomDatabase.java:191)
       at uz.iumarov.ieltsspeaking.data.local.database.daos.RecordingDao_Impl.getAllRecordings(RecordingDao_Impl.java:167)
       at uz.iumarov.ieltsspeaking.data.local.database.DatabaseHelper.getAllRecording(DatabaseHelper.java:361)
       at uz.iumarov.ieltsspeaking.ui.main.recordingsFragment.RecordingsPresenter$1.call(RecordingsPresenter.java:77)
       at uz.iumarov.ieltsspeaking.ui.main.recordingsFragment.RecordingsPresenter$1.call(RecordingsPresenter.java:74)
       at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:46)
       at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:35)
       at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)
       at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
       at rx.Observable.unsafeSubscribe(Observable.java:10151)
       at rx.internal.operators.OnSubscribeMap.call(OnSubscribeMap.java:48)
       at rx.internal.operators.OnSubscribeMap.call(OnSubscribeMap.java:33)
       at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)
       at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
       at rx.Observable.unsafeSubscribe(Observable.java:10151)
       at rx.internal.operators.OperatorSubscribeOn$1.call(OperatorSubscribeOn.java:94)
       at rx.internal.schedulers.EventLoopsScheduler$EventLoopWorker$1.call(EventLoopsScheduler.java:172)
       at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:55)
       at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
       at java.util.concurrent.FutureTask.run(FutureTask.java:237)
       at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:152)
       at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:265)
       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
       at java.lang.Thread.run(Thread.java:818)

EDIT 2:

After some time, I started getting different error:

java.lang.IllegalStateException: Room cannot verify the data integrity. Looks like you've changed schema but forgot to update the version number. You can simply fix this by increasing the version number.
       at android.arch.persistence.room.RoomOpenHelper.checkIdentity(RoomOpenHelper.java:118)
       at android.arch.persistence.room.RoomOpenHelper.onOpen(RoomOpenHelper.java:99)
       at android.arch.persistence.db.framework.FrameworkSQLiteOpenHelper$1.onOpen(FrameworkSQLiteOpenHelper.java:64)
       at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:266)
       at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
       at android.arch.persistence.db.framework.FrameworkSQLiteOpenHelper$OpenHelper.getWritableSupportDatabase(FrameworkSQLiteOpenHelper.java:106)
       at android.arch.persistence.db.framework.FrameworkSQLiteOpenHelper.getWritableDatabase(FrameworkSQLiteOpenHelper.java:82)
       at android.arch.persistence.room.RoomDatabase.query(RoomDatabase.java:191)
       at uz.iumarov.ieltsspeaking.data.local.database.daos.RecordingDao_Impl.getAllRecordings(RecordingDao_Impl.java:167)
       at uz.iumarov.ieltsspeaking.data.local.database.DatabaseHelper.getAllRecording(DatabaseHelper.java:361)
       at uz.iumarov.ieltsspeaking.ui.main.recordingsFragment.RecordingsPresenter$1.call(RecordingsPresenter.java:77)
       at uz.iumarov.ieltsspeaking.ui.main.recordingsFragment.RecordingsPresenter$1.call(RecordingsPresenter.java:74)
       at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:46)
       at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:35)
       at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)
       at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
       at rx.Observable.unsafeSubscribe(Observable.java:10151)
       at rx.internal.operators.OnSubscribeMap.call(OnSubscribeMap.java:48)
       at rx.internal.operators.OnSubscribeMap.call(OnSubscribeMap.java:33)
       at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)
       at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
       at rx.Observable.unsafeSubscribe(Observable.java:10151)
       at rx.internal.operators.OperatorSubscribeOn$1.call(OperatorSubscribeOn.java:94)
       at rx.internal.schedulers.EventLoopsScheduler$EventLoopWorker$1.call(EventLoopsScheduler.java:172)
       at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:55)
       at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
       at java.util.concurrent.FutureTask.run(FutureTask.java:237)
       at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:152)
       at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:265)
       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
       at java.lang.Thread.run(Thread.java:818)

And when I updated the version number, I am getting Migration error:

java.lang.IllegalStateException: A migration from 22 to 23 is necessary. Please provide a Migration in the builder or call fallbackToDestructiveMigration in the builder in which case Room will re-create all of the tables.
       at android.arch.persistence.room.RoomOpenHelper.onUpgrade(RoomOpenHelper.java:81)
       at android.arch.persistence.db.framework.FrameworkSQLiteOpenHelper$1.onUpgrade(FrameworkSQLiteOpenHelper.java:49)
       at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:256)
       at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
       at android.arch.persistence.db.framework.FrameworkSQLiteOpenHelper$OpenHelper.getWritableSupportDatabase(FrameworkSQLiteOpenHelper.java:106)
       at android.arch.persistence.db.framework.FrameworkSQLiteOpenHelper.getWritableDatabase(FrameworkSQLiteOpenHelper.java:82)
       at android.arch.persistence.room.RoomDatabase.query(RoomDatabase.java:191)
       at uz.iumarov.ieltsspeaking.data.local.database.daos.RecordingDao_Impl.getAllRecordings(RecordingDao_Impl.java:167)
       at uz.iumarov.ieltsspeaking.data.local.database.DatabaseHelper.getAllRecording(DatabaseHelper.java:361)
       at uz.iumarov.ieltsspeaking.ui.main.recordingsFragment.RecordingsPresenter$1.call(RecordingsPresenter.java:77)
       at uz.iumarov.ieltsspeaking.ui.main.recordingsFragment.RecordingsPresenter$1.call(RecordingsPresenter.java:74)
       at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:46)
       at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:35)
       at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)
       at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
       at rx.Observable.unsafeSubscribe(Observable.java:10151)
       at rx.internal.operators.OnSubscribeMap.call(OnSubscribeMap.java:48)
       at rx.internal.operators.OnSubscribeMap.call(OnSubscribeMap.java:33)
       at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)
       at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
       at rx.Observable.unsafeSubscribe(Observable.java:10151)
       at rx.internal.operators.OperatorSubscribeOn$1.call(OperatorSubscribeOn.java:94)
       at rx.internal.schedulers.EventLoopsScheduler$EventLoopWorker$1.call(EventLoopsScheduler.java:172)
       at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:55)
       at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
       at java.util.concurrent.FutureTask.run(FutureTask.java:237)
       at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:152)
       at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:265)
       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
       at java.lang.Thread.run(Thread.java:818)

Please, somebody help me!

SOLVED

I deleted my app and reinstalled. Now, everything is working fine with alpha9 verison.

Body:
Had the same issue.
Be aware that database may persist after uninstall.

In manifest you need to do

    android:allowBackup="false"


问:
site.css is not working for my sample web site
Newbie here.

I have created an empty MVC project in VS2010 and I'm trying to format my view for authentication. So, I've added this to site.css:

```<code>.rez
{
color: Olive;
}
</code>```

and this to my View:

```<code>@using (Html.BeginForm())
{
<div>
<label class="rez">Username</label><input type="text" name="Username"/>
</div>
<div>
Password<input type="password" name="Password"/>
</div>
<div>
<input type="submit" name="Log"/>
</div>
}
</code>```

It's not working. I haven't touched routing or bundleconfig. I've configured web.config for authentication. _ViewStart and _Layout are also unchanged.

What am I doing wrong and more importantly how do I debug this issue. I'm using chrome.

答:
Naming Difference Found in Asp.net MVC 4

case sensitive

the problem is due to the file we're accessing, defined in ~/App_Start/BundleConfig.cs and the file we're applying changes in ~/Content/Site.css

In BundleConfig.cs we have:

```<code>bundles.Add(new StyleBundle("~/Content/css").Include(
                  "~/Content/bootstrap.css",
                  "~/Content/site.css"));
</code>```

but in project directory we have:

```<code>~/Content/Site.css
</code>```

Solution : Make sure to have the same file names.

Body:
Newbie here.

I have created an empty MVC project in VS2010 and I'm trying to format my view for authentication. So, I've added this to site.css:

.rez
{
color: Olive;
}

and this to my View:

@using (Html.BeginForm())
{

Username<input type="text" name="Username"/>

Password<input type="password" name="Password"/>

<input type="submit" name="Log"/>

}

It's not working. I haven't touched routing or bundleconfig. I've configured web.config for authentication. _ViewStart and _Layout are also unchanged.

What am I doing wrong and more importantly how do I debug this issue. I'm using chrome.

Body:
Naming Difference Found in Asp.net MVC 4

case sensitive

the problem is due to the file we're accessing, defined in ~/App_Start/BundleConfig.cs and the file we're applying changes in ~/Content/Site.css

In BundleConfig.cs we have:

bundles.Add(new StyleBundle("~/Content/css").Include(
                  "~/Content/bootstrap.css",
                  "~/Content/site.css"));

but in project directory we have:

~/Content/Site.css

Solution : Make sure to have the same file names.


问:
codeigniter photo thumb create and upload
it gives blank screen :/ it uploads first image, thats fine. than it call _create_thumbnail and it gives blank screen at line "$this->image_lib->resize()" :/

any idea what can be the problem?

Thanks!!

/**
 * ==================================================================
 * Upload photo
 *

 * Thumb    = 210px - 160px
 * Original = 500px - 385px
 *
 */

```<code>function img_upload()
{
    $config['upload_path'] = 'uploads/';
    $config['allowed_types'] = 'gif|jpg|jpeg|png';
    $config['max_size'] = '1000';
    $config['max_width'] = '1920';
    $config['max_height'] = '1280';
    $config['width'] = 500;
    $config['height'] = 385;

    $this->load->library('upload', $config);

    if(!$this->upload->do_upload()) echo $this->upload->display_errors();
    else {

        $fInfo = $this->upload->data();
        $this->_create_thumbnail($fInfo['file_name']);

        $data['uploadInfo'] = $fInfo;
        $data['thumbnail_name'] = $fInfo['raw_name'] . '_thumb' . $fInfo['file_ext'];

        // set view
        $this->load->view('upload_success', $data);
    }
}

function _create_thumbnail($fileName)
{
    $config['image_library'] = 'gd2';
    $config['source_image'] = 'uploads/' . $fileName;
    $config['create_thumb'] = TRUE;
    $config['maintain_ratio'] = TRUE;
    $config['width'] = 210;
    $config['height'] = 160;

    $this->load->library('image_lib', $config);
    if(!$this->image_lib->resize()) echo $this->image_lib->display_errors();

}
</code>```

答:
try this</p>

```<code>function _create_thumbnail($fileName)
 {
$this->load->library('image_lib');
         $config['image_library'] = 'gd2';
         $config['source_image'] = './uploads/' . $fileName;
         $config['create_thumb'] = TRUE;
         $config['maintain_ratio'] = TRUE;
         $config['width'] = 210;
         $config['height'] = 160;
         $config['new_image'] = './uploads/'.$fileName;

         $this->image_lib->initialize($config);
         if(!$this->image_lib->resize()) echo
 $this->image_lib->display_errors();

 }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
it gives blank screen :/ it uploads first image, thats fine. than it call _create_thumbnail and it gives blank screen at line "$this->image_lib->resize()" :/

any idea what can be the problem?

Thanks!!

/**
 * ==================================================================
 * Upload photo
 *

 * Thumb    = 210px - 160px
 * Original = 500px - 385px
 *
 */

function img_upload()
{
    $config['upload_path'] = 'uploads/';
    $config['allowed_types'] = 'gif|jpg|jpeg|png';
    $config['max_size'] = '1000';
    $config['max_width'] = '1920';
    $config['max_height'] = '1280';
    $config['width'] = 500;
    $config['height'] = 385;

    $this->load->library('upload', $config);

    if(!$this->upload->do_upload()) echo $this->upload->display_errors();
    else {

        $fInfo = $this->upload->data();
        $this->_create_thumbnail($fInfo['file_name']);

        $data['uploadInfo'] = $fInfo;
        $data['thumbnail_name'] = $fInfo['raw_name'] . '_thumb' . $fInfo['file_ext'];

        // set view
        $this->load->view('upload_success', $data);
    }
}

function _create_thumbnail($fileName)
{
    $config['image_library'] = 'gd2';
    $config['source_image'] = 'uploads/' . $fileName;
    $config['create_thumb'] = TRUE;
    $config['maintain_ratio'] = TRUE;
    $config['width'] = 210;
    $config['height'] = 160;

    $this->load->library('image_lib', $config);
    if(!$this->image_lib->resize()) echo $this->image_lib->display_errors();

}

Body:
try this

function _create_thumbnail($fileName)
 {
$this->load->library('image_lib');
         $config['image_library'] = 'gd2';
         $config['source_image'] = './uploads/' . $fileName;
         $config['create_thumb'] = TRUE;
         $config['maintain_ratio'] = TRUE;
         $config['width'] = 210;
         $config['height'] = 160;
         $config['new_image'] = './uploads/'.$fileName;

         $this->image_lib->initialize($config);
         if(!$this->image_lib->resize()) echo
 $this->image_lib->display_errors();

 }


问:
Interactive grid column to display full content but read only
Environment: Oracle APEX v5.1.2 / Oracle 12c

I have an interactive grid report by where I have one field that is a display only column but it actually returns an error message description that could be quite long. Since I would like to keep my IG report to one record per row, is there a means of being able to display the full contents of this field without allowing changes to the underlying column value in the database?

Some means of a tool tip or being able to drill into the field to view all info but read only.

答: Im on 18.2, and I havent used 5.1.2, but I would assume the features havent changed. Set the column to Textarea so that if you click on it you can have the full text, but then you need to disable it somehow. Just making it Read Only should probably be enough, if not, you can probably also disable it using javascript.</p>


问:
TensorFlow Serving: Update model_config (add additional models) at runtime
I'm busy configuring a TensorFlow Serving client that asks a TensorFlow Serving server to produce predictions on a given input image, for a given model.

If the model being requested has not yet been served, it is downloaded from a remote URL to a folder where the server's models are located. (The client does this). At this point I need to update the model_config and trigger the server to reload it.

This functionality appears to exist (based on https://github.com/tensorflow/serving/pull/885 and https://github.com/tensorflow/serving/blob/master/tensorflow_serving/apis/model_service.proto#L22), but I can't find any documentation on how to actually use it.

I am essentially looking for a python script with which I can trigger the reload from client side (or otherwise to configure the server to listen for changes and trigger the reload itself).

答:
Add a model to TF Serving server and to the existing config file conf_filepath: Use arguments name, base_path, model_platform for the new model. Keeps the original models intact.

Notice a small difference from @Karl 's answer - using MergeFrom instead of CopyFrom

pip install tensorflow-serving-api

```<code>import grpc
from google.protobuf import text_format
from tensorflow_serving.apis import model_service_pb2_grpc, model_management_pb2
from tensorflow_serving.config import model_server_config_pb2

def add_model_config(conf_filepath, host, name, base_path, model_platform):
    with open(conf_filepath, 'r+') as f:
        config_ini = f.read()
    channel = grpc.insecure_channel(host)
    stub = model_service_pb2_grpc.ModelServiceStub(channel)
    request = model_management_pb2.ReloadConfigRequest()
    model_server_config = model_server_config_pb2.ModelServerConfig()
    config_list = model_server_config_pb2.ModelConfigList()
    model_server_config = text_format.Parse(text=config_ini, message=model_server_config)

    # Create a config to add to the list of served models
    one_config = config_list.config.add()
    one_config.name = name
    one_config.base_path = base_path
    one_config.model_platform = model_platform

    model_server_config.model_config_list.MergeFrom(config_list)
    request.config.CopyFrom(model_server_config)

    response = stub.HandleReloadConfigRequest(request, 10)
    if response.status.error_code == 0:
        with open(conf_filepath, 'w+') as f:
            f.write(request.config.__str__())
        print("Updated TF Serving conf file")
    else:
        print("Failed to update model_config_list!")
        print(response.status.error_code)
        print(response.status.error_message)
</code>```

Body:
Add a model to TF Serving server and to the existing config file conf_filepath: Use arguments name, base_path, model_platform for the new model. Keeps the original models intact.

Notice a small difference from @Karl 's answer - using MergeFrom instead of CopyFrom

pip install tensorflow-serving-api

import grpc
from google.protobuf import text_format
from tensorflow_serving.apis import model_service_pb2_grpc, model_management_pb2
from tensorflow_serving.config import model_server_config_pb2

def add_model_config(conf_filepath, host, name, base_path, model_platform):
    with open(conf_filepath, 'r+') as f:
        config_ini = f.read()
    channel = grpc.insecure_channel(host)
    stub = model_service_pb2_grpc.ModelServiceStub(channel)
    request = model_management_pb2.ReloadConfigRequest()
    model_server_config = model_server_config_pb2.ModelServerConfig()
    config_list = model_server_config_pb2.ModelConfigList()
    model_server_config = text_format.Parse(text=config_ini, message=model_server_config)

    # Create a config to add to the list of served models
    one_config = config_list.config.add()
    one_config.name = name
    one_config.base_path = base_path
    one_config.model_platform = model_platform

    model_server_config.model_config_list.MergeFrom(config_list)
    request.config.CopyFrom(model_server_config)

    response = stub.HandleReloadConfigRequest(request, 10)
    if response.status.error_code == 0:
        with open(conf_filepath, 'w+') as f:
            f.write(request.config.__str__())
        print("Updated TF Serving conf file")
    else:
        print("Failed to update model_config_list!")
        print(response.status.error_code)
        print(response.status.error_message)


问:
Making a button content change within user control on click
I realise that WPF is still a bucket of magic to me. The problem seems to be simple. I have a user control with a button. I would like to change the button content (text) on click.

If I open the form with user control without initialising the button value and then say in

```<code>void Button_Click(object sender, RoutedEventArgs e)
{
    Button.Content = "New Value";
}
</code>```

it works.

If I initialise the button value dynamically in the control constructor by Button.Content = "Init Value", the second bit Button.Content = "New Value"
never happens (it happens, but button text does not show the change ever again, at least that what it seems).

So I decided to use a binding. Declared ButtonText property in MyUserControl (+ the corresponding DependencyProperty with getter and setter) and tried to do ButtonText = "Init Value"; in constructor and ButtonText = "New Value"; in Button_Click(). The first one works, the second one still does not. I assume because of the wrong data context in Button_Click()?

In MyUserControl I tried a few things including

```<code><Button x:Name="Button"
 Content="{Binding Path=ButtonText, RelativeSource={RelativeSource AncestorType=UserControl}}"
 Click="Button_Click" />

<Button x:Name="Button"
 Content="{Binding Path=ButtonText, Element=MyUserControl}"
 Click="Button_Click" />
</code>```

and nothing seems to work.

What is the easiest way to achieve what I need, i.e. both dynamic initialisation and dynamic change? With an explanation, if possible, please, why my first (direct) approach does not work and what the binding approach is missing.

Thanks a lot!

EDIT:

An alternative would be to use triggers.

This example works:

```<code><Style x:Key="ButtonStyle" TargetType="{x:Type Button}">
    <Setter Property="Content" Value="Init Value"/>
    <Style.Triggers>
        <Trigger Property="IsClicked" Value="True">
            <Setter Property="Content" Value="New Value" />
        </Trigger>
    </Style.Triggers>
</Style>
</code>```

My problem is that I need a DataTrigger, like this

```<code><Style x:Key="ButtonStyle" TargetType="{x:Type Button}">
    <Setter Property="Content" Value="Init Value"/>
    <Style.Triggers>
        <DataTrigger Binding="{Binding Path=MyUserControlProperty, ElementName=MyUserControl}" Value="True">
            <Setter Property="Content" Value="New Value" />
        </DataTrigger>
    </Style.Triggers>
</Style>
</code>```

How do I make MyUserControlProperty value change propagate properly?

The funniest thing is if I open the control as a new form the initialisation of Button.Content = "Init Value" does not screw things up and everything just works. What the? Why is this simple task so hard and why so many behaviours?

答:
Don't set Button.Content directly, when you have a binding set on it. If you set Button.Content in the Constructor you effectively remove the binding.
This works:</p>

```<code><Window x:Class="StackOverflow.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="450" Width="800">
    <StackPanel>
        <Button Content="{Binding Path=ButtonText1, RelativeSource={RelativeSource AncestorType=Window}}"  Click="Button1_OnClick"></Button>
    </StackPanel>
</Window>

</code>```

```<code>using System.Windows;

namespace StackOverflow
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow
    {
        public MainWindow()
        {
            InitializeComponent();
            ButtonText1 = "Paul";
        }

        private void Button1_OnClick(object sender, RoutedEventArgs e)
        {
            ButtonText1 = "Maria";
        }

        public string ButtonText1
        {
            get => (string)GetValue(ButtonText1Property);
            set => SetValue(ButtonText1Property, value);
        }

        // Using a DependencyProperty as the backing store for ButtonText1.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ButtonText1Property =
            DependencyProperty.Register("ButtonText1", typeof(string), typeof(MainWindow), new PropertyMetadata("Peter"));

    }
}
</code>```

Body:
I realise that WPF is still a bucket of magic to me. The problem seems to be simple. I have a user control with a button. I would like to change the button content (text) on click.

If I open the form with user control without initialising the button value and then say in

void Button_Click(object sender, RoutedEventArgs e)
{
    Button.Content = "New Value";
}

it works.

If I initialise the button value dynamically in the control constructor by Button.Content = "Init Value", the second bit Button.Content = "New Value"
never happens (it happens, but button text does not show the change ever again, at least that what it seems).

So I decided to use a binding. Declared ButtonText property in MyUserControl (+ the corresponding DependencyProperty with getter and setter) and tried to do ButtonText = "Init Value"; in constructor and ButtonText = "New Value"; in Button_Click(). The first one works, the second one still does not. I assume because of the wrong data context in Button_Click()?

In MyUserControl I tried a few things including

<Button x:Name="Button"
 Content="{Binding Path=ButtonText, RelativeSource={RelativeSource AncestorType=UserControl}}"
 Click="Button_Click" />

<Button x:Name="Button"
 Content="{Binding Path=ButtonText, Element=MyUserControl}"
 Click="Button_Click" />

and nothing seems to work.

What is the easiest way to achieve what I need, i.e. both dynamic initialisation and dynamic change? With an explanation, if possible, please, why my first (direct) approach does not work and what the binding approach is missing.

Thanks a lot!

EDIT:

An alternative would be to use triggers.

This example works:

</Style>

My problem is that I need a DataTrigger, like this

</Style>

How do I make MyUserControlProperty value change propagate properly?

The funniest thing is if I open the control as a new form the initialisation of Button.Content = "Init Value" does not screw things up and everything just works. What the? Why is this simple task so hard and why so many behaviours?

Body:
Don't set Button.Content directly, when you have a binding set on it. If you set Button.Content in the Constructor you effectively remove the binding.
This works:

<Window x:Class="StackOverflow.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="450" Width="800">
    <StackPanel>
        <Button Content="{Binding Path=ButtonText1, RelativeSource={RelativeSource AncestorType=Window}}"  Click="Button1_OnClick"></Button>
    </StackPanel>
</Window>

using System.Windows;

namespace StackOverflow
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow
    {
        public MainWindow()
        {
            InitializeComponent();
            ButtonText1 = "Paul";
        }

        private void Button1_OnClick(object sender, RoutedEventArgs e)
        {
            ButtonText1 = "Maria";
        }

        public string ButtonText1
        {
            get => (string)GetValue(ButtonText1Property);
            set => SetValue(ButtonText1Property, value);
        }

        // Using a DependencyProperty as the backing store for ButtonText1.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ButtonText1Property =
            DependencyProperty.Register("ButtonText1", typeof(string), typeof(MainWindow), new PropertyMetadata("Peter"));

    }
}


问:
Detecting if video was taken in portrait/landscape
I would like to confirm that what I am doing is indeed the correct way as some elements behave unexpected.

First, I have a landscape and portrait layout, as I understand, doing this will automatically detect if the phone is in portrait/landscape mode:

```<code>- layout
   - activity_video_player.xml
 - layout-land
   - activity_video_player.xml
</code>```

Then when the user selects a video from the gallery, I check if the video was taking in landscape or portrait, by doing this (inside OnCreate):

```<code>int w;
int h;

MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
mediaMetadataRetriever.setDataSource(this, videoURI);
String height = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
String width = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
w = Integer.parseInt(width);
h = Integer.parseInt(height);

if (w > h) {
    this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else {
    this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
</code>```

I have tested this and it works fine, but I noticed some of my xml elements (play button) is placed incorrectly.

So my app flow is:

```<code>MainActivity --> SelectvidButton --> Gallery Intent --> VideoPlayActivity
</code>```

My Question

Is this the correct way of doing this and if it is, is there any reason why some of the xml elements get placed incorrectly?

EDIT 1:

I noticed that this only happens when the activity is launched for the first time, if I press the back button and select the same video again, the layout is perfectly like I want it to be.

EDIT 2:

I have also noticed that this only happens if the previous activity (MainActivity) was in the same orientation than what the selected video is.

答:
Here is what I ended up doing.

Instead of using MediaMetadataRetriever to get the width and height, I first retrieve a Bitmap from the video file and then setting the orientation according to the width and hight of the Bitmap, as shown below:

```<code>private void rotateScreen() {
    try {
        //Create a new instance of MediaMetadataRetriever
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        //Declare the Bitmap
        Bitmap bmp;
        //Set the video Uri as data source for MediaMetadataRetriever
        retriever.setDataSource(this, mVideoUri);
        //Get one "frame"/bitmap - * NOTE - no time was set, so the first available frame will be used
        bmp = retriever.getFrameAtTime();

        //Get the bitmap width and height
        videoWidth = bmp.getWidth();
        videoHeight = bmp.getHeight();

        //If the width is bigger then the height then it means that the video was taken in landscape mode and we should set the orientation to landscape
        if (videoWidth > videoHeight) {
            //Set orientation to landscape
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
        //If the width is smaller then the height then it means that the video was taken in portrait mode and we should set the orientation to portrait
        if (videoWidth < videoHeight) {
            //Set orientation to portrait
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }

    } catch (RuntimeException ex) {
        //error occurred
        Log.e("MediaMetadataRetriever", "- Failed to rotate the video");

    }
}
</code>```

Body:
I would like to confirm that what I am doing is indeed the correct way as some elements behave unexpected.

First, I have a landscape and portrait layout, as I understand, doing this will automatically detect if the phone is in portrait/landscape mode:

- layout
   - activity_video_player.xml
 - layout-land
   - activity_video_player.xml

Then when the user selects a video from the gallery, I check if the video was taking in landscape or portrait, by doing this (inside OnCreate):

int w;
int h;

MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
mediaMetadataRetriever.setDataSource(this, videoURI);
String height = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
String width = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
w = Integer.parseInt(width);
h = Integer.parseInt(height);

if (w > h) {
    this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else {
    this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}

I have tested this and it works fine, but I noticed some of my xml elements (play button) is placed incorrectly.

So my app flow is:

MainActivity --> SelectvidButton --> Gallery Intent --> VideoPlayActivity

My Question

Is this the correct way of doing this and if it is, is there any reason why some of the xml elements get placed incorrectly?

EDIT 1:

I noticed that this only happens when the activity is launched for the first time, if I press the back button and select the same video again, the layout is perfectly like I want it to be.

EDIT 2:

I have also noticed that this only happens if the previous activity (MainActivity) was in the same orientation than what the selected video is.

Body:
Here is what I ended up doing.

Instead of using MediaMetadataRetriever to get the width and height, I first retrieve a Bitmap from the video file and then setting the orientation according to the width and hight of the Bitmap, as shown below:

private void rotateScreen() {
    try {
        //Create a new instance of MediaMetadataRetriever
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        //Declare the Bitmap
        Bitmap bmp;
        //Set the video Uri as data source for MediaMetadataRetriever
        retriever.setDataSource(this, mVideoUri);
        //Get one "frame"/bitmap - * NOTE - no time was set, so the first available frame will be used
        bmp = retriever.getFrameAtTime();

        //Get the bitmap width and height
        videoWidth = bmp.getWidth();
        videoHeight = bmp.getHeight();

        //If the width is bigger then the height then it means that the video was taken in landscape mode and we should set the orientation to landscape
        if (videoWidth > videoHeight) {
            //Set orientation to landscape
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
        //If the width is smaller then the height then it means that the video was taken in portrait mode and we should set the orientation to portrait
        if (videoWidth < videoHeight) {
            //Set orientation to portrait
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }

    } catch (RuntimeException ex) {
        //error occurred
        Log.e("MediaMetadataRetriever", "- Failed to rotate the video");

    }
}


问:
Arduino-seeed motor shield v2
My issue is maybe simple but I haven't been able to figure it out.
I am using an arduino uno, seeedstudio motor shield v2, and a wheel encoder. The issue is, the example code for this shield looks like this:

```<code>void loop()
{
motor.speed(0, 100);            // set motor0 to speed 100
delay(1000);
motor.brake(0);                 // brake
delay(1000);
motor.speed(0, -100);           // set motor0 to speed -100
delay(1000);
motor.stop(0);                  // stop
delay(1000);
}
</code>```

But delays are blocking and I can seem to count encoder pulses because of this (presumably). I have tried different implementations of millis() but the encoder reads wild numbers in the 10s of thousands/ negative.

答:
There is no wheel encoder in your code, but I assume your problem is that delay is a blocking function.

The easiest way to to check if a time has elapsed without blocking the program is to manually check if the time has elapsed since your last instruction. As an example:

```<code>void loop()
{
    unsigned long previous_time = millis();
    motor.speed(0, 100);
    while (millis() - previous_time < 1000)
    {
        // do something (check the encoder for instance
    }
}
</code>```

This way, you'll be able to perform other instructions while you are waiting for the delay to complete. Of course you can put this check in a function.

Hope it helps!

Title: Arduino-seeed motor shield v2

Body:
My issue is maybe simple but I haven't been able to figure it out.
I am using an arduino uno, seeedstudio motor shield v2, and a wheel encoder. The issue is, the example code for this shield looks like this:

void loop()
{
motor.speed(0, 100);            // set motor0 to speed 100
delay(1000);
motor.brake(0);                 // brake
delay(1000);
motor.speed(0, -100);           // set motor0 to speed -100
delay(1000);
motor.stop(0);                  // stop
delay(1000);
}

But delays are blocking and I can seem to count encoder pulses because of this (presumably). I have tried different implementations of millis() but the encoder reads wild numbers in the 10s of thousands/ negative.

Body:
There is no wheel encoder in your code, but I assume your problem is that delay is a blocking function.

The easiest way to to check if a time has elapsed without blocking the program is to manually check if the time has elapsed since your last instruction. As an example:

void loop()
{
    unsigned long previous_time = millis();
    motor.speed(0, 100);
    while (millis() - previous_time < 1000)
    {
        // do something (check the encoder for instance
    }
}

This way, you'll be able to perform other instructions while you are waiting for the delay to complete. Of course you can put this check in a function.

Hope it helps!


问:
Django 2.2 NoReverseMatch error, kwargs returns blank string?
I get a NoReverseMatch error with a blank string for kwargs. Am I doing something wrong in the models.py file that doesn't save the username associated with the post?

NoReverseMatch at /groups/posts/in/nasa-rocks/ Reverse for 'for_user'
  with keyword arguments '{'username': ''}' not found. 1 pattern(s)
  tried: ['posts/by/(?P[^/]+)/$']

models.py:

```<code>from django.db import models
from django.urls import reverse
from django.conf import settings

# Create your models here.

import misaka

from groups.models import Group

from django.contrib.auth import get_user_model
User = get_user_model()

class Post(models.Model):
    user = models.ForeignKey(User,related_name='posts',on_delete='CASCADE')
    group = models.ForeignKey(Group,related_name='posts',null=True,blank=True,on_delete='CASCADE')
    created_at = models.DateTimeField(auto_now=True)
    message = models.TextField()
    message_html = models.TextField(editable=False)

    def __str__(self):
        return self.message

    def save(self,*args,**kwargs):
        self.message_html = misaka.html(self.message)
        super().save(*args,**kwargs)

    def get_absolute_url(self):
        return reverse('posts:detail',kwargs={'username':self.user.username,'pk':self.pk})

    class Meta:
        ordering = ['-created_at']
        unique_together = ['user','message']
</code>```

urls.py:

```<code>from django.urls import path

from . import views

app_name = 'posts'

urlpatterns = [
    path('',views.PostListView.as_view(),name='list'),
    path('create/',views.PostCreateView.as_view(),name='create'),
    path('by/<username>/',views.UserPosts.as_view(),name='for_user'),
    path('by/<username>/<pk>/',views.PostDetailView.as_view(),name='detail'),
    path('delete/<pk>/',views.PostDeleteView.as_view(),name='delete')
]
</code>```

views.py:

```<code>from django.shortcuts import render
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse_lazy

from django.views import generic
from django.http import Http404

from braces.views import SelectRelatedMixin

from . import models
from . import forms

from django.contrib.auth import get_user_model
User = get_user_model()

# Create your views here.

class PostListView(SelectRelatedMixin,generic.ListView):
    model = models.Post
    select_related = ('user','group')

class UserPosts(generic.ListView):
    model = models.Post
    template_name = 'posts/user_post_list.html'

    def get_queryset(self):
        try:
            self.post_user = User.objects.prefetch_related("posts").get(
                username__iexact=self.kwargs.get("username")
            )
        except User.DoesNotExist:
            raise Http404
        else:
            return self.post_user.posts.all()

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["post_user"] = self.post_user
        return context

class PostDetailView(SelectRelatedMixin,generic.DetailView):
    model = models.Post
    select_related = ('user','group')

    def get_queryset(self):
        queryset = super().get_queryset()
        return queryset.filter(user__username__iexact=self.kwargs.get('username'))

class PostCreateView(LoginRequiredMixin,SelectRelatedMixin,generic.CreateView):

    fields = ('message','group')
    model = models.Post

    def form_valid(self,form):
        self.object = form.save(commit=False)
        self.object.user = self.request.user
        self.object.save()
        return super().form_valid(form)

class PostDeleteView(LoginRequiredMixin,SelectRelatedMixin,generic.DeleteView):
    model = models.Post
    select_related = ('user','group')
    success_url = reverse_lazy('posts:list')

    def get_queryset(self):
        queryset = super().get_queryset()
        return queryset.filter(user_id=self.request.user.id)

        def delete(self,*args,**kwargs):
            message.success(self.request,'Post Deleted')
            return super().delete(*args,**kwargs)

</code>```

_post.html:

```<code><div class="post media">
  <h3>{{post.message_html|safe}}</h3>
  <div class="media-body">
    <strong>{{post.user.username}}</strong>
    <h5 class="media-heading">
      <span class="username">
                <a href="{% url 'posts:for_user' username=post.user.username %}">@{{ post.user.username }}</a>
            </span>
            <time class="time">
                <a href="{% url 'posts:detail' username=post.user.username pk=post.pk %}">{{ post.created_at }}</a>
            </time>
      {% if post.group %}
      <span class="group-name">in <a href="#">{{ post.group.name }}</a></span>
      {% endif %}

    </h5>
    <div class="media-footer">
      {% if user.is_authenticated and post.user == user %}
        <a href="{% url 'posts:delete' pk=post.pk %}" title='delete' class="btn btn-simple">
          <span class="fas fa-trash-alt text-danger" aria-hidden="True"></span>
          <span class="text-danger icon-label">Delete</span>
        </a>
      {% endif %}
    </div>
  </div>
</div>
</code>```

答:
As far as I understand problem is empty username. Default pattern requires it to be at least one symbol ['posts/by/(?P[^/]+)/$']. So likely you didn't fetch model properly or there is no user for post.

Error by the way is pretty verbose on this. It shows pattern and arguments, you need to read it more careful.

Body:
I get a NoReverseMatch error with a blank string for kwargs. Am I doing something wrong in the models.py file that doesn't save the username associated with the post?

NoReverseMatch at /groups/posts/in/nasa-rocks/ Reverse for 'for_user'
  with keyword arguments '{'username': ''}' not found. 1 pattern(s)
  tried: ['posts/by/(?P[^/]+)/$']

models.py:

from django.db import models
from django.urls import reverse
from django.conf import settings

# Create your models here.

import misaka

from groups.models import Group

from django.contrib.auth import get_user_model
User = get_user_model()

class Post(models.Model):
    user = models.ForeignKey(User,related_name='posts',on_delete='CASCADE')
    group = models.ForeignKey(Group,related_name='posts',null=True,blank=True,on_delete='CASCADE')
    created_at = models.DateTimeField(auto_now=True)
    message = models.TextField()
    message_html = models.TextField(editable=False)

    def __str__(self):
        return self.message

    def save(self,*args,**kwargs):
        self.message_html = misaka.html(self.message)
        super().save(*args,**kwargs)

    def get_absolute_url(self):
        return reverse('posts:detail',kwargs={'username':self.user.username,'pk':self.pk})

    class Meta:
        ordering = ['-created_at']
        unique_together = ['user','message']

urls.py:

from django.urls import path

from . import views

app_name = 'posts'

urlpatterns = [
    path('',views.PostListView.as_view(),name='list'),
    path('create/',views.PostCreateView.as_view(),name='create'),
    path('by/<username>/',views.UserPosts.as_view(),name='for_user'),
    path('by/<username>/<pk>/',views.PostDetailView.as_view(),name='detail'),
    path('delete/<pk>/',views.PostDeleteView.as_view(),name='delete')
]

views.py:

from django.shortcuts import render
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse_lazy

from django.views import generic
from django.http import Http404

from braces.views import SelectRelatedMixin

from . import models
from . import forms

from django.contrib.auth import get_user_model
User = get_user_model()

# Create your views here.

class PostListView(SelectRelatedMixin,generic.ListView):
    model = models.Post
    select_related = ('user','group')

class UserPosts(generic.ListView):
    model = models.Post
    template_name = 'posts/user_post_list.html'

    def get_queryset(self):
        try:
            self.post_user = User.objects.prefetch_related("posts").get(
                username__iexact=self.kwargs.get("username")
            )
        except User.DoesNotExist:
            raise Http404
        else:
            return self.post_user.posts.all()

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["post_user"] = self.post_user
        return context

class PostDetailView(SelectRelatedMixin,generic.DetailView):
    model = models.Post
    select_related = ('user','group')

    def get_queryset(self):
        queryset = super().get_queryset()
        return queryset.filter(user__username__iexact=self.kwargs.get('username'))

class PostCreateView(LoginRequiredMixin,SelectRelatedMixin,generic.CreateView):

    fields = ('message','group')
    model = models.Post

    def form_valid(self,form):
        self.object = form.save(commit=False)
        self.object.user = self.request.user
        self.object.save()
        return super().form_valid(form)

class PostDeleteView(LoginRequiredMixin,SelectRelatedMixin,generic.DeleteView):
    model = models.Post
    select_related = ('user','group')
    success_url = reverse_lazy('posts:list')

    def get_queryset(self):
        queryset = super().get_queryset()
        return queryset.filter(user_id=self.request.user.id)

        def delete(self,*args,**kwargs):
            message.success(self.request,'Post Deleted')
            return super().delete(*args,**kwargs)

_post.html:

{{post.message_html|safe}}

    {{post.user.username}}

                @{{ post.user.username }}

            <time class="time">
                {{ post.created_at }}
            </time>
      {% if post.group %}
      in {{ post.group.name }}
      {% endif %}

      {% if user.is_authenticated and post.user == user %}

          Delete

      {% endif %}


问:
Load ImageView from URL into RemoteView of a Home Screen Widget
I'm developing a simple Widget to my Android app based on the Google  StackWidget sample: https://android.googlesource.com/platform/development/+/master/samples/StackWidget/src/com/example/android/stackwidget/StackWidgetService.java

I'm using the Glide image library and trying to populate an ImageView on getViewAt method of StackWidgetService class that extends RemoteViewsService. My code is similar to:

```<code>Handler uiHandler = new Handler(Looper.getMainLooper());
uiHandler.post(() ->
    Glide.with(context)
        .asBitmap()
        .load(widgetItems.get(position).image_url)
        .into(new SimpleTarget<Bitmap>(512, 512) {
            @Override
            public void onResourceReady(Bitmap bitmap, Transition transition) {
                rv.setImageViewBitmap(R.id.widget_item_image, bitmap);
            }
        })
);
</code>```

What's the best way of loading images from an URL to populate a RemoteView from an Android Widget?

答:
Another example in java.

```<code>  static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
                            int appWidgetId) {
    String url = "https://firebasestorage.googleapis.com/v0/b/telling-299f3.appspot.com/o/POSTS%2Fcropped1099087212.jpg?alt=media&token=6a3bca19-6483-484d-a7e3-64c25a8a77a8";

    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.app_widget);

    Intent intent = new Intent(context, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

    AppWidgetTarget awt = new AppWidgetTarget(context, R.id.widget_post_image, views, appWidgetId) {
        @Override
        public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
            super.onResourceReady(resource, transition);
        }
    };

    RequestOptions options = new RequestOptions().
            override(300, 300).placeholder(R.drawable.post_placeholder).error(R.drawable.post_placeholder);

    Glide.with(context.getApplicationContext())
            .asBitmap()
            .load(url)
            .apply(options)
            .into(awt);
    //views.setImageViewBitmap(R.id.widget_post_image, bitmap);

    views.setOnClickPendingIntent(R.id.widget_post_image, pendingIntent);

    // Instruct the widget manager to update the widget
    appWidgetManager.updateAppWidget(appWidgetId, views);
}
</code>```

my app_widget.xml file contains

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#09C"
android:padding="@dimen/widget_margin">

<ImageView
    android:id="@+id/widget_post_image"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:src="@drawable/placeholder_image_one" />
</LinearLayout>
</code>```

Body:
I'm developing a simple Widget to my Android app based on the Google  StackWidget sample: https://android.googlesource.com/platform/development/+/master/samples/StackWidget/src/com/example/android/stackwidget/StackWidgetService.java

I'm using the Glide image library and trying to populate an ImageView on getViewAt method of StackWidgetService class that extends RemoteViewsService. My code is similar to:

Handler uiHandler = new Handler(Looper.getMainLooper());
uiHandler.post(() ->
    Glide.with(context)
        .asBitmap()
        .load(widgetItems.get(position).image_url)
        .into(new SimpleTarget<Bitmap>(512, 512) {
            @Override
            public void onResourceReady(Bitmap bitmap, Transition transition) {
                rv.setImageViewBitmap(R.id.widget_item_image, bitmap);
            }
        })
);

What's the best way of loading images from an URL to populate a RemoteView from an Android Widget?

Body:
Another example in java.

  static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
                            int appWidgetId) {
    String url = "https://firebasestorage.googleapis.com/v0/b/telling-299f3.appspot.com/o/POSTS%2Fcropped1099087212.jpg?alt=media&token=6a3bca19-6483-484d-a7e3-64c25a8a77a8";

    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.app_widget);

    Intent intent = new Intent(context, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

    AppWidgetTarget awt = new AppWidgetTarget(context, R.id.widget_post_image, views, appWidgetId) {
        @Override
        public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
            super.onResourceReady(resource, transition);
        }
    };

    RequestOptions options = new RequestOptions().
            override(300, 300).placeholder(R.drawable.post_placeholder).error(R.drawable.post_placeholder);

    Glide.with(context.getApplicationContext())
            .asBitmap()
            .load(url)
            .apply(options)
            .into(awt);
    //views.setImageViewBitmap(R.id.widget_post_image, bitmap);

    views.setOnClickPendingIntent(R.id.widget_post_image, pendingIntent);

    // Instruct the widget manager to update the widget
    appWidgetManager.updateAppWidget(appWidgetId, views);
}

my app_widget.xml file contains

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#09C"
android:padding="@dimen/widget_margin">

<ImageView
    android:id="@+id/widget_post_image"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:src="@drawable/placeholder_image_one" />
</LinearLayout>


问:
Where to store html code for jQuery?
In some scripts long html blocks are added to selector. For example

```<code>$("#test").prepend($('<div id="tester">..long html tags..</div>').hide().fadeIn(2000));
</code>```

Where it would be better to store that large html blocks? Directly, in variable, in html code, text file or other.

Thank you.

答: Because javascript (therefor jquery) is interpreted code it does not really matter from a perfomance perspective. "Better" becomes a subjective choice and with that it becomes a question of readablity and reusablity. If you have text patterns that are going to be reused then you definitly want to use some manner of template. After that it is purely dealers' choice.</p>

Title: Where to store html code for jQuery?

Body:
In some scripts long html blocks are added to selector. For example

$("#test").prepend($('
..long html tags..
').hide().fadeIn(2000));

Where it would be better to store that large html blocks? Directly, in variable, in html code, text file or other.

Thank you.


问:
How can one route a search URL which has a query string embedded?
I am working on an express application and I have two GET URLs. One fetches all resources in the database but is right-protected(needs authentication and admin access) while the other fetches resources based on a search parameter(query string).

The route that requires authentication looks like so:

carRouter.get('/car', verifyToken, isAdmin, fetchAllCarAds);

This means that the admin has to be logged in first and then a check is carried out to ascertain whether he is truly an admin before he is given access. Now I have another GET route that doesn't require authentication like so
:

carRouter.get('/car?status=unsold', filterUnsoldCars);.

I understand that express does not allow routing based on query strings so how do I ensure that the request that does not require authentication(query string) is accessible in the one without query string?

答:
I fixed it by placing it before the verifyToken function and it worked. I would like to learn of other ways of doing it if there are. Thanks

carRouter.get('/car', filterUnsoldCars, verifyToken, isAdminDummy, fetchAllCarAds);


问:
In Excel how can I update an external file if it has so many rows that it cannot be loaded?
I have a .csv file that has around 2 million rows, and I want to add a new column. Problem is, I could manage to that by losing a lot of data (basicly everything above ~1,1m rows). When I used connection to the external file (so that I could read all rows), and made changes to it in Power Query, the changes was not saved to the .csv file.</p>

答:
You can apply one of several solutions:

Using a text editor which can handle huge files, save the csv files into smaller chunks. Apply the modifications to each chunk. Join chunks again to get the desired file.

Create a "small" program yourself, which loads the csv line by line and applies the modification, adding the resulting data to a second file.

Maybe some other software can handle that size of a csv. Patch the LibreOffice for this purpose, to handle 2000000+ lines - the source code is available :)


问:
How to temporarily define a condition, within a block?
In Common Lisp (specifically SBCL in my case), it is common to define exceptions (known as "conditions") using the define-condition macro. This defines the condition globally, within the current package.

Is there a way to define a condition locally, within a specific scope? Or, alternatively, some other idiomatic way to prematurely exit a scope with a value, without polluting the global namespace?

```<code>(with-conditions
  (block
    (...)
    (prematurely-exit-block-with some-data)
    (...))
  (when-condition-happens (some data) ...))
</code>```

答:
Is there a way to define a condition locally, within a specific scope?

No.

Or, alternatively, some other idiomatic way to prematurely exit a scope with a value, without polluting the global namespace?

Common Lisp has several constructs for such control flow, where one or more values are returned: RETURN, RETURN-FROM, THROW, ...

RETURN returns from a block named NIL

RETURN-FROM returns from a named block

THROW jumps to a catch tag, which got established via CATCH

return and return-from are using lexical blocks. catch establishes a dynamic scope for its tag.

Body:
In Common Lisp (specifically SBCL in my case), it is common to define exceptions (known as "conditions") using the define-condition macro. This defines the condition globally, within the current package.

Is there a way to define a condition locally, within a specific scope? Or, alternatively, some other idiomatic way to prematurely exit a scope with a value, without polluting the global namespace?

(with-conditions
  (block
    (...)
    (prematurely-exit-block-with some-data)
    (...))
  (when-condition-happens (some data) ...))