问:
How to enumerate a list within a list that was enumerated
The lists are made up as I do not have my code in front of me.

I have one list that has two items: listA = [Region1, Region2]

Within those lists (they are objects with embedded information originally) they each have a set of items. frame1 has three items; let's say layer1 = [VA, GA, NC] and frame2 has two items; layer2 = [WI, MI].

So, hierarchically:

```<code>Region1:
    VA
    GA
    NC
Region2:
    WI
    MI
</code>```

What I am trying to do is enumerate the parent layers to be:

```<code>0 Region1
1 Region2
</code>```

While also enumerating from each respective sublist so the result would look something like:

```<code>0 Region1
0 VA
1 GA
2 NC
1 Region2
0 WI
1 MI
</code>```

The first enumeration is simple, but I am lost on how to enumerate properly using any nested loop. I keep getting all 5 layers for each frame no matter how I've gone about it.

Any tips, tricks, ideas? I specifically need this to work with the basic enumerate function; not the Enum module.

答:
You iterate over the outer, and the inner enumerations:

```<code>listA = [['abc', 'def'], ['ghi', 'klm'], ['nop', 'qrs']]
for idx, inner in enumerate(listA):
    print('Region', idx)
    for jdx, elt in enumerate(inner):
        print(jdx, elt)
</code>```

output:

```<code>Region 0
0 abc
1 def
Region 1
0 ghi
1 klm
Region 2
0 nop
1 qrs
</code>```

Body:
The lists are made up as I do not have my code in front of me.

I have one list that has two items: listA = [Region1, Region2]

Within those lists (they are objects with embedded information originally) they each have a set of items. frame1 has three items; let's say layer1 = [VA, GA, NC] and frame2 has two items; layer2 = [WI, MI].

So, hierarchically:

Region1:
    VA
    GA
    NC
Region2:
    WI
    MI

What I am trying to do is enumerate the parent layers to be:

0 Region1
1 Region2

While also enumerating from each respective sublist so the result would look something like:

0 Region1
0 VA
1 GA
2 NC
1 Region2
0 WI
1 MI

The first enumeration is simple, but I am lost on how to enumerate properly using any nested loop. I keep getting all 5 layers for each frame no matter how I've gone about it.

Any tips, tricks, ideas? I specifically need this to work with the basic enumerate function; not the Enum module.

Body:
You iterate over the outer, and the inner enumerations:

listA = [['abc', 'def'], ['ghi', 'klm'], ['nop', 'qrs']]
for idx, inner in enumerate(listA):
    print('Region', idx)
    for jdx, elt in enumerate(inner):
        print(jdx, elt)

output:

Region 0
0 abc
1 def
Region 1
0 ghi
1 klm
Region 2
0 nop
1 qrs


来源: stackexchange

问:
Android - SQLite3 Multiple Columns
I am having trouble getting my code to insert data from two text boxes into two seperate columns.

Input:

Name=1 Rank=2

Current output:

(Row 1) Name=11 Rank=null

Desired output:

(Row 1) Name=1 Rank=2

Any help would be greatly appreciated.

Code on the add page (text boxes + save button):

```<code>package org.x.x;

import org.x.x.R;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class Add extends Foundation {

 private EditText input, input2;
 private Button saveButton;

 @Override
 public void onCreate(final Bundle savedInstanceState) {
  Log.d(MyApplication.APP_NAME, "onCreate");
     super.onCreate(savedInstanceState);

     this.setContentView(R.layout.add);

     // get "Application" object for shared state or creating of expensive resources - like DataHelper
     // (this is not recreated as often as each Activity)
     this.application = (MyApplication) this.getApplication();

     // inflate views
     this.input = (EditText) this.findViewById(R.id.Beverage_Txt);
     this.input2 = (EditText) this.findViewById(R.id.Rank_Txt);
     this.saveButton = (Button) this.findViewById(R.id.save_button);
     //this.deleteButton = (Button) this.findViewById(R.id.del_button);
     //this.output = (TextView) this.findViewById(R.id.out_text);

     // save new data to database (when save button is clicked)
     this.saveButton.setOnClickListener(new OnClickListener() {
       public void onClick(final View v) {
        new InsertDataTask().execute(Add.this.input.getText().toString(), Add.this.input2.getText().toString());
          Add.this.input.setText("");
          Add.this.input2.setText("");
       }
       });
 }

 @Override
 public void onSaveInstanceState(final Bundle b) {
  Log.d(MyApplication.APP_NAME, "onSaveInstanceState");
     if ((this.input.getText().toString() != null) && (this.input.getText().toString().length() > 0)) {
      b.putString(Add.NAME, this.input.getText().toString());
     }
     if ((this.input2.getText().toString() != null) && (this.input2.getText().toString().length() > 0)) {
      b.putString(Add.RANK, this.input2.getText().toString());
     }
     super.onSaveInstanceState(b);
 }

 @Override
 public void onRestoreInstanceState(final Bundle b) {
  super.onRestoreInstanceState(b);
  Log.d(MyApplication.APP_NAME, "onRestoreInstanceState");
  String name = b.getString(Foundation.NAME);
  String rank = b.getString(Foundation.RANK);
  if (name != null) {
      // use onSaveInstanceState/onRestoreInstance state to manage state when orientation is changed (and whenever restarted)
         // put some text in input box, then rotate screen, text should remain
         // COMMENT this out, and try again, text won't be there - you need to maintain this state - esp for orientation changes
         // (you can rotate the screen in the emulator by pressing 9 on numeric keypad)
         this.input.setText(name);
  }
  if (rank != null) {
      // use onSaveInstanceState/onRestoreInstance state to manage state when orientation is changed (and whenever restarted)
         // put some text in input box, then rotate screen, text should remain
         // COMMENT this out, and try again, text won't be there - you need to maintain this state - esp for orientation changes
         // (you can rotate the screen in the emulator by pressing 9 on numeric keypad)
         this.input2.setText(rank);
  }
 }

 private class InsertDataTask extends AsyncTask<String, Void, Void> {
       private final ProgressDialog dialog = new ProgressDialog(Add.this);

       // can use UI thread here
       protected void onPreExecute() {
          this.dialog.setMessage("Inserting data...");
          this.dialog.show();
       }

       // automatically done on worker thread (separate from UI thread)
       protected Void doInBackground(final String... args) {
          Add.this.application.getDataHelper().insert(args[0], args[0]);
          return null;
       }

       // can use UI thread here
       protected void onPostExecute(final Void unused) {
          if (this.dialog.isShowing()) {
             this.dialog.dismiss();
          }
          // reset the output view by retrieving the new data
          // (note, this is a naive example, in the real world it might make sense
          // to have a cache of the data and just append to what is already there, or such
          // in order to cut down on expensive database operations)
          //new SelectDataTask().execute();
       }
 }

 @Override
 public void onBackPressed() {
  this.startActivity(new Intent(Add.this, Compare.class));
 }
}
</code>```

Datahelper code:

```<code>package org.x.x;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

public class DataHelper {

   private static final String DATABASE_NAME = "example.db";
   private static final int DATABASE_VERSION = 1;
   private static final String TABLE_NAME = "table1";

   private Context context;
   private SQLiteDatabase db;

   private SQLiteStatement insertStmt;

   private static final String INSERT = "insert into " + TABLE_NAME + "(name, rank) values (?, ?)";

   public DataHelper(Context context) {
      this.context = context;
      OpenHelper openHelper = new OpenHelper(this.context);
      this.db = openHelper.getWritableDatabase();
      this.insertStmt = this.db.compileStatement(INSERT);
   }

   public SQLiteDatabase getDb() {
      return this.db;
   }

   public long insert(String name, String rank) {
      this.insertStmt.bindString(1, name + rank);

      return this.insertStmt.executeInsert();
   }

   public void deleteAll() {
      this.db.delete(TABLE_NAME, null, null);
   }

   public List<String> selectAll() {
      List<String> list = new ArrayList<String>();
      Cursor cursor = this.db.query(TABLE_NAME, new String[] { "name", "rank" }, null, null, null, null, "id desc");
      if (cursor.moveToFirst()) {
         do {
            list.add(cursor.getString(0));
            list.add(cursor.getString(1));
         } while (cursor.moveToNext());
      }
      if (cursor != null && !cursor.isClosed()) {
         cursor.close();
      }
      return list;
   }

   private static class OpenHelper extends SQLiteOpenHelper {

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

      @Override
      public void onCreate(SQLiteDatabase db) {
         db.execSQL("CREATE TABLE " + TABLE_NAME + " (id INTEGER PRIMARY KEY, name TEXT, rank TEXT)");
      }

      @Override
      public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
         Log.w("Example", "Upgrading database, this will drop tables and recreate.");
         db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
         onCreate(db);
      }
   }
}
</code>```

Template code (shared resources):

```<code>package org.x.x;

import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.widget.TextView;

public class Foundation extends Activity {

   public static final String NAME = "NAME";
   public static final String RANK = "RANK";

   public MyApplication application;

   public TextView output;

   public class SelectDataTask extends AsyncTask<String, Void, String> {
       private final ProgressDialog dialog = new ProgressDialog(Foundation.this);

       // can use UI thread here
       protected void onPreExecute() {
          this.dialog.setMessage("Selecting data...");
          this.dialog.show();
       }

       // automatically done on worker thread (separate from UI thread)
       protected String doInBackground(final String... args) {
          List<String> names = Foundation.this.application.getDataHelper().selectAll();
          /*List<String> ranks = Foundation.this.application.getDataHelper().selectAll();*/
          StringBuilder sb = new StringBuilder();
          for (String name : names) {
             sb.append(name + "\n");
          }
          /*for (String rank : ranks) {
        sb.append(rank + "\n");
       }*/
          return sb.toString();
       }

       // can use UI thread here
       protected void onPostExecute(final String result) {
          if (this.dialog.isShowing()) {
             this.dialog.dismiss();
          }
          Foundation.this.output.setText(result);
       }
 }
}
</code>```

MyApplication code:

```<code>package org.x.x;

import android.app.Application;
import android.util.Log;

public class MyApplication extends Application {

   public static final String APP_NAME = "x";

   private DataHelper dataHelper;

   @Override
   public void onCreate() {
      super.onCreate();
      Log.d(APP_NAME, "APPLICATION onCreate");
      this.dataHelper = new DataHelper(this);
   }

   @Override
   public void onTerminate() {
      Log.d(APP_NAME, "APPLICATION onTerminate");
      super.onTerminate();
   }

   public DataHelper getDataHelper() {
      return this.dataHelper;
   }

   public void setDataHelper(DataHelper dataHelper) {
      this.dataHelper = dataHelper;
   }
}
</code>```

答:
I found the problem, changed (on Add page):

```<code>      protected Void doInBackground(final String... args) {
         Add.this.application.getDataHelper().insert(args[0], args[0]);
         return null;
      }
</code>```

To:

```<code>      protected Void doInBackground(final String... args) {
         Add.this.application.getDataHelper().insert(args[0], args[1]);
         return null;
      }
</code>```

ContentLicense: CC BY-SA 2.5

Title: Android - SQLite3 Multiple Columns

Body:
I am having trouble getting my code to insert data from two text boxes into two seperate columns.

Input:

Name=1 Rank=2

Current output:

(Row 1) Name=11 Rank=null

Desired output:

(Row 1) Name=1 Rank=2

Any help would be greatly appreciated.

Code on the add page (text boxes + save button):

package org.x.x;

import org.x.x.R;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class Add extends Foundation {

 private EditText input, input2;
 private Button saveButton;

 @Override
 public void onCreate(final Bundle savedInstanceState) {
  Log.d(MyApplication.APP_NAME, "onCreate");
     super.onCreate(savedInstanceState);

     this.setContentView(R.layout.add);

     // get "Application" object for shared state or creating of expensive resources - like DataHelper
     // (this is not recreated as often as each Activity)
     this.application = (MyApplication) this.getApplication();

     // inflate views
     this.input = (EditText) this.findViewById(R.id.Beverage_Txt);
     this.input2 = (EditText) this.findViewById(R.id.Rank_Txt);
     this.saveButton = (Button) this.findViewById(R.id.save_button);
     //this.deleteButton = (Button) this.findViewById(R.id.del_button);
     //this.output = (TextView) this.findViewById(R.id.out_text);

     // save new data to database (when save button is clicked)
     this.saveButton.setOnClickListener(new OnClickListener() {
       public void onClick(final View v) {
        new InsertDataTask().execute(Add.this.input.getText().toString(), Add.this.input2.getText().toString());
          Add.this.input.setText("");
          Add.this.input2.setText("");
       }
       });
 }

 @Override
 public void onSaveInstanceState(final Bundle b) {
  Log.d(MyApplication.APP_NAME, "onSaveInstanceState");
     if ((this.input.getText().toString() != null) && (this.input.getText().toString().length() > 0)) {
      b.putString(Add.NAME, this.input.getText().toString());
     }
     if ((this.input2.getText().toString() != null) && (this.input2.getText().toString().length() > 0)) {
      b.putString(Add.RANK, this.input2.getText().toString());
     }
     super.onSaveInstanceState(b);
 }

 @Override
 public void onRestoreInstanceState(final Bundle b) {
  super.onRestoreInstanceState(b);
  Log.d(MyApplication.APP_NAME, "onRestoreInstanceState");
  String name = b.getString(Foundation.NAME);
  String rank = b.getString(Foundation.RANK);
  if (name != null) {
      // use onSaveInstanceState/onRestoreInstance state to manage state when orientation is changed (and whenever restarted)
         // put some text in input box, then rotate screen, text should remain
         // COMMENT this out, and try again, text won't be there - you need to maintain this state - esp for orientation changes
         // (you can rotate the screen in the emulator by pressing 9 on numeric keypad)
         this.input.setText(name);
  }
  if (rank != null) {
      // use onSaveInstanceState/onRestoreInstance state to manage state when orientation is changed (and whenever restarted)
         // put some text in input box, then rotate screen, text should remain
         // COMMENT this out, and try again, text won't be there - you need to maintain this state - esp for orientation changes
         // (you can rotate the screen in the emulator by pressing 9 on numeric keypad)
         this.input2.setText(rank);
  }
 }

 private class InsertDataTask extends AsyncTask<String, Void, Void> {
       private final ProgressDialog dialog = new ProgressDialog(Add.this);

       // can use UI thread here
       protected void onPreExecute() {
          this.dialog.setMessage("Inserting data...");
          this.dialog.show();
       }

       // automatically done on worker thread (separate from UI thread)
       protected Void doInBackground(final String... args) {
          Add.this.application.getDataHelper().insert(args[0], args[0]);
          return null;
       }

       // can use UI thread here
       protected void onPostExecute(final Void unused) {
          if (this.dialog.isShowing()) {
             this.dialog.dismiss();
          }
          // reset the output view by retrieving the new data
          // (note, this is a naive example, in the real world it might make sense
          // to have a cache of the data and just append to what is already there, or such
          // in order to cut down on expensive database operations)
          //new SelectDataTask().execute();
       }
 }

 @Override
 public void onBackPressed() {
  this.startActivity(new Intent(Add.this, Compare.class));
 }
}

Datahelper code:

package org.x.x;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

public class DataHelper {

   private static final String DATABASE_NAME = "example.db";
   private static final int DATABASE_VERSION = 1;
   private static final String TABLE_NAME = "table1";

   private Context context;
   private SQLiteDatabase db;

   private SQLiteStatement insertStmt;

   private static final String INSERT = "insert into " + TABLE_NAME + "(name, rank) values (?, ?)";

   public DataHelper(Context context) {
      this.context = context;
      OpenHelper openHelper = new OpenHelper(this.context);
      this.db = openHelper.getWritableDatabase();
      this.insertStmt = this.db.compileStatement(INSERT);
   }

   public SQLiteDatabase getDb() {
      return this.db;
   }

   public long insert(String name, String rank) {
      this.insertStmt.bindString(1, name + rank);

      return this.insertStmt.executeInsert();
   }

   public void deleteAll() {
      this.db.delete(TABLE_NAME, null, null);
   }

   public List<String> selectAll() {
      List<String> list = new ArrayList<String>();
      Cursor cursor = this.db.query(TABLE_NAME, new String[] { "name", "rank" }, null, null, null, null, "id desc");
      if (cursor.moveToFirst()) {
         do {
            list.add(cursor.getString(0));
            list.add(cursor.getString(1));
         } while (cursor.moveToNext());
      }
      if (cursor != null && !cursor.isClosed()) {
         cursor.close();
      }
      return list;
   }

   private static class OpenHelper extends SQLiteOpenHelper {

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

      @Override
      public void onCreate(SQLiteDatabase db) {
         db.execSQL("CREATE TABLE " + TABLE_NAME + " (id INTEGER PRIMARY KEY, name TEXT, rank TEXT)");
      }

      @Override
      public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
         Log.w("Example", "Upgrading database, this will drop tables and recreate.");
         db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
         onCreate(db);
      }
   }
}

Template code (shared resources):

package org.x.x;

import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.widget.TextView;

public class Foundation extends Activity {

   public static final String NAME = "NAME";
   public static final String RANK = "RANK";

   public MyApplication application;

   public TextView output;

   public class SelectDataTask extends AsyncTask<String, Void, String> {
       private final ProgressDialog dialog = new ProgressDialog(Foundation.this);

       // can use UI thread here
       protected void onPreExecute() {
          this.dialog.setMessage("Selecting data...");
          this.dialog.show();
       }

       // automatically done on worker thread (separate from UI thread)
       protected String doInBackground(final String... args) {
          List<String> names = Foundation.this.application.getDataHelper().selectAll();
          /*List<String> ranks = Foundation.this.application.getDataHelper().selectAll();*/
          StringBuilder sb = new StringBuilder();
          for (String name : names) {
             sb.append(name + "\n");
          }
          /*for (String rank : ranks) {
        sb.append(rank + "\n");
       }*/
          return sb.toString();
       }

       // can use UI thread here
       protected void onPostExecute(final String result) {
          if (this.dialog.isShowing()) {
             this.dialog.dismiss();
          }
          Foundation.this.output.setText(result);
       }
 }
}

MyApplication code:

package org.x.x;

import android.app.Application;
import android.util.Log;

public class MyApplication extends Application {

   public static final String APP_NAME = "x";

   private DataHelper dataHelper;

   @Override
   public void onCreate() {
      super.onCreate();
      Log.d(APP_NAME, "APPLICATION onCreate");
      this.dataHelper = new DataHelper(this);
   }

   @Override
   public void onTerminate() {
      Log.d(APP_NAME, "APPLICATION onTerminate");
      super.onTerminate();
   }

   public DataHelper getDataHelper() {
      return this.dataHelper;
   }

   public void setDataHelper(DataHelper dataHelper) {
      this.dataHelper = dataHelper;
   }
}

Body:
I found the problem, changed (on Add page):

      protected Void doInBackground(final String... args) {
         Add.this.application.getDataHelper().insert(args[0], args[0]);
         return null;
      }

To:

      protected Void doInBackground(final String... args) {
         Add.this.application.getDataHelper().insert(args[0], args[1]);
         return null;
      }


问:
Why can't I see any changes in my "Place" tab
I want each tab to to show something different.  To start things off, I want to make changes to the Place tab.  The problem is, none of the changes are being reflected in the Android Simulator.

Image of what I'm referring to

In this case, I want the text something to show up, but it's not.  What am I doing wrong?  I've also included code that might be relevant to this issue.

Here's MainActivity.java:

```<code>import android.net.Uri;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.Arrays;

public class MainActivity extends AppCompatActivity implements Place.OnFragmentInteractionListener, Profile.OnFragmentInteractionListener, Take.OnFragmentInteractionListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TabLayout tabLayout = (TabLayout)findViewById(R.id.tabLayout);
        tabLayout.addTab(tabLayout.newTab().setText("Place"));
        tabLayout.addTab(tabLayout.newTab().setText("Take"));
        tabLayout.addTab(tabLayout.newTab().setText("Profile"));

        final ViewPager viewPager = (ViewPager)findViewById(R.id.pager);
        final PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager(),tabLayout.getTabCount());
        viewPager.setAdapter(adapter);
        viewPager.setOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    @Override
    public void onFragmentInteraction(Uri uri) {

    }
}
</code>```

Here's fragment_place.xml:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Place"
        android:layout_centerInParent="true"
        android:textSize="30dp"
        android:id="@+id/textView" />

    <EditText
        android:id="@+id/editText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="41dp"
        android:layout_marginStart="41dp"
        android:layout_marginTop="80dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Something" />

</RelativeLayout>
</code>```

Here's PagerAdapter.java:

```<code>import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;

public class PagerAdapter extends FragmentStatePagerAdapter {

    int mNoOfTabs;

    public PagerAdapter(FragmentManager fm, int NumberOfTabs) {
        super(fm);
        this.mNoOfTabs = NumberOfTabs; // set global number of tabs to local number of tabs
    }

    @Override
    public Fragment getItem(int position) {
        switch(position) {
            case 0:
                Place place = new Place();
                return place;
            case 1:
                Profile profile = new Profile();
                return profile;
            case 2:
                Take take = new Take();
                return take;
            default:
                return null;
        }
    }

    @Override
    public int getCount() {
        return 0;
    }
}
</code>```

答: I don't see in your code where you provide the layout xml to the fragment</p>

ContentLicense: CC BY-SA 3.0

Body:
I want each tab to to show something different.  To start things off, I want to make changes to the Place tab.  The problem is, none of the changes are being reflected in the Android Simulator.

Image of what I'm referring to

In this case, I want the text something to show up, but it's not.  What am I doing wrong?  I've also included code that might be relevant to this issue.

Here's MainActivity.java:

import android.net.Uri;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.Arrays;

public class MainActivity extends AppCompatActivity implements Place.OnFragmentInteractionListener, Profile.OnFragmentInteractionListener, Take.OnFragmentInteractionListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TabLayout tabLayout = (TabLayout)findViewById(R.id.tabLayout);
        tabLayout.addTab(tabLayout.newTab().setText("Place"));
        tabLayout.addTab(tabLayout.newTab().setText("Take"));
        tabLayout.addTab(tabLayout.newTab().setText("Profile"));

        final ViewPager viewPager = (ViewPager)findViewById(R.id.pager);
        final PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager(),tabLayout.getTabCount());
        viewPager.setAdapter(adapter);
        viewPager.setOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    @Override
    public void onFragmentInteraction(Uri uri) {

    }
}

Here's fragment_place.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Place"
        android:layout_centerInParent="true"
        android:textSize="30dp"
        android:id="@+id/textView" />

    <EditText
        android:id="@+id/editText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="41dp"
        android:layout_marginStart="41dp"
        android:layout_marginTop="80dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Something" />

</RelativeLayout>

Here's PagerAdapter.java:

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;

public class PagerAdapter extends FragmentStatePagerAdapter {

    int mNoOfTabs;

    public PagerAdapter(FragmentManager fm, int NumberOfTabs) {
        super(fm);
        this.mNoOfTabs = NumberOfTabs; // set global number of tabs to local number of tabs
    }

    @Override
    public Fragment getItem(int position) {
        switch(position) {
            case 0:
                Place place = new Place();
                return place;
            case 1:
                Profile profile = new Profile();
                return profile;
            case 2:
                Take take = new Take();
                return take;
            default:
                return null;
        }
    }

    @Override
    public int getCount() {
        return 0;
    }
}


问:
Rails + Rspec: Database cleaner gem is not working
I need some guidance on how to get database cleaner to work for my rails app. ID of records keep on increasing for each test and is not being wiped out.

I've set up a test to check if database cleaner works and it fails.

spec/models/concerns/database_cleaner_test.rb

```<code>require 'rails_helper'

describe "db_cleaner" do

    let!(:article) { FactoryGirl.create(:article) }

    it "first test" do
      expect(Article.all.count).to eq(1)
      expect(Article.last.id).to eq(1)
    end

    it "should clean db" do
      expect(Article.all.count).to eq(1)
      expect(Article.last.id).to eq(1)
    end

end
</code>```

Failures:

```<code>  1) db_cleaner should clean db
     Failure/Error: expect(Article.last.id).to eq(1)

       expected: 1
            got: 2

       (compared using ==)
</code>```

Setup:

```<code>gem 'rails', '~> 5.1.2'
gem 'pg', '~> 0.18'

group :development, :test do
  gem 'rspec-rails', '~> 3.6', '>= 3.6.1'
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
  gem 'capybara', '2.7.1'
  gem 'capybara-webkit'
  gem 'database_cleaner', '~> 1.6', '>= 1.6.2'
  gem 'capybara-screenshot'
  gem 'factory_girl_rails', '~> 4.8'
end
</code>```

Here is what i see in my rails test console and type in

```<code>DatabaseCleaner.clean

 => [#<DatabaseCleaner::Base:0x00000005e09368 @orm=:active_record, @strategy=#<DatabaseCleaner::ActiveRecord::Transaction:0x00000005e08f58 @db=:default, @connection_class=ActiveRecord::Base>, @db=:default>]
</code>```

I have copied and pasted the database-cleaner recommended configuration from the readme and it does not work. (i'm using rspec with capybara webkit) Here is my full rails_helper.rb file:

```<code>ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)

abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'spec_helper'
require 'rspec/rails'
Capybara.javascript_driver = :webkit
Capybara.server = :puma
require 'capybara/rails'
require 'capybara/rspec'
require 'capybara-screenshot/rspec'
require 'capybara/webkit/matchers'
Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }
Capybara.ignore_hidden_elements = false

ActiveRecord::Migration.maintain_test_schema!

RSpec.configure do |config|

  config.fixture_path = "#{::Rails.root}/spec/fixtures"
RSpec.configure do |config|

  config.use_transactional_fixtures = false

  config.before(:suite) do
    if config.use_transactional_fixtures?
      raise(<<-MSG)
        Delete line `config.use_transactional_fixtures = true` from rails_helper.rb
        (or set it to false) to prevent uncommitted transactions being used in
        JavaScript-dependent specs.

        During testing, the app-under-test that the browser driver connects to
        uses a different database connection to the database connection used by
        the spec. The app's database connection would not be able to access
        uncommitted transaction data setup over the spec's database connection.
      MSG
    end
    DatabaseCleaner.clean_with(:truncation)
  end

  config.before(:each) do
    DatabaseCleaner.strategy = :transaction
  end

  config.before(:each, type: :feature) do
    # :rack_test driver's Rack app under test shares database connection
    # with the specs, so continue to use transaction strategy for speed.
    driver_shares_db_connection_with_specs = Capybara.current_driver == :rack_test

    if !driver_shares_db_connection_with_specs
      # Driver is probably for an external browser with an app
      # under test that does *not* share a database connection with the
      # specs, so use truncation strategy.
      DatabaseCleaner.strategy = :truncation
    end
  end

  config.before(:each) do
    DatabaseCleaner.start
  end

  config.append_after(:each) do
    DatabaseCleaner.clean
  end

  config.infer_spec_type_from_file_location!
  config.filter_rails_from_backtrace!
  config.include FactoryGirl::Syntax::Methods
  config.include(Capybara::Webkit::RspecMatchers, :type => :feature)
  config.include Warden::Test::Helpers
  Warden.test_mode!
  config.after :each do
    Warden.test_reset!
  end
end

Capybara::Webkit.configure do |config|
  config.block_unknown_urls
end

RSpec::Matchers.define :appear_before do |later_content|
  match do |earlier_content|
    page.body.index(earlier_content) < page.body.index(later_content)
  end
end
</code>```

I have also referenced this tutorial and tweaked the rspec config, but this too does not help.

```<code>ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)

abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'database_cleaner'
require 'spec_helper'
require 'rspec/rails'
Capybara.javascript_driver = :webkit
Capybara.server = :puma
require 'capybara/rails'
require 'capybara/rspec'
require 'capybara-screenshot/rspec'
require 'capybara/webkit/matchers'
Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }
Capybara.ignore_hidden_elements = false
Capybara::Screenshot.autosave_on_failure = false

ActiveRecord::Migration.maintain_test_schema!

RSpec.configure do |config|

  config.fixture_path = "#{::Rails.root}/spec/fixtures"
  config.use_transactional_fixtures = false
  config.infer_spec_type_from_file_location!
  config.filter_rails_from_backtrace!
  config.include FactoryGirl::Syntax::Methods
  config.include(Capybara::Webkit::RspecMatchers, :type => :feature)
  config.include Warden::Test::Helpers
  Warden.test_mode!
  config.after :each do
    Warden.test_reset!
  end

  config.before(:suite) do
    DatabaseCleaner.clean_with(:truncation)
  end

  config.before(:each) do
    DatabaseCleaner.strategy = :transaction
  end

  config.before(:each, :js => true) do
    DatabaseCleaner.strategy = :truncation
  end

  config.before(:each) do
    DatabaseCleaner.start
  end

  config.after(:each) do
    DatabaseCleaner.clean
  end
end

Capybara::Webkit.configure do |config|
  config.block_unknown_urls
end
</code>```

答: The behavior of auto increment ids with database cleaner is dependent on the specific database used and the method of cleaning you are using (truncation, deletion, transaction).  That being said, it should be irrelevant to your tests since they shouldn't be depending on specific ids at all.</p>

Body:
I need some guidance on how to get database cleaner to work for my rails app. ID of records keep on increasing for each test and is not being wiped out.

I've set up a test to check if database cleaner works and it fails.

spec/models/concerns/database_cleaner_test.rb

require 'rails_helper'

describe "db_cleaner" do

    let!(:article) { FactoryGirl.create(:article) }

    it "first test" do
      expect(Article.all.count).to eq(1)
      expect(Article.last.id).to eq(1)
    end

    it "should clean db" do
      expect(Article.all.count).to eq(1)
      expect(Article.last.id).to eq(1)
    end

end

Failures:

  1) db_cleaner should clean db
     Failure/Error: expect(Article.last.id).to eq(1)

       expected: 1
            got: 2

       (compared using ==)

Setup:

gem 'rails', '~> 5.1.2'
gem 'pg', '~> 0.18'

group :development, :test do
  gem 'rspec-rails', '~> 3.6', '>= 3.6.1'
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
  gem 'capybara', '2.7.1'
  gem 'capybara-webkit'
  gem 'database_cleaner', '~> 1.6', '>= 1.6.2'
  gem 'capybara-screenshot'
  gem 'factory_girl_rails', '~> 4.8'
end

Here is what i see in my rails test console and type in

DatabaseCleaner.clean

 => [#<DatabaseCleaner::Base:0x00000005e09368 @orm=:active_record, @strategy=#<DatabaseCleaner::ActiveRecord::Transaction:0x00000005e08f58 @db=:default, @connection_class=ActiveRecord::Base>, @db=:default>]

I have copied and pasted the database-cleaner recommended configuration from the readme and it does not work. (i'm using rspec with capybara webkit) Here is my full rails_helper.rb file:

ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)

abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'spec_helper'
require 'rspec/rails'
Capybara.javascript_driver = :webkit
Capybara.server = :puma
require 'capybara/rails'
require 'capybara/rspec'
require 'capybara-screenshot/rspec'
require 'capybara/webkit/matchers'
Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }
Capybara.ignore_hidden_elements = false

ActiveRecord::Migration.maintain_test_schema!

RSpec.configure do |config|

  config.fixture_path = "#{::Rails.root}/spec/fixtures"
RSpec.configure do |config|

  config.use_transactional_fixtures = false

  config.before(:suite) do
    if config.use_transactional_fixtures?
      raise(<<-MSG)
        Delete line `config.use_transactional_fixtures = true` from rails_helper.rb
        (or set it to false) to prevent uncommitted transactions being used in
        JavaScript-dependent specs.

        During testing, the app-under-test that the browser driver connects to
        uses a different database connection to the database connection used by
        the spec. The app's database connection would not be able to access
        uncommitted transaction data setup over the spec's database connection.
      MSG
    end
    DatabaseCleaner.clean_with(:truncation)
  end

  config.before(:each) do
    DatabaseCleaner.strategy = :transaction
  end

  config.before(:each, type: :feature) do
    # :rack_test driver's Rack app under test shares database connection
    # with the specs, so continue to use transaction strategy for speed.
    driver_shares_db_connection_with_specs = Capybara.current_driver == :rack_test

    if !driver_shares_db_connection_with_specs
      # Driver is probably for an external browser with an app
      # under test that does *not* share a database connection with the
      # specs, so use truncation strategy.
      DatabaseCleaner.strategy = :truncation
    end
  end

  config.before(:each) do
    DatabaseCleaner.start
  end

  config.append_after(:each) do
    DatabaseCleaner.clean
  end

  config.infer_spec_type_from_file_location!
  config.filter_rails_from_backtrace!
  config.include FactoryGirl::Syntax::Methods
  config.include(Capybara::Webkit::RspecMatchers, :type => :feature)
  config.include Warden::Test::Helpers
  Warden.test_mode!
  config.after :each do
    Warden.test_reset!
  end
end

Capybara::Webkit.configure do |config|
  config.block_unknown_urls
end

RSpec::Matchers.define :appear_before do |later_content|
  match do |earlier_content|
    page.body.index(earlier_content) < page.body.index(later_content)
  end
end

I have also referenced this tutorial and tweaked the rspec config, but this too does not help.

ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)

abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'database_cleaner'
require 'spec_helper'
require 'rspec/rails'
Capybara.javascript_driver = :webkit
Capybara.server = :puma
require 'capybara/rails'
require 'capybara/rspec'
require 'capybara-screenshot/rspec'
require 'capybara/webkit/matchers'
Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }
Capybara.ignore_hidden_elements = false
Capybara::Screenshot.autosave_on_failure = false

ActiveRecord::Migration.maintain_test_schema!

RSpec.configure do |config|

  config.fixture_path = "#{::Rails.root}/spec/fixtures"
  config.use_transactional_fixtures = false
  config.infer_spec_type_from_file_location!
  config.filter_rails_from_backtrace!
  config.include FactoryGirl::Syntax::Methods
  config.include(Capybara::Webkit::RspecMatchers, :type => :feature)
  config.include Warden::Test::Helpers
  Warden.test_mode!
  config.after :each do
    Warden.test_reset!
  end

  config.before(:suite) do
    DatabaseCleaner.clean_with(:truncation)
  end

  config.before(:each) do
    DatabaseCleaner.strategy = :transaction
  end

  config.before(:each, :js => true) do
    DatabaseCleaner.strategy = :truncation
  end

  config.before(:each) do
    DatabaseCleaner.start
  end

  config.after(:each) do
    DatabaseCleaner.clean
  end
end

Capybara::Webkit.configure do |config|
  config.block_unknown_urls
end


问:
Using linked Resources in Custom REST Controller with Spring REST JPA
I am developing a set of rest resources over a database and exposing the core CRUD functionality using Spring Data Rest to directly interact with the Repositories.

In my simplified sample I have Users:

```<code>@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public long id;

    public String name;

    @OneToMany(mappedBy = "user")
    public Collection<Project> projects;
}
</code>```

and users Own Projects:

```<code>@Entity
public class Project {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public long id;

    public String name;

    public String oneOfManyComplexDerivedProperties;

    @ManyToOne
    public User user;
}
</code>```

Directly interacting with the repositories is fine, so for creating Users (other other simple entities), the problem comes with creating Projects.  Projects have a large number of server derived fields based on the users form input, so I wrote a custom controller to generate them and persist the result.
In order to persist the result, I need to associate the Project with it's owning User.  I want my client to be able to use the user Link for this, just as when creating a new entity by going direct to the repository (going direct to the repository just works):

```<code>@RepositoryRestController
public class CustomProjectController {

    @Autowired
    ProjectRepo projectRepo;

    @RequestMapping(value = "/createProject", method = RequestMethod.POST)
    public HttpEntity<Project> createProject(@RequestParam User userResource,
                                         @RequestParam String formField1, // actually an uploaded file that gets processed, but i want simple for example purposes
                                         @RequestParam String formfield2)
{
    Project project = new Project();

    /*
    Actually a large amount of complex business logic to derive properties from users form fields, some of these results are binary.
     */
    String result = "result";
    project.oneOfManyComplexDerivedProperties = result;
    project.user = userResource;
    projectRepo.save(project);

    // aware that this is more complex than I've written.
    return ResponseEntity.ok(project);
}
}
</code>```

When I call:

http://localhost:9999/api/createProject?userResource=http://localhost:9999/api/users/1&formField1=data1&formField2=Otherdata

I get:

```<code>{
    "timestamp": 1510588643801,
    "status": 400,
    "error": "Bad Request",
    "exception": "org.springframework.web.method.annotation.MethodArgumentTypeMismatchException",
    "message": "Failed to convert value of type 'java.lang.String' to required type 'com.badger.User'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.lang.Long] for value 'http://localhost:9999/api/users/1'; nested exception is java.lang.NumberFormatException: For input string: \"http://localhost:9999/api/users/1\"",
    "path": "/api/createProject"
}
</code>```

If I change userResource to type Resource then I get a different error:

"Failed to convert value of type 'java.lang.String' to required type 'org.springframework.hateoas.Resource'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'org.springframework.hateoas.Resource': no matching editors or conversion strategy found"

I can't find any reference to using repository URI's in custom controllers in the docs, the closest I found was Resolving entity URI in custom controller (Spring HATEOAS) but the API's have changed since that was written and I have not been able to get it to work.

答:
What User userResource requires is a User object what you passed in was a String http://localhost:9999/api/users/1

So I would recommend you changing your request to a POST request and passing your User Object as the body of that request.

The body of the request will look like in JSON format:

```<code>{
    id: 1,
    name: "myName",
    projects: []
}
</code>```

so you then remove userResource=http://localhost:9999/api/users/1 from your URL.
Finally change @RequestParam User userResource to @RequestBody User userResource

EDIT
since you have the user Id in your request you can make a call within the controller to find the user by the Id. So you can change the user object from @RequestParam User userResource to @RequestParam long userId then make a call to find the user something like findUserById(userId) inside your method

so you url will look like http://localhost:9999/api/createProject?userId=1&formField1=data1&formField2=Otherdata

Body:
I am developing a set of rest resources over a database and exposing the core CRUD functionality using Spring Data Rest to directly interact with the Repositories.

In my simplified sample I have Users:

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public long id;

    public String name;

    @OneToMany(mappedBy = "user")
    public Collection<Project> projects;
}

and users Own Projects:

@Entity
public class Project {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public long id;

    public String name;

    public String oneOfManyComplexDerivedProperties;

    @ManyToOne
    public User user;
}

Directly interacting with the repositories is fine, so for creating Users (other other simple entities), the problem comes with creating Projects.  Projects have a large number of server derived fields based on the users form input, so I wrote a custom controller to generate them and persist the result.
In order to persist the result, I need to associate the Project with it's owning User.  I want my client to be able to use the user Link for this, just as when creating a new entity by going direct to the repository (going direct to the repository just works):

@RepositoryRestController
public class CustomProjectController {

    @Autowired
    ProjectRepo projectRepo;

    @RequestMapping(value = "/createProject", method = RequestMethod.POST)
    public HttpEntity<Project> createProject(@RequestParam User userResource,
                                         @RequestParam String formField1, // actually an uploaded file that gets processed, but i want simple for example purposes
                                         @RequestParam String formfield2)
{
    Project project = new Project();

    /*
    Actually a large amount of complex business logic to derive properties from users form fields, some of these results are binary.
     */
    String result = "result";
    project.oneOfManyComplexDerivedProperties = result;
    project.user = userResource;
    projectRepo.save(project);

    // aware that this is more complex than I've written.
    return ResponseEntity.ok(project);
}
}

When I call:

http://localhost:9999/api/createProject?userResource=http://localhost:9999/api/users/1&formField1=data1&formField2=Otherdata

I get:

{
    "timestamp": 1510588643801,
    "status": 400,
    "error": "Bad Request",
    "exception": "org.springframework.web.method.annotation.MethodArgumentTypeMismatchException",
    "message": "Failed to convert value of type 'java.lang.String' to required type 'com.badger.User'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.lang.Long] for value 'http://localhost:9999/api/users/1'; nested exception is java.lang.NumberFormatException: For input string: \"http://localhost:9999/api/users/1\"",
    "path": "/api/createProject"
}

If I change userResource to type Resource then I get a different error:

"Failed to convert value of type 'java.lang.String' to required type 'org.springframework.hateoas.Resource'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'org.springframework.hateoas.Resource': no matching editors or conversion strategy found"

I can't find any reference to using repository URI's in custom controllers in the docs, the closest I found was Resolving entity URI in custom controller (Spring HATEOAS) but the API's have changed since that was written and I have not been able to get it to work.

Body:
What User userResource requires is a User object what you passed in was a String http://localhost:9999/api/users/1

So I would recommend you changing your request to a POST request and passing your User Object as the body of that request.

The body of the request will look like in JSON format:

{
    id: 1,
    name: "myName",
    projects: []
}

so you then remove userResource=http://localhost:9999/api/users/1 from your URL.
Finally change @RequestParam User userResource to @RequestBody User userResource

EDIT
since you have the user Id in your request you can make a call within the controller to find the user by the Id. So you can change the user object from @RequestParam User userResource to @RequestParam long userId then make a call to find the user something like findUserById(userId) inside your method

so you url will look like http://localhost:9999/api/createProject?userId=1&formField1=data1&formField2=Otherdata


问:
Reading the first line of a file in Ruby
I want to read only the first line of a file using Ruby in the fastest, simplest, most idiomatic way possible. What's the best approach?

(Specifically: I want to read the git commit UUID out of the REVISION file in my latest Capistrano-deployed Rails directory, and then output that to my  tag. This will let me see at an http-glance what version is deployed to my server. If there's an entirely different & better way to do this, please let me know.)

答:
Here's a concise idiomatic way to do it that properly opens the file for reading and closes it afterwards.

```<code>File.open('path.txt', &:gets)
</code>```

If you want an empty file to cause an exception use this instead.

```<code>File.open('path.txt', &:readline)
</code>```

Also, here's a quick & dirty implementation of head that would work for your purposes and in many other instances where you want to read a few more lines.

```<code># Reads a set number of lines from the top.
# Usage: File.head('path.txt')
class File
  def self.head(path, n = 1)
     open(path) do |f|
        lines = []
        n.times do
          line = f.gets || break
          lines << line
        end
        lines
     end
  end
end
</code>```

Body:
Here's a concise idiomatic way to do it that properly opens the file for reading and closes it afterwards.

File.open('path.txt', &:gets)

If you want an empty file to cause an exception use this instead.

File.open('path.txt', &:readline)

Also, here's a quick & dirty implementation of head that would work for your purposes and in many other instances where you want to read a few more lines.

# Reads a set number of lines from the top.
# Usage: File.head('path.txt')
class File
  def self.head(path, n = 1)
     open(path) do |f|
        lines = []
        n.times do
          line = f.gets || break
          lines << line
        end
        lines
     end
  end
end


问:
Graph Algorithm in Python
I have this example graph

```<code>graph = { "v1" : ["v3"],
          "v2" : ["v3", "v5"],
          "v3" : ["v1", "v2", "v4", "v5"],
          "v4" : ["v3"],
          "v5" : ["v3", "v2"],
          "v6" : []
        }
</code>```

And I have this two algorithm for generating edges and finding isolated nodes:

```<code>def edges(g):
    edges = []
    for node in g[node]:
        edges.append((node, g[node]))
    return edges

def isolated(g):
    result = []
    for node in g[node]:
        if not g[node]:
            result += node
    return result
</code>```

What am I doing wrong?

答:
If the graph can contain directed edges, then just checking the adjacency lists for any given nodes is not enough. Instead, you could get sets for all the nodes that are a source or a target for some edge and collect those that are neither.

```<code>>>> targets = {n for lst in graph.values() for n in lst}
>>> sources = {n for n in graph if graph[n] != []}
>>> isolated = {n for n in graph if n not in sources and n not in targets}
>>> isolated
{'v6'}
</code>```

Or using set methods:

```<code>>>> isolated = set(graph).difference(sources).difference(targets)
</code>```

Title: Graph Algorithm in Python

Body:
I have this example graph

graph = { "v1" : ["v3"],
          "v2" : ["v3", "v5"],
          "v3" : ["v1", "v2", "v4", "v5"],
          "v4" : ["v3"],
          "v5" : ["v3", "v2"],
          "v6" : []
        }

And I have this two algorithm for generating edges and finding isolated nodes:

def edges(g):
    edges = []
    for node in g[node]:
        edges.append((node, g[node]))
    return edges

def isolated(g):
    result = []
    for node in g[node]:
        if not g[node]:
            result += node
    return result

What am I doing wrong?

Body:
If the graph can contain directed edges, then just checking the adjacency lists for any given nodes is not enough. Instead, you could get sets for all the nodes that are a source or a target for some edge and collect those that are neither.

>>> targets = {n for lst in graph.values() for n in lst}
>>> sources = {n for n in graph if graph[n] != []}
>>> isolated = {n for n in graph if n not in sources and n not in targets}
>>> isolated
{'v6'}

Or using set methods:

>>> isolated = set(graph).difference(sources).difference(targets)


问:
java.lang.ClassNotFoundException: scala.Int when using akka 2.5.6 with sbt version 1.0.2
I am trying to use akka -remoting version 2.5.4 with latest sbt 1.0.2

When I use sbt version 0.13.15 or 0.13.16 it is working very well.

But when I'm using sbt verion 1.0.2 as here, I'm getting below error.

The Below exception is runtime exception.

```<code>[error] (run-main-0) java.lang.ClassNotFoundException: scala.Int
[error] java.lang.ClassNotFoundException: scala.Int
[error]     at sbt.internal.inc.classpath.ClasspathFilter.loadClass(ClassLoaders.scala:74)
[error]     at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
[error]     at java.lang.Class.forName0(Native Method)
[error]     at java.lang.Class.forName(Class.java:348)
[error]     at akka.actor.ReflectiveDynamicAccess.$anonfun$getClassFor$1(ReflectiveDynamicAccess.scala:21)
[error]     at scala.util.Try$.apply(Try.scala:209)
[error]     at akka.actor.ReflectiveDynamicAccess.getClassFor(ReflectiveDynamicAccess.scala:20)
[error]     at akka.serialization.Serialization.$anonfun$bindings$3(Serialization.scala:313)
[error]     at scala.collection.TraversableLike$WithFilter.$anonfun$map$2(TraversableLike.scala:739)
[error]     at scala.collection.immutable.HashMap$HashMap1.foreach(HashMap.scala:231)
[error]     at scala.collection.immutable.HashMap$HashTrieMap.foreach(HashMap.scala:462)
[error]     at scala.collection.TraversableLike$WithFilter.map(TraversableLike.scala:738)
[error]     at akka.serialization.Serialization.<init>(Serialization.scala:311)
[error]     at akka.serialization.SerializationExtension$.createExtension(SerializationExtension.scala:15)
[error]     at akka.serialization.SerializationExtension$.createExtension(SerializationExtension.scala:12)
[error]     at akka.actor.ActorSystemImpl.registerExtension(ActorSystem.scala:880)
[error]     at akka.actor.ExtensionId.apply(Extension.scala:77)
[error]     at akka.actor.ExtensionId.apply$(Extension.scala:77)
[error]     at akka.serialization.SerializationExtension$.apply(SerializationExtension.scala:12)
[error]     at akka.remote.RemoteActorRefProvider.init(RemoteActorRefProvider.scala:203)
[error]     at akka.actor.ActorSystemImpl.liftedTree2$1(ActorSystem.scala:796)
[error]     at akka.actor.ActorSystemImpl._start$lzycompute(ActorSystem.scala:793)
[error]     at akka.actor.ActorSystemImpl._start(ActorSystem.scala:793)
[error]     at akka.actor.ActorSystemImpl.start(ActorSystem.scala:809)
[error]     at akka.actor.ActorSystem$.apply(ActorSystem.scala:244)
[error]     at akka.actor.ActorSystem$.apply(ActorSystem.scala:287)
[error]     at akka.actor.ActorSystem$.apply(ActorSystem.scala:262)
[error]     at module09.remoteB.RemoteBStartup$.main(RemoteBStartup.scala:8)
[error]     at module09.remoteB.RemoteBStartup.main(RemoteBStartup.scala)
[error]     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[error]     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
[error]     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
[error]     at java.lang.reflect.Method.invoke(Method.java:498)
[error]     at sbt.Run.invokeMain(Run.scala:89)
[error]     at sbt.Run.run0(Run.scala:83)
[error]     at sbt.Run.execute$1(Run.scala:61)
[error]     at sbt.Run.$anonfun$run$4(Run.scala:73)
[error]     at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:12)
[error]     at sbt.util.InterfaceUtil$$anon$1.get(InterfaceUtil.scala:10)
[error]     at sbt.TrapExit$App.run(TrapExit.scala:252)
[error]     at java.lang.Thread.run(Thread.java:748)
</code>```

The github location is here

To me, this looks like the error is because of ConfigFactory.load as in here is having some issues due to sbt latest version.

答:
This was a bug in sbt, so I filed it as such and it has been fixed in sbt version 1.1.0.

(If this would have turned out out to be hard to resolve, we might have considered to implement a workaround in Akka, but this turned out not to be needed)

Body:
I am trying to use akka -remoting version 2.5.4 with latest sbt 1.0.2

When I use sbt version 0.13.15 or 0.13.16 it is working very well.

But when I'm using sbt verion 1.0.2 as here, I'm getting below error.

The Below exception is runtime exception.

[error] (run-main-0) java.lang.ClassNotFoundException: scala.Int
[error] java.lang.ClassNotFoundException: scala.Int
[error]     at sbt.internal.inc.classpath.ClasspathFilter.loadClass(ClassLoaders.scala:74)
[error]     at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
[error]     at java.lang.Class.forName0(Native Method)
[error]     at java.lang.Class.forName(Class.java:348)
[error]     at akka.actor.ReflectiveDynamicAccess.$anonfun$getClassFor$1(ReflectiveDynamicAccess.scala:21)
[error]     at scala.util.Try$.apply(Try.scala:209)
[error]     at akka.actor.ReflectiveDynamicAccess.getClassFor(ReflectiveDynamicAccess.scala:20)
[error]     at akka.serialization.Serialization.$anonfun$bindings$3(Serialization.scala:313)
[error]     at scala.collection.TraversableLike$WithFilter.$anonfun$map$2(TraversableLike.scala:739)
[error]     at scala.collection.immutable.HashMap$HashMap1.foreach(HashMap.scala:231)
[error]     at scala.collection.immutable.HashMap$HashTrieMap.foreach(HashMap.scala:462)
[error]     at scala.collection.TraversableLike$WithFilter.map(TraversableLike.scala:738)
[error]     at akka.serialization.Serialization.<init>(Serialization.scala:311)
[error]     at akka.serialization.SerializationExtension$.createExtension(SerializationExtension.scala:15)
[error]     at akka.serialization.SerializationExtension$.createExtension(SerializationExtension.scala:12)
[error]     at akka.actor.ActorSystemImpl.registerExtension(ActorSystem.scala:880)
[error]     at akka.actor.ExtensionId.apply(Extension.scala:77)
[error]     at akka.actor.ExtensionId.apply$(Extension.scala:77)
[error]     at akka.serialization.SerializationExtension$.apply(SerializationExtension.scala:12)
[error]     at akka.remote.RemoteActorRefProvider.init(RemoteActorRefProvider.scala:203)
[error]     at akka.actor.ActorSystemImpl.liftedTree2$1(ActorSystem.scala:796)
[error]     at akka.actor.ActorSystemImpl._start$lzycompute(ActorSystem.scala:793)
[error]     at akka.actor.ActorSystemImpl._start(ActorSystem.scala:793)
[error]     at akka.actor.ActorSystemImpl.start(ActorSystem.scala:809)
[error]     at akka.actor.ActorSystem$.apply(ActorSystem.scala:244)
[error]     at akka.actor.ActorSystem$.apply(ActorSystem.scala:287)
[error]     at akka.actor.ActorSystem$.apply(ActorSystem.scala:262)
[error]     at module09.remoteB.RemoteBStartup$.main(RemoteBStartup.scala:8)
[error]     at module09.remoteB.RemoteBStartup.main(RemoteBStartup.scala)
[error]     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[error]     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
[error]     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
[error]     at java.lang.reflect.Method.invoke(Method.java:498)
[error]     at sbt.Run.invokeMain(Run.scala:89)
[error]     at sbt.Run.run0(Run.scala:83)
[error]     at sbt.Run.execute$1(Run.scala:61)
[error]     at sbt.Run.$anonfun$run$4(Run.scala:73)
[error]     at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:12)
[error]     at sbt.util.InterfaceUtil$$anon$1.get(InterfaceUtil.scala:10)
[error]     at sbt.TrapExit$App.run(TrapExit.scala:252)
[error]     at java.lang.Thread.run(Thread.java:748)

The github location is here

To me, this looks like the error is because of ConfigFactory.load as in here is having some issues due to sbt latest version.


问:
SAS put data to Excel via DDE
I want to write some data to Excel via DDE and have the following code:

```<code>option noxwait noxsync;
x call "C:\Program Files (x86)\Microsoft Office\Office15\EXCEL.EXE";

%let delay=5;
data _null_;
    rc=sleep(&delay);
run;

filename random dde 'excel|Tabelle1!r1c1:r100c3';
data _null_;
    set sashelp.class;
    file random;
    put name sex age;
run;
</code>```

Excel opens successfully however the sheet remains empty. The log tells me that 19 records were written to the file RANDOM.

Any suggestions why the data is not written to my Excel sheet? Could it be connected with my language settings (German) in Excel?

答:
Very mad story from my end: When I changed my language settings from German to English it works fine with the shown code.

Update:
It also works with German language settings, however I have to translate all statements, e.g. the range written to:

English Excel

```<code>filename random dde 'excel|Sheet1!r1c1:r100c3';
</code>```

German Excel use z(eile) and s(palte) instead of r(ow) and c(olumn)

```<code>filename random dde 'excel|Tabelle1!z1s1:z100s3';
</code>```

Title: SAS put data to Excel via DDE

Body:
I want to write some data to Excel via DDE and have the following code:

option noxwait noxsync;
x call "C:\Program Files (x86)\Microsoft Office\Office15\EXCEL.EXE";

%let delay=5;
data _null_;
    rc=sleep(&delay);
run;

filename random dde 'excel|Tabelle1!r1c1:r100c3';
data _null_;
    set sashelp.class;
    file random;
    put name sex age;
run;

Excel opens successfully however the sheet remains empty. The log tells me that 19 records were written to the file RANDOM.

Any suggestions why the data is not written to my Excel sheet? Could it be connected with my language settings (German) in Excel?

Body:
Very mad story from my end: When I changed my language settings from German to English it works fine with the shown code.

Update:
It also works with German language settings, however I have to translate all statements, e.g. the range written to:

English Excel

filename random dde 'excel|Sheet1!r1c1:r100c3';

German Excel use z(eile) and s(palte) instead of r(ow) and c(olumn)

filename random dde 'excel|Tabelle1!z1s1:z100s3';


问:
Where should HTML be rendered in Object-Oriented PHP design?
Using Object-Oriented PHP, where should HTML be rendered?

The business processes include several actions to maintain customer records.

Should the rendering of each business process get a separate PHP file? ie. viewCustomerTransactions.php?

Where should code like this reside?

```<code>$custTrans = Customer.getTransactions();

foreach ($custTrans as $ct){
     $amount = $ct[0];
     $date = $ct[1];
     $product = $ct[2];

     echo '<div class="custTrans">';
         echo '<span class="custTransAmount">'.$amount.'</span>';
         echo '<span class="custTransDate">'.$date.'</span>';
         echo '<span class="custTransproduct">'.$product.'</span>';
     echo '</div>';
}
</code>```

Perhaps an MVC framework like codeigniter would be better?

答:
If I were you I would store the html in a variable instead of echoing it out like so:

```<code>$custTrans = Customer.getTransactions();

$html = "";
foreach ($custTrans as $ct){
     $amount  = $ct[0];
     $date    = $ct[1];
     $product = $ct[2];

     $html .= "<div class="custTrans">";
         $html .= "<span class='custTransAmount'>".$amount."</span>";
         $html .= "<span class='custTransDate'>".$date."</span>";
         $html .= "<span class='custTransproduct'>".$product."</span>";
     $html .= "</div>";
}
</code>```

You then have this html data stored in the variable $html and you can echo it out where ever you like.

```<code>echo $html;
</code>```

Does that solve you problem mate?

W.

Body:
Using Object-Oriented PHP, where should HTML be rendered?

The business processes include several actions to maintain customer records.

Should the rendering of each business process get a separate PHP file? ie. viewCustomerTransactions.php?

Where should code like this reside?

$custTrans = Customer.getTransactions();

foreach ($custTrans as $ct){
     $amount = $ct[0];
     $date = $ct[1];
     $product = $ct[2];

     echo '
';
         echo ''.$amount.'';
         echo ''.$date.'';
         echo ''.$product.'';
     echo '
';
}

Perhaps an MVC framework like codeigniter would be better?

Body:
If I were you I would store the html in a variable instead of echoing it out like so:

$custTrans = Customer.getTransactions();

$html = "";
foreach ($custTrans as $ct){
     $amount  = $ct[0];
     $date    = $ct[1];
     $product = $ct[2];

     $html .= "<div class="custTrans">";
         $html .= "<span class='custTransAmount'>".$amount."</span>";
         $html .= "<span class='custTransDate'>".$date."</span>";
         $html .= "<span class='custTransproduct'>".$product."</span>";
     $html .= "</div>";
}

You then have this html data stored in the variable $html and you can echo it out where ever you like.

echo $html;

Does that solve you problem mate?

W.


问:
Spring Cloud Gateway - Return 503 when no Service Instance Available
Trying out Spring Cloud Gateway with Spring Boot microservices registered/discovered via Eureka server. The setup is working fine and clients can call the discovered services via the gateway without problem which is great.

Now, I am trying to test a scenario where a client calls a service (via the gateway) for which currently there are no instances available to service the call (i.e. service is down). When we test this scenario, the default behaviour is that the client gets a 500 Internal Server Error response. What would be the simplest way to change this default behaviour to return a 503 Service Unavilable response instead?

Current Stack:

```<code>Java 8
Spring Boot 2.0.0.M6
Spring Cloud 2.0.0.M3
Spring Cloud Starter Eureka 2.0.0.M2 (in Gateway JVM)
Spring Cloud Starter Netflix Ribbon 2.0.0.M3 (in Gateway JVM)
Spring Cloud Starter Netflix Eureka Server 2.0.0.M3 (in Eureka Server JVM)
</code>```

答:
This might be a little hacky, but why not add a controller advice? Something like this should get you there. </p>

```<code>@ControllerAdvice
public class ServiceNotFoundHandler {
    @ExceptionHandler(NotFoundException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.SERVICE_UNAVAILABLE)
    public String handleUnavailableService(NotFoundException e) {
        return "service unavailable";
    }
}
</code>```

Body:
Trying out Spring Cloud Gateway with Spring Boot microservices registered/discovered via Eureka server. The setup is working fine and clients can call the discovered services via the gateway without problem which is great.

Now, I am trying to test a scenario where a client calls a service (via the gateway) for which currently there are no instances available to service the call (i.e. service is down). When we test this scenario, the default behaviour is that the client gets a 500 Internal Server Error response. What would be the simplest way to change this default behaviour to return a 503 Service Unavilable response instead?

Current Stack:

Java 8
Spring Boot 2.0.0.M6
Spring Cloud 2.0.0.M3
Spring Cloud Starter Eureka 2.0.0.M2 (in Gateway JVM)
Spring Cloud Starter Netflix Ribbon 2.0.0.M3 (in Gateway JVM)
Spring Cloud Starter Netflix Eureka Server 2.0.0.M3 (in Eureka Server JVM)

Body:
This might be a little hacky, but why not add a controller advice? Something like this should get you there.

@ControllerAdvice
public class ServiceNotFoundHandler {
    @ExceptionHandler(NotFoundException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.SERVICE_UNAVAILABLE)
    public String handleUnavailableService(NotFoundException e) {
        return "service unavailable";
    }
}


问:
Postgresql multi Insert with array variable
I'm looking to do a multiple dynamic insert with a variable array/list. The number of inserts will always vary.

I'd like to replace

```<code>insert into my table (col 1, col 2)
select *
from unnest(array[1, 2], array[3, 4]);
</code>```

with

```<code>insert into my table (col 1, col 2)
select *
from unnest(:list-of-inserts);
</code>```

答:
Depends if you want to create a new Table with your data or not ?

This could be a simple :

```<code>SELECT * INTO table FROM unnest(array[1, 2], array[3, 4]);
</code>```

OR

Do the same in a temporary table :

```<code>SELECT * INTO temp mytable FROM unnest(array[1, 2], array[3, 4]);
</code>```

Then

```<code>INSERT INTO table (col 1, col 2) SELECT col1, col2 FROM mytable;
</code>```

Hope this will answer your question.

Body:
I'm looking to do a multiple dynamic insert with a variable array/list. The number of inserts will always vary.

I'd like to replace

insert into my table (col 1, col 2)
select *
from unnest(array[1, 2], array[3, 4]);

with

insert into my table (col 1, col 2)
select *
from unnest(:list-of-inserts);

Body:
Depends if you want to create a new Table with your data or not ?

This could be a simple :

SELECT * INTO table FROM unnest(array[1, 2], array[3, 4]);

OR

Do the same in a temporary table :

SELECT * INTO temp mytable FROM unnest(array[1, 2], array[3, 4]);

Then

INSERT INTO table (col 1, col 2) SELECT col1, col2 FROM mytable;

Hope this will answer your question.


问:
automatic include mechanism in PHP
Is there a way I can include files same folder automatically?

I see lot of code in application I am working on that has this kind of code. Specific example is swift mailer (if anyone is aware of that). But this can also be used as general example:

```<code> Folder: vendor\swiftmailer\swiftmailer\lib\classes\Swift\Transport

 |
 --- File MailInvoker.php
                 |
                 --- interface Swift_Transport_MailInvoker
 |
 --- File SimpleMailInvoker.php
                 |
                 --- class Swift_Transport_SimpleMailInvoker implements Swift_Transport_MailInvoker
</code>```

I am unable to figure out without any specific include statements or without any mention in any of autoload files, how class can use interface.

Thanks in advance for help!

答:
You can load classes automatic. See http://php.net/manual/en/language.oop5.autoload.php for the offical documentation.

Basically you create a function to load classes and register it with spl_autoload_register('autoloader_function_name');
That function will be executed when the class isn't already included.

You can find the swift autoloader in the file swiftmailer/lib/classes/Swift.php as public static function autoload($class)

Here, on stackoverflow, there are a many examples too:  Best Way To Autoload Classes In PHP

Title: automatic include mechanism in PHP

Body:
Is there a way I can include files same folder automatically?

I see lot of code in application I am working on that has this kind of code. Specific example is swift mailer (if anyone is aware of that). But this can also be used as general example:

 Folder: vendor\swiftmailer\swiftmailer\lib\classes\Swift\Transport

 |
 --- File MailInvoker.php
                 |
                 --- interface Swift_Transport_MailInvoker
 |
 --- File SimpleMailInvoker.php
                 |
                 --- class Swift_Transport_SimpleMailInvoker implements Swift_Transport_MailInvoker

I am unable to figure out without any specific include statements or without any mention in any of autoload files, how class can use interface.

Thanks in advance for help!


问:
Visual studio equivalent of java System.out
What do I use in Visual Studio (C#) to perform the equivalent of Java's System.out.println( /*stuff*/ ) ?

Does the output from the command show in the Output window in the IDE?

I have a button on a webpage that calls a service which returns a string. I want to see what's in the string and have tried all the variations below and nothing ever shows up in the output. It also doesn't stop on the breakpoint so I can check if there are any results.

```<code>var service = new OTest.TylerAPI.APIWebServiceSoapClient();
results = service.OdysseyMsgExecution("<Message MessageType='FindCaseByCaseNumber' Source='APIMessage' ReferenceNumber='1' NodeID='1' UserID='1'> <CaseNumber>T4CV0043212010</CaseNumber></Message>", "NMODYSSEYMETRO");
System.Diagnostics.Debug.Write(results);
</code>```

答:
In System.Diagnostics,

```<code>Debug.Write()
Debug.WriteLine()
</code>```

etc. will print to the Output window in VS.

Body:
What do I use in Visual Studio (C#) to perform the equivalent of Java's System.out.println( /*stuff*/ ) ?

Does the output from the command show in the Output window in the IDE?

I have a button on a webpage that calls a service which returns a string. I want to see what's in the string and have tried all the variations below and nothing ever shows up in the output. It also doesn't stop on the breakpoint so I can check if there are any results.

var service = new OTest.TylerAPI.APIWebServiceSoapClient();
results = service.OdysseyMsgExecution("<Message MessageType='FindCaseByCaseNumber' Source='APIMessage' ReferenceNumber='1' NodeID='1' UserID='1'> <CaseNumber>T4CV0043212010</CaseNumber></Message>", "NMODYSSEYMETRO");
System.Diagnostics.Debug.Write(results);

Body:
In System.Diagnostics,

Debug.Write()
Debug.WriteLine()

etc. will print to the Output window in VS.


问:
How to use WriteProcessMemory in Delphi
I cannot compile this code. Could I have a help? Thanks.

```<code>procedure ChangeOutsideDateTime(h: HWND; dt: TDateTime);
var
  st: TSystemTime;
  pst: Pointer;
  hDTP: Cardinal;
  hProc: THandle;
  dwWrote: DWORD;
begin
  DateTimeToSystemTime(dt, st);
  pst:= VirtualAllocEx(h, nil, SizeOf(st), MEM_COMMIT, 0);
  if pst <> nil then begin
    if GetWindowThreadProcessId(h, hDTP) > 0 then begin
      hProc:= OpenProcess(PROCESS_VM_OPERATION, false, hDTP);
      if WriteProcessMemory(hProc, pst, @st, SizeOf(st), dwWrote) > 0 then begin
        SendMessage(h, DTM_SETSYSTEMTIME, GDT_VALID, hDTP);
        CloseHandle(hProc);
      end;
    end;
    VirtualFreeEx(h, pst, 0, MEM_RELEASE);
  end;
end;
</code>```

It shows "Types of actual and formal var parameters must be identical" at line where is using "WriteProcessMemory".

答:
Your code has several mitakes in it.

you are passing an HWND to VirtualAllocEx(), but it expects a THandle to an opened process instead.  And you are calling VirtualAllocEx() before you have opened the process handle.  And you are not requesting write acess to the allocated memory.

when calling OpenProcess(), you are not asking for PROCESS_VM_WRITE permission, which WriteProcessMemory() requires.

your use of WriteProcessMemory() does not match its declaration. That is why you are getting a compiler error.

you are passing the HWND's process ID as the LPARAM of DTM_SETSYSTEMTIME, but it expects the allocated TSystemTime pointer instead.

Try something more like this:

```<code>procedure ChangeOutsideDateTime(h: HWND; dt: TDateTime);
var
  st: TSystemTime;
  PID: DWORD;
  hProc: THandle;
  pst: Pointer;
  NumWrote: SIZE_T;
begin
  GetWindowThreadProcessId(h, PID);
  hProc := OpenProcess(PROCESS_VM_OPERATION or PROCESS_VM_WRITE, false, PID);
  if hProc <> 0 then
  try
    pst := VirtualAllocEx(hProc, nil, SizeOf(st), MEM_COMMIT, PAGE_READWRITE);
    if pst <> nil then
    try
      DateTimeToSystemTime(dt, st);
      if WriteProcessMemory(hProc, pst, @st, SizeOf(st), NumWrote) then begin
        SendMessage(h, DTM_SETSYSTEMTIME, GDT_VALID, LPARAM(pst));
      end;
    finally
      VirtualFreeEx(hProc, pst, 0, MEM_RELEASE);
    end;
  finally
    CloseHandle(hProc);
  end;
end;
</code>```

Title: How to use WriteProcessMemory in Delphi

Body:
I cannot compile this code. Could I have a help? Thanks.

procedure ChangeOutsideDateTime(h: HWND; dt: TDateTime);
var
  st: TSystemTime;
  pst: Pointer;
  hDTP: Cardinal;
  hProc: THandle;
  dwWrote: DWORD;
begin
  DateTimeToSystemTime(dt, st);
  pst:= VirtualAllocEx(h, nil, SizeOf(st), MEM_COMMIT, 0);
  if pst <> nil then begin
    if GetWindowThreadProcessId(h, hDTP) > 0 then begin
      hProc:= OpenProcess(PROCESS_VM_OPERATION, false, hDTP);
      if WriteProcessMemory(hProc, pst, @st, SizeOf(st), dwWrote) > 0 then begin
        SendMessage(h, DTM_SETSYSTEMTIME, GDT_VALID, hDTP);
        CloseHandle(hProc);
      end;
    end;
    VirtualFreeEx(h, pst, 0, MEM_RELEASE);
  end;
end;

It shows "Types of actual and formal var parameters must be identical" at line where is using "WriteProcessMemory".

Body:
Your code has several mitakes in it.

you are passing an HWND to VirtualAllocEx(), but it expects a THandle to an opened process instead.  And you are calling VirtualAllocEx() before you have opened the process handle.  And you are not requesting write acess to the allocated memory.

when calling OpenProcess(), you are not asking for PROCESS_VM_WRITE permission, which WriteProcessMemory() requires.

your use of WriteProcessMemory() does not match its declaration. That is why you are getting a compiler error.

you are passing the HWND's process ID as the LPARAM of DTM_SETSYSTEMTIME, but it expects the allocated TSystemTime pointer instead.

Try something more like this:

procedure ChangeOutsideDateTime(h: HWND; dt: TDateTime);
var
  st: TSystemTime;
  PID: DWORD;
  hProc: THandle;
  pst: Pointer;
  NumWrote: SIZE_T;
begin
  GetWindowThreadProcessId(h, PID);
  hProc := OpenProcess(PROCESS_VM_OPERATION or PROCESS_VM_WRITE, false, PID);
  if hProc <> 0 then
  try
    pst := VirtualAllocEx(hProc, nil, SizeOf(st), MEM_COMMIT, PAGE_READWRITE);
    if pst <> nil then
    try
      DateTimeToSystemTime(dt, st);
      if WriteProcessMemory(hProc, pst, @st, SizeOf(st), NumWrote) then begin
        SendMessage(h, DTM_SETSYSTEMTIME, GDT_VALID, LPARAM(pst));
      end;
    finally
      VirtualFreeEx(hProc, pst, 0, MEM_RELEASE);
    end;
  finally
    CloseHandle(hProc);
  end;
end;


问:
Undefined variable errors - strange situation
I have a problem with existing project.
I get the message:

ErrorException (E_ERROR) Undefined variable: errors

and in my code where error occur is:

```<code>@if (count($errors) > 0)
</code>```

I was try to install new project with same plugins and features and on new project I don't have that problem and error exception.
Also I can't change that file, because it's plugins file.

Environment on both projects are:

LEMP,

PHP: 7.1.1

Laravel: 5.5

What can be that error?

答:
My team was solved this error by uncomment ShareErrorsFromSession in app/Http/Kernel.php file</p>

```<code>\Illuminate\View\Middleware\ShareErrorsFromSession::class,
</code>```

Body:
I have a problem with existing project.
I get the message:

ErrorException (E_ERROR) Undefined variable: errors

and in my code where error occur is:

@if (count($errors) > 0)

I was try to install new project with same plugins and features and on new project I don't have that problem and error exception.
Also I can't change that file, because it's plugins file.

Environment on both projects are:

LEMP,

PHP: 7.1.1

Laravel: 5.5

What can be that error?

Body:
My team was solved this error by uncomment ShareErrorsFromSession in app/Http/Kernel.php file

\Illuminate\View\Middleware\ShareErrorsFromSession::class,


答: Use Either Debug.WriteLine() or Trace.WriteLine(). If in release mode, only the latter will appear in the output window, in debug mode, both will.

Title: Visual studio equivalent of java System.out


问:
indexing an m-dimensional array in Matlab (with m not constant)
I have an indexing problem in Matlab. Let's say that I have a m-dimensional array A with m depending on the problem.

Suppose I have vector with indices

```<code>x = [i2, ..., im]
</code>```

and I want to take the vector

```<code>A(:, i_2, ..., i_m)
</code>```

. If m is constant in all cases, it is not that difficult. You can just say

```<code>i_j = x(j), j = 2, ..., m
</code>```

. Is it possible to do this without an if-loop
 (so without saying 'if m == 2 then .. if m == 3 then ...' and so on )?

Thanks for the help

答:
This can be easily done converting x into cell array and generating a comma-separated list from that:

```<code>A = rand(3,3,3,3,3); % example A
x = [2 1 3 2]; % example x
ind = num2cell(x);
result = A(:, ind{:});
</code>```

Body:
I have an indexing problem in Matlab. Let's say that I have a m-dimensional array A with m depending on the problem.

Suppose I have vector with indices

x = [i2, ..., im]

and I want to take the vector

A(:, i_2, ..., i_m)

. If m is constant in all cases, it is not that difficult. You can just say

i_j = x(j), j = 2, ..., m

. Is it possible to do this without an if-loop
 (so without saying 'if m == 2 then .. if m == 3 then ...' and so on )?

Thanks for the help

Body:
This can be easily done converting x into cell array and generating a comma-separated list from that:

A = rand(3,3,3,3,3); % example A
x = [2 1 3 2]; % example x
ind = num2cell(x);
result = A(:, ind{:});


问:
nodejs express serving folder and files stored in DigitalOcean/S3
I would like to ask help on serving files stored via object storage in DigitalOcean/S3` using nodejs.

My current app checks the ./public/ folder inside the nodejs app folder as follows:

in app.js

```<code>app.use(express.static(path.join(__dirname, 'public')));
</code>```

and in routes/index.js

```<code>var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
res.render('home', { title: 'homepage' });
});
module.exports = router;
</code>```

How can I let the app serve files located in the ./public/ directory in a bucket.

```<code>DIR   s3://my***/public/
</code>```

Your help is greatly appreciated.

答:
I think you're confusing the purpose of S3, it's not like a database when you'll proxy calls to the data (s3) and hand it back to the client. Generally you'll expose the S3 bucket in a way that lets anyone view individual items from it but not index or update it.

From there you can just lookup the full file URL and pass it back to the user / browser / app. For example, I usually store the S3 location within my database, I'll then pull this out and append it on the end of the S3 bucket URL and then hand that back to the frontend to render my images directly from S3.

If you want to attach your own domain name to S3, you can checkout AWS Cloudfront and use the CDN feature. This allows you to attach your own domain name to the bucket and serve things up super quickly from anywhere across the globe.

Body:
I would like to ask help on serving files stored via object storage in DigitalOcean/S3` using nodejs.

My current app checks the ./public/ folder inside the nodejs app folder as follows:

in app.js

app.use(express.static(path.join(__dirname, 'public')));

and in routes/index.js

var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
res.render('home', { title: 'homepage' });
});
module.exports = router;

How can I let the app serve files located in the ./public/ directory in a bucket.

DIR   s3://my***/public/

Your help is greatly appreciated.


问:
CSS class for pointer cursor
Is there any CSS class or attribute for pointer:cursor in Bootstrap 4 specially for button or link?

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>
<button type="button" class="btn btn-success">Sample Button</button>```

答:
UPDATE for Bootstrap 4 stable

The cursor: pointer; rule has been restored, so buttons will now by default have the cursor on hover:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<button type="button" class="btn btn-success">Sample Button</button>```
</div>
</div>
</p>

<hr>

<p>No, there isn't. You need to make some custom CSS for this.</p>

<p>If you just need a link that looks like a button (with pointer), use this:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">
Sample Button</code>```

ContentLicense: CC BY-SA 4.0

Title: CSS class for pointer cursor

Body:
UPDATE for Bootstrap 4 stable

The cursor: pointer; rule has been restored, so buttons will now by default have the cursor on hover:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<button type="button" class="btn btn-success">Sample Button</button>

No, there isn't. You need to make some custom CSS for this.

If you just need a link that looks like a button (with pointer), use this:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">
<a class="btn btn-success" href="#" role="button">Sample Button</a>


问:
Extract an array of objects from json string and put them in ArrayList?
I’ve a simple question, and was wondering if someone here could help me how to parse through a Json string and extract all the User and put it into a List?

Note the object key directly under Users is a random number which can change with every response!

```<code>{
    "_links": {},
    "count": {},
    "users": {
        "123321": { //*Is a random number which can be any number
            "_links": {},
            "user": {
                "id": "123321",
                "name": "...",
                "age": "...",
                "address": ""
                ..
            }
        },
        "456654": {
            "_links": {},
            "user": {
                "id": "456654",
                "name": "...",
                "age": "...",
                "address": ""
                ...
            }
        }
        ...
    },
    "page": {}
}
</code>```

Ideally, it would be nice to utilize Jackson Json or Gson.

Also I would like to only construct User object with two fields (id & name) and ignore the rest of the fields!

答:
A Jackson-approach could look like this:

```<code>ObjectMapper om = new ObjectMapper();
JsonNode node = om.readTree(input);

List<JsonNode> users = node.findValues("user");
</code>```

From here you can either retrieve the values directly from the JsonNode instances, e.g.:

```<code>for (JsonNode jsonNode : users) {
    System.out.println(jsonNode.get("name"));
    System.out.println(jsonNode.get("id"));
}
</code>```

or convert to a POJO:

```<code>for (JsonNode user : users) {
    User pojo = om.treeToValue(user, User.class);
    System.out.println(pojo.id);
    System.out.println(pojo.name);
}
</code>```

Assuming the existence of a POJO that looks something like the following:

```<code>@JsonIgnoreProperties(ignoreUnknown = true)
public class User {
    public String name, id;
}
</code>```

Body:
I’ve a simple question, and was wondering if someone here could help me how to parse through a Json string and extract all the User and put it into a List?

Note the object key directly under Users is a random number which can change with every response!

{
    "_links": {},
    "count": {},
    "users": {
        "123321": { //*Is a random number which can be any number
            "_links": {},
            "user": {
                "id": "123321",
                "name": "...",
                "age": "...",
                "address": ""
                ..
            }
        },
        "456654": {
            "_links": {},
            "user": {
                "id": "456654",
                "name": "...",
                "age": "...",
                "address": ""
                ...
            }
        }
        ...
    },
    "page": {}
}

Ideally, it would be nice to utilize Jackson Json or Gson.

Also I would like to only construct User object with two fields (id & name) and ignore the rest of the fields!

Body:
A Jackson-approach could look like this:

ObjectMapper om = new ObjectMapper();
JsonNode node = om.readTree(input);

List<JsonNode> users = node.findValues("user");

From here you can either retrieve the values directly from the JsonNode instances, e.g.:

for (JsonNode jsonNode : users) {
    System.out.println(jsonNode.get("name"));
    System.out.println(jsonNode.get("id"));
}

or convert to a POJO:

for (JsonNode user : users) {
    User pojo = om.treeToValue(user, User.class);
    System.out.println(pojo.id);
    System.out.println(pojo.name);
}

Assuming the existence of a POJO that looks something like the following:

@JsonIgnoreProperties(ignoreUnknown = true)
public class User {
    public String name, id;
}


问:
CSV connection to CPLEX with DBConnection
I want to connect CPLEX with a CSV formatted file where my data is supposed to be written and read.

I think I correctly connected CSV files in the folder "provacsv" like this:

```<code>DBConnection db("odbc","DRIVER={Microsoft Access Text Driver (*.txt, *.csv)}; DBQ=C:\\Users\\Giovanni\\opl\\provacsv");
</code>```

However I cannot read data, even as simple as a column of 2 values. I'm using the following syntax:

```<code>c from DBRead(db,"SELECT c FROM cb.csv");
b from DBRead(db,"SELECT b FROM cb.csv");
A from DBRead(db,"SELECT * FROM A.csv");    // A is a matrix of values (like 2X2 matrix)
</code>```

I would also like to write the output of my file with something like:

```<code>x to DBWrite(db,"WRITE x TO x.csv");
</code>```

答:
For read csv

You should use IloOplInputFile:

Suppose you have this export.cvs file

```<code>Nicolas;2;
Alexander;3;
</code>```

Then you could write

```<code>tuple t
{
string firstname;
int number;
}

{t} s={};

execute
{
var f=new IloOplInputFile("export.csv");
while (!f.eof)
{
var str=f.readline();
//writeln(str);
var ar=str.split(";");
if (ar.length==3) s.add(ar[0],Opl.intValue(ar[1]));
}
f.close();
}

execute
{
writeln(s);
}
</code>```

which will read the csv file and compute the tuple set s:

```<code>{<"Nicolas" 2> <"Alexander" 3>}
</code>```

and for write

```<code>tuple t
{
string firstname;
int number;
}

{t} s={<"Nicolas",2>,<"Alexander",3>};

execute
{
var f=new IloOplOutputFile("export.csv");
for(var i in s)
{
f.writeln(i.firstname,";",i.number,";");
}
f.close();
}
</code>```

writes a file export.csv

```<code>Nicolas;2;
Alexander;3;
</code>```

This can be also read at

https://www.ibm.com/developerworks/community/forums/html/topic?id=538340b3-3e1a-4951-bed3-48cac63e7c29&ps=25

and

https://www.ibm.com/developerworks/community/forums/html/threadTopic?id=3fd44d41-210b-4b81-a005-819530d6377b&ps=25

Body:
I want to connect CPLEX with a CSV formatted file where my data is supposed to be written and read.

I think I correctly connected CSV files in the folder "provacsv" like this:

DBConnection db("odbc","DRIVER={Microsoft Access Text Driver (*.txt, *.csv)}; DBQ=C:\\Users\\Giovanni\\opl\\provacsv");

However I cannot read data, even as simple as a column of 2 values. I'm using the following syntax:

c from DBRead(db,"SELECT c FROM cb.csv");
b from DBRead(db,"SELECT b FROM cb.csv");
A from DBRead(db,"SELECT * FROM A.csv");    // A is a matrix of values (like 2X2 matrix)

I would also like to write the output of my file with something like:

x to DBWrite(db,"WRITE x TO x.csv");

Body:
For read csv

You should use IloOplInputFile:

Suppose you have this export.cvs file

Nicolas;2;
Alexander;3;

Then you could write

tuple t
{
string firstname;
int number;
}

{t} s={};

execute
{
var f=new IloOplInputFile("export.csv");
while (!f.eof)
{
var str=f.readline();
//writeln(str);
var ar=str.split(";");
if (ar.length==3) s.add(ar[0],Opl.intValue(ar[1]));
}
f.close();
}

execute
{
writeln(s);
}

which will read the csv file and compute the tuple set s:

{<"Nicolas" 2> <"Alexander" 3>}

and for write

tuple t
{
string firstname;
int number;
}

{t} s={<"Nicolas",2>,<"Alexander",3>};

execute
{
var f=new IloOplOutputFile("export.csv");
for(var i in s)
{
f.writeln(i.firstname,";",i.number,";");
}
f.close();
}

writes a file export.csv

Nicolas;2;
Alexander;3;

This can be also read at

https://www.ibm.com/developerworks/community/forums/html/topic?id=538340b3-3e1a-4951-bed3-48cac63e7c29&ps=25

and

https://www.ibm.com/developerworks/community/forums/html/threadTopic?id=3fd44d41-210b-4b81-a005-819530d6377b&ps=25


问:
How to get the element from a excel which contains multiple HTML Tags?
Now I am having a excel file that full of HTML tags, which are stored as strings like:

```<code>< Productname= " ABC " label= " CDE " show_ always= " 1" length-threshold= " 1" truncate- threshold= " 10" max- value-width= " 10" value- extension= " . . . " delimiter= " | " >
< Productname= " XYZ " label= " XYZ " show_ always= " 1" length-threshold= " 1" truncate- threshold= " 10" max- value-width= " 10" value- extension= " . . . " delimiter= " | " >
< Productname= " JKL " label= " JKL " show_ always= " 1" length-threshold= " 1" truncate- threshold= " 10" max- value-width= " 10" value- extension= " . . . " delimiter= " | " >
</code>```

And I would like to extract the different values in the code, and present them as follows:

```<code>       Productname  label   show_always length-threshold value- extension ...
           ABC       CDE        1             1             . . .
</code>```

1, I though of using the "=" as a separator, but the strings, which is the name of the variable, have different lengths and they are strings instead of variables in the documents. Therefore I do not have idea how can I accruately get the value. Is there any way that I can get the value in fromt and behind the value accruately?

2, Besides of this althorigm, is there any better way to solve the problem, without directly scrawing from the site?

Looking forward to your answer and many thanks!

答:
You should really use xslt. It's a language to perfom magic in several ways:
https://www.google.se/search?q=excel+xslt</p>

Body:
Now I am having a excel file that full of HTML tags, which are stored as strings like:

< Productname= " ABC " label= " CDE " show_ always= " 1" length-threshold= " 1" truncate- threshold= " 10" max- value-width= " 10" value- extension= " . . . " delimiter= " | " >
< Productname= " XYZ " label= " XYZ " show_ always= " 1" length-threshold= " 1" truncate- threshold= " 10" max- value-width= " 10" value- extension= " . . . " delimiter= " | " >
< Productname= " JKL " label= " JKL " show_ always= " 1" length-threshold= " 1" truncate- threshold= " 10" max- value-width= " 10" value- extension= " . . . " delimiter= " | " >

And I would like to extract the different values in the code, and present them as follows:

       Productname  label   show_always length-threshold value- extension ...
           ABC       CDE        1             1             . . .

1, I though of using the "=" as a separator, but the strings, which is the name of the variable, have different lengths and they are strings instead of variables in the documents. Therefore I do not have idea how can I accruately get the value. Is there any way that I can get the value in fromt and behind the value accruately?

2, Besides of this althorigm, is there any better way to solve the problem, without directly scrawing from the site?

Looking forward to your answer and many thanks!