问:
Using RecyclerView with DataBase
```<code>public class Contact {

// id
int mNumber;

String  mMonth,mDate, mDay, mTime , mTitle , mContent;
int mMood,mWeather;

public Contact(){}

public Contact(int number, String month, String date, String day, String time, String title, String content, int weather, int mood) {
    mNumber=number; mMonth=month; mDay = day; mDate = date ; mTime = time; mTitle = title; mContent = content; mWeather = weather; mMood =mood;
}

public Contact(String month, String date, String day, String time, String title, String content, int weather, int mood) {
    mMonth=month; mDay = day; mDate = date ; mTime = time; mTitle = title; mContent = content; mWeather = weather; mMood =mood;
}
public Contact(String month, String date, String day, String time, String title, String content) {
    mMonth=month; mDay = day; mDate = date ; mTime = time; mTitle = title; mContent = content;
}

public int getmNumber() {
    return mNumber;
}

public void setmNumber(int mNumber) {
    this.mNumber = mNumber;
}

public String getmMonth() {
    return mMonth;
}

public void setmMonth(String mMonth) {
    this.mMonth = mMonth;
}

public String getmDate() {
    return mDate;
}

public void setmDate(String mDate) {
    this.mDate = mDate;
}

public String getmDay() {
    return mDay;
}

public void setmDay(String mDay) {
    this.mDay = mDay;
}

public String getmTime() {
    return mTime;
}

public void setmTime(String mTime) {
    this.mTime = mTime;
}

public String getmTitle() {
    return mTitle;
}

public void setmTitle(String mTitle) {
    this.mTitle = mTitle;
}

public String getmContent() {
    return mContent;
}

public void setmContent(String mContent) {
    this.mContent = mContent;
}

public int getmMood() {
    return mMood;
}

public void setmMood(int mMood) {
    this.mMood = mMood;
}

public int getmWeather() {
    return mWeather;
}

public void setmWeather(int mWeather) {
    this.mWeather = mWeather;
}
}
</code>```

Contact class is use to save value

```<code>public class DBHelper extends SQLiteOpenHelper {

public static final String DATABASE_NAME = "Calendar.db";

//Table Name
public static final String D_TABLE_NAME = "Diary";

public static final String D_COL_1 = "m_Number";  //id
public static final String D_COL_2 = "m_Title";
public static final String D_COL_3 = "m_Content";
public static final String D_COL_4 = "m_Month";
public static final String D_COL_5 = "m_Date";
public static final String D_COL_6 = "m_Day";
public static final String D_COL_7 = "m_Time";
public static final String D_COL_8 = "m_Mood";    //image
public static final String D_COL_9 = "m_Weather"; //image

public DBHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {

    db.execSQL("CREATE TABLE "+D_TABLE_NAME+"("+D_COL_1+" INTEGER PRIMARY KEY AUTOINCREMENT, "+D_COL_2+" TEXT, "+D_COL_3+" TEXT, "+D_COL_4+" TEXT, "
                +D_COL_5+" TEXT, "+D_COL_6+" TEXT, "+D_COL_7+ " TEXT, "+D_COL_8+" INTEGER, "+D_COL_9+" INTEGER);");

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("drop table if exists"+TABLE_NAME);
    onCreate(db);
}

//Insert new Data
public void addContact(Contact contact){
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues contentValues = new ContentValues();
    contentValues.put(D_COL_2,contact.getmTitle());
    contentValues.put(D_COL_3,contact.getmContent());
    contentValues.put(D_COL_4,contact.getmMonth());
    contentValues.put(D_COL_5,contact.getmDate());
    contentValues.put(D_COL_6,contact.getmDay());
    contentValues.put(D_COL_7,contact.getmTime());
    contentValues.put(D_COL_8,contact.getmMood());
    contentValues.put(D_COL_9,contact.getmWeather());

    db.insert(D_TABLE_NAME,null,contentValues);
    db.close();

}   //

// mNumber to get Contact
public Contact getContact(int mNumber) {
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.query(D_TABLE_NAME, new String[] { D_COL_1,D_COL_2,D_COL_3,D_COL_4,D_COL_5,
                    D_COL_6,D_COL_7,D_COL_8,D_COL_9 }, D_COL_1 + "=?",
            new String[] { String.valueOf(mNumber) }, null, null, null, null);
    if (cursor != null)
        cursor.moveToFirst();

    Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
            cursor.getString(1), cursor.getString(2),cursor.getString(3),cursor.getString(4),cursor.getString(5),cursor.getString(6),
            Integer.parseInt(cursor.getString(7)),Integer.parseInt(cursor.getString(8)));
    return contact;
}

// All Contact information get
public List<Contact> getAllContacts() {
    List<Contact> contactList = new ArrayList<Contact>();

    // Select All Query
    String selectQuery = "SELECT  * FROM " + D_TABLE_NAME;

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

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            Contact contact = new Contact();
            contact.setmNumber(Integer.parseInt(cursor.getString(0)));
            contact.setmTitle(cursor.getString(1));
            contact.setmContent(cursor.getString(2));
            contact.setmMonth(cursor.getString(3));
            contact.setmDate(cursor.getString(4));
            contact.setmDay(cursor.getString(5));
            contact.setmTime(cursor.getString(6));
            contact.setmMood(Integer.parseInt(cursor.getString(7)));
            contact.setmWeather(Integer.parseInt(cursor.getString(8)));
            // Adding contact to list
            contactList.add(contact);
        } while (cursor.moveToNext());
    }
    // return contact list
    Log.d("agent99", contactList.get(0).getmTitle().toString());

    return contactList;
}

public int updateContact(Contact contact) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(D_COL_2,contact.getmTitle());
    values.put(D_COL_3,contact.getmContent());
    values.put(D_COL_4,contact.getmMonth());
    values.put(D_COL_5,contact.getmDate());
    values.put(D_COL_6,contact.getmDay());
    values.put(D_COL_7,contact.getmTime());
    values.put(D_COL_8,contact.getmMood());
    values.put(D_COL_9,contact.getmWeather());

    // updating row
    return db.update(D_TABLE_NAME, values, D_COL_1 + " = ?",
            new String[] { String.valueOf(contact.getmNumber()) });
}

// Contact information delete
public void deleteContact(Contact contact) {
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(D_TABLE_NAME, D_COL_1 + " = ?",
            new String[] { String.valueOf(contact.getmNumber()) });
    db.close();
}

// Contact information number
public int getContactsCount() {
    String countQuery = "SELECT  * FROM " + D_TABLE_NAME;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    cursor.close();
    // return count
    return cursor.getCount();
}
}
</code>```

Recycler Adapter class DataManager

```<code>import android.content.Context;
import android.content.Intent;
import android.support.v4.widget.CursorAdapter;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.codbking.calendar.Contact;
import com.codbking.calendar.DBHelper;
import com.codbking.calendar.exaple.R;
import java.util.List;

public class DataManager extends RecyclerView.Adapter<DataManager.RecyclerViewHolder> {
DBHelper dbHelper;
CursorAdapter mCursorAdapter;

List<Contact> contacts = dbHelper.getAllContacts();

public static class RecyclerViewHolder extends RecyclerView.ViewHolder {

    TextView mDate, mDay, mMonth, mTime, mTitle, mContent;
    ImageView mMood, mWeather;
    private Context context;

    RecyclerViewHolder(final View itemView) {
        super(itemView);
        context = itemView.getContext();
        mDate = (TextView) itemView.findViewById(R.id.TV_entries_item_date);
        mDay = (TextView) itemView.findViewById(R.id.TV_entries_item_day);
        mMonth = (TextView) itemView.findViewById(R.id.TV_entries_item_header);
        mTime = (TextView) itemView.findViewById(R.id.TV_entries_item_time);
        mTitle = (TextView) itemView.findViewById(R.id.TV_entries_item_title);
        mContent = (TextView) itemView.findViewById(R.id.TV_entries_item_summary);
        mMood = (ImageView) itemView.findViewById(R.id.IV_entries_item_weather);
        mWeather = (ImageView) itemView.findViewById(R.id.IV_entries_item_mood);

        itemView.setClickable(true);

        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent myIntent = new Intent(v.getContext(), MainActivity.class);
                context.startActivity(myIntent);
            }
        });
    }
}

@Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.entries, viewGroup, false);
    return new RecyclerViewHolder(v);
}

@Override
public void onBindViewHolder(RecyclerViewHolder viewHolder, int i) {
    // get the single element from the main array

    for (Contact cn : contacts) {
        viewHolder.mDate.setText(cn.getmDate());
        viewHolder.mDay.setText(cn.getmDay());
        viewHolder.mMonth.setText(cn.getmMonth());
        viewHolder.mTime.setText(cn.getmTime());
        viewHolder.mTitle.setText(cn.getmTitle());
        viewHolder.mContent.setText(cn.getmContent());
        viewHolder.mMood.setImageResource(cn.getmMood());
        viewHolder.mWeather.setImageResource(cn.getmWeather());

    }

}
@Override
public int getItemCount(){
   return contacts.size();
}
}
</code>```

I don't know how to use RecyclerView with DataBase.
Error occur in DataManager Class (confidence)

Maybe Error occur in onBindViewHolder() Method or getItemCount() Method.
Previously I use RecyclerView without DataBase App run well... But when I use DataBase, App is just die so I surely die  onBindViewHolder() Method or getItemCount() Method in this code

答:
Replace your onBindViewHolder code with this one</p>

```<code>       @Override
     public void onBindViewHolder(RecyclerViewHolder viewHolder, int i) {
     // get the single element from the main array
        Contact cn = contact.get(i);
        viewHolder.mDate.setText(cn.getmDate());
        viewHolder.mDay.setText(cn.getmDay());
        viewHolder.mMonth.setText(cn.getmMonth());
        viewHolder.mTime.setText(cn.getmTime());
        viewHolder.mTitle.setText(cn.getmTitle());
        viewHolder.mContent.setText(cn.getmContent());
        viewHolder.mTitle.setText(cn.getmTitle());
        viewHolder.mContent.setText(cn.getmContent());
        viewHolder.mMood.setImageResource(cn.getmMood());
        viewHolder.mWeather.setImageResource(cn.getmWeather());

      }
</code>```

Title: Using RecyclerView with DataBase

Body:
public class Contact {

// id
int mNumber;

String  mMonth,mDate, mDay, mTime , mTitle , mContent;
int mMood,mWeather;

public Contact(){}

public Contact(int number, String month, String date, String day, String time, String title, String content, int weather, int mood) {
    mNumber=number; mMonth=month; mDay = day; mDate = date ; mTime = time; mTitle = title; mContent = content; mWeather = weather; mMood =mood;
}

public Contact(String month, String date, String day, String time, String title, String content, int weather, int mood) {
    mMonth=month; mDay = day; mDate = date ; mTime = time; mTitle = title; mContent = content; mWeather = weather; mMood =mood;
}
public Contact(String month, String date, String day, String time, String title, String content) {
    mMonth=month; mDay = day; mDate = date ; mTime = time; mTitle = title; mContent = content;
}

public int getmNumber() {
    return mNumber;
}

public void setmNumber(int mNumber) {
    this.mNumber = mNumber;
}

public String getmMonth() {
    return mMonth;
}

public void setmMonth(String mMonth) {
    this.mMonth = mMonth;
}

public String getmDate() {
    return mDate;
}

public void setmDate(String mDate) {
    this.mDate = mDate;
}

public String getmDay() {
    return mDay;
}

public void setmDay(String mDay) {
    this.mDay = mDay;
}

public String getmTime() {
    return mTime;
}

public void setmTime(String mTime) {
    this.mTime = mTime;
}

public String getmTitle() {
    return mTitle;
}

public void setmTitle(String mTitle) {
    this.mTitle = mTitle;
}

public String getmContent() {
    return mContent;
}

public void setmContent(String mContent) {
    this.mContent = mContent;
}

public int getmMood() {
    return mMood;
}

public void setmMood(int mMood) {
    this.mMood = mMood;
}

public int getmWeather() {
    return mWeather;
}

public void setmWeather(int mWeather) {
    this.mWeather = mWeather;
}
}

Contact class is use to save value

public class DBHelper extends SQLiteOpenHelper {

public static final String DATABASE_NAME = "Calendar.db";

//Table Name
public static final String D_TABLE_NAME = "Diary";

public static final String D_COL_1 = "m_Number";  //id
public static final String D_COL_2 = "m_Title";
public static final String D_COL_3 = "m_Content";
public static final String D_COL_4 = "m_Month";
public static final String D_COL_5 = "m_Date";
public static final String D_COL_6 = "m_Day";
public static final String D_COL_7 = "m_Time";
public static final String D_COL_8 = "m_Mood";    //image
public static final String D_COL_9 = "m_Weather"; //image

public DBHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {

    db.execSQL("CREATE TABLE "+D_TABLE_NAME+"("+D_COL_1+" INTEGER PRIMARY KEY AUTOINCREMENT, "+D_COL_2+" TEXT, "+D_COL_3+" TEXT, "+D_COL_4+" TEXT, "
                +D_COL_5+" TEXT, "+D_COL_6+" TEXT, "+D_COL_7+ " TEXT, "+D_COL_8+" INTEGER, "+D_COL_9+" INTEGER);");

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("drop table if exists"+TABLE_NAME);
    onCreate(db);
}

//Insert new Data
public void addContact(Contact contact){
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues contentValues = new ContentValues();
    contentValues.put(D_COL_2,contact.getmTitle());
    contentValues.put(D_COL_3,contact.getmContent());
    contentValues.put(D_COL_4,contact.getmMonth());
    contentValues.put(D_COL_5,contact.getmDate());
    contentValues.put(D_COL_6,contact.getmDay());
    contentValues.put(D_COL_7,contact.getmTime());
    contentValues.put(D_COL_8,contact.getmMood());
    contentValues.put(D_COL_9,contact.getmWeather());

    db.insert(D_TABLE_NAME,null,contentValues);
    db.close();

}   //

// mNumber to get Contact
public Contact getContact(int mNumber) {
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.query(D_TABLE_NAME, new String[] { D_COL_1,D_COL_2,D_COL_3,D_COL_4,D_COL_5,
                    D_COL_6,D_COL_7,D_COL_8,D_COL_9 }, D_COL_1 + "=?",
            new String[] { String.valueOf(mNumber) }, null, null, null, null);
    if (cursor != null)
        cursor.moveToFirst();

    Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
            cursor.getString(1), cursor.getString(2),cursor.getString(3),cursor.getString(4),cursor.getString(5),cursor.getString(6),
            Integer.parseInt(cursor.getString(7)),Integer.parseInt(cursor.getString(8)));
    return contact;
}

// All Contact information get
public List<Contact> getAllContacts() {
    List<Contact> contactList = new ArrayList<Contact>();

    // Select All Query
    String selectQuery = "SELECT  * FROM " + D_TABLE_NAME;

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

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            Contact contact = new Contact();
            contact.setmNumber(Integer.parseInt(cursor.getString(0)));
            contact.setmTitle(cursor.getString(1));
            contact.setmContent(cursor.getString(2));
            contact.setmMonth(cursor.getString(3));
            contact.setmDate(cursor.getString(4));
            contact.setmDay(cursor.getString(5));
            contact.setmTime(cursor.getString(6));
            contact.setmMood(Integer.parseInt(cursor.getString(7)));
            contact.setmWeather(Integer.parseInt(cursor.getString(8)));
            // Adding contact to list
            contactList.add(contact);
        } while (cursor.moveToNext());
    }
    // return contact list
    Log.d("agent99", contactList.get(0).getmTitle().toString());

    return contactList;
}

public int updateContact(Contact contact) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(D_COL_2,contact.getmTitle());
    values.put(D_COL_3,contact.getmContent());
    values.put(D_COL_4,contact.getmMonth());
    values.put(D_COL_5,contact.getmDate());
    values.put(D_COL_6,contact.getmDay());
    values.put(D_COL_7,contact.getmTime());
    values.put(D_COL_8,contact.getmMood());
    values.put(D_COL_9,contact.getmWeather());

    // updating row
    return db.update(D_TABLE_NAME, values, D_COL_1 + " = ?",
            new String[] { String.valueOf(contact.getmNumber()) });
}

// Contact information delete
public void deleteContact(Contact contact) {
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(D_TABLE_NAME, D_COL_1 + " = ?",
            new String[] { String.valueOf(contact.getmNumber()) });
    db.close();
}

// Contact information number
public int getContactsCount() {
    String countQuery = "SELECT  * FROM " + D_TABLE_NAME;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    cursor.close();
    // return count
    return cursor.getCount();
}
}

Recycler Adapter class DataManager

import android.content.Context;
import android.content.Intent;
import android.support.v4.widget.CursorAdapter;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.codbking.calendar.Contact;
import com.codbking.calendar.DBHelper;
import com.codbking.calendar.exaple.R;
import java.util.List;

public class DataManager extends RecyclerView.Adapter<DataManager.RecyclerViewHolder> {
DBHelper dbHelper;
CursorAdapter mCursorAdapter;

List<Contact> contacts = dbHelper.getAllContacts();

public static class RecyclerViewHolder extends RecyclerView.ViewHolder {

    TextView mDate, mDay, mMonth, mTime, mTitle, mContent;
    ImageView mMood, mWeather;
    private Context context;

    RecyclerViewHolder(final View itemView) {
        super(itemView);
        context = itemView.getContext();
        mDate = (TextView) itemView.findViewById(R.id.TV_entries_item_date);
        mDay = (TextView) itemView.findViewById(R.id.TV_entries_item_day);
        mMonth = (TextView) itemView.findViewById(R.id.TV_entries_item_header);
        mTime = (TextView) itemView.findViewById(R.id.TV_entries_item_time);
        mTitle = (TextView) itemView.findViewById(R.id.TV_entries_item_title);
        mContent = (TextView) itemView.findViewById(R.id.TV_entries_item_summary);
        mMood = (ImageView) itemView.findViewById(R.id.IV_entries_item_weather);
        mWeather = (ImageView) itemView.findViewById(R.id.IV_entries_item_mood);

        itemView.setClickable(true);

        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent myIntent = new Intent(v.getContext(), MainActivity.class);
                context.startActivity(myIntent);
            }
        });
    }
}

@Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.entries, viewGroup, false);
    return new RecyclerViewHolder(v);
}

@Override
public void onBindViewHolder(RecyclerViewHolder viewHolder, int i) {
    // get the single element from the main array

    for (Contact cn : contacts) {
        viewHolder.mDate.setText(cn.getmDate());
        viewHolder.mDay.setText(cn.getmDay());
        viewHolder.mMonth.setText(cn.getmMonth());
        viewHolder.mTime.setText(cn.getmTime());
        viewHolder.mTitle.setText(cn.getmTitle());
        viewHolder.mContent.setText(cn.getmContent());
        viewHolder.mMood.setImageResource(cn.getmMood());
        viewHolder.mWeather.setImageResource(cn.getmWeather());

    }

}
@Override
public int getItemCount(){
   return contacts.size();
}
}

I don't know how to use RecyclerView with DataBase.
Error occur in DataManager Class (confidence)

Maybe Error occur in onBindViewHolder() Method or getItemCount() Method.
Previously I use RecyclerView without DataBase App run well... But when I use DataBase, App is just die so I surely die  onBindViewHolder() Method or getItemCount() Method in this code

Body:
Replace your onBindViewHolder code with this one

       @Override
     public void onBindViewHolder(RecyclerViewHolder viewHolder, int i) {
     // get the single element from the main array
        Contact cn = contact.get(i);
        viewHolder.mDate.setText(cn.getmDate());
        viewHolder.mDay.setText(cn.getmDay());
        viewHolder.mMonth.setText(cn.getmMonth());
        viewHolder.mTime.setText(cn.getmTime());
        viewHolder.mTitle.setText(cn.getmTitle());
        viewHolder.mContent.setText(cn.getmContent());
        viewHolder.mTitle.setText(cn.getmTitle());
        viewHolder.mContent.setText(cn.getmContent());
        viewHolder.mMood.setImageResource(cn.getmMood());
        viewHolder.mWeather.setImageResource(cn.getmWeather());

      }


来源: stackexchange

问:
Appveyor cannot find test coverage
I have a small project (.netstandard 1.0 + net45) on github which I integrated with Appveyor.
I'm using xunit for unit tests and opencover for test coverage.
I cannot get Appveyor to commit test results, here is the output:

Committing...
  No results, this could be for a number of reasons. The most common reasons are:
      1) missing PDBs for the assemblies that match the filter please review the
      output file and refer to the Usage guide (Usage.rtf) about filters.
      2) the profiler may not be registered correctly, please refer to the Usage
      guide and the -register switch.

Here is my script:

- .\tools\OpenCover.4.6.519\tools\OpenCover.Console.exe \
  -target:"c:\Program Files\dotnet\dotnet.exe" \
  -targetargs:"test -f netcoreapp1.1 -c %CONFIGURATION% Giver.Tests/Giver.Tests.csproj" \
  -mergeoutput \
  -hideskipped:File \
  -output:opencoverCoverage.xml \
  -oldStyle \
  -filter:"+[Giver*]* -[Giver.*Tests*]*" \
  -searchdirs:Giver.Tests/bin/%CONFIGURATION%/netcoreapp1.1 \
  -register:user

DebugType is full for all projects.

I probably tried most of the combinations for OpenCover.Console arguments.

The same script works on my machine (after replacing %CONFIGURATION%).

答:
Yeah, it was totally my mistake.

If you change DebugType to Full using Project Properties page (Visual Studio), beware, it will add a condition like this:

```<code><PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
</code>```

I am using Release configuration for Appveyor build, so this condition will not be met and portable .pdb will be generated (opencover only works with Full .pdb).

After deleting this condition, everything works fine.

ContentLicense: CC BY-SA 3.0

Title: Appveyor cannot find test coverage

Body:
Yeah, it was totally my mistake.

If you change DebugType to Full using Project Properties page (Visual Studio), beware, it will add a condition like this:

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">

I am using Release configuration for Appveyor build, so this condition will not be met and portable .pdb will be generated (opencover only works with Full .pdb).

After deleting this condition, everything works fine.


问:
Registry Permissions Fix for SQL Server 2008 Express Install
I have a distributed windows application (written in C#) that currently uses MSDE. The decision was made to upgrade the client database to SQL Server 2008 Express since we need to be able to support Windows 7 (and still support XP) in the next year.

Currently, I am using a batch file to run the installer (and using a Configuration.ini as well), but recently encountered the following error during the install.

"Could not fix registry key
  HKEY_LOCAL_MACHINE\Software\Microsoft\MSSQLServer\MSSQLServer\SuperSocketNetLib\Lpc.
  System.UnauthorizedAccessException: Attempted to perform an
  unauthorized operation.  at
  Microsoft.SqlServer.Configuration.FixSqlRegistryKey.Program.OpenKey(String
  keyName)  at
  Microsoft.SqlServer.Configuration.FixSqlRegistryKey.Program.FixRegistryKey(String
  keyName) at
  Microsoft.SqlServer.Configuration.FixSqlRegistryKey.Program.FixRegistryKeyAndSubKeys(RegistryKey
  key)"

I understand the issue and how to fix in manually.

I need the application to modify this registry key ahead of time and add permissions for the Administrator group or set the key to inherit permissions from the parent. I am also open to other solutions to this SQL 2008 Express installation problem.

I have been researching how to modify the permissions of registry keys but I have been running into issues trying to get it to work correctly (and to understand all the classes and objects associated with setting permissions).

Can someone provide the proper way to add the Administrator group (of any machine) with full control permissions, or how to set the permissions of the key so that it inherits from the parent?

Side question, will their always be an Administrator group on every Windows XP machine?

Thanks!

答:
You can try using subinacl.exe to set permissions for registry keys:
http://www.microsoft.com/downloads/en/details.aspx?FamilyID=e8ba3e56-d8fe-4a91-93cf-ed6985e3927b&displaylang=en

Administrators group exists on all XP versions.

ContentLicense: CC BY-SA 2.5


问:
What's the blending equation of THREE.NormalBlending?
I can't find it in the document. Could anyone tell me what's the equation?

I thought it is equal to the following THREE.CustomBlending:

```<code>    blending: THREE.CustomBlending,
    blendEquation: THREE.AddEquation,
    blendSrc: THREE.SrcAlphaFactor,
    blendDst: THREE.OneMinusSrcAlphaFactor
</code>```

But I get a different result when I change the material from NormalBlending to the above CustomBlending.

Here is the link about default CustomBlending.

答:
Looking at the source code the various Three.js blending modes are different depending on whether or not the material is marked as using premultiplied alpha or not

So, if the material is considered pre-multiplied then it should be the same as

```<code>blending: THREE.CustomBlending,
blendEquation: THREE.AddEquation,
blendSrc: THREE.OneFactor,
blendDst: THREE.OneMinusSrcAlphaFactor
</code>```

Otherwise it's

```<code>blending: THREE.CustomBlending,
blendEquation: THREE.AddEquation,
blendSrc: THREE.SrcAlphaFactor,
blendSrcAlpha: THREE.OneFactor,
blendDst: THREE.OneMinusSrcAlphaFactor
</code>```

"use strict";

const nonPremultipledBlend = {
  blending: THREE.CustomBlending,
  blendEquation: THREE.AddEquation,
  blendSrc: THREE.SrcAlphaFactor,
  blendSrcAlpha: THREE.OneFactor,
  blendDst: THREE.OneMinusSrcAlphaFactor,
};

const premultipledBlend = {
  blending: THREE.CustomBlending,
  blendEquation: THREE.AddEquation,
  blendSrc: THREE.OneFactor,
  blendDst: THREE.OneMinusSrcAlphaFactor,
};

const renderer = new THREE.WebGLRenderer();
document.body.appendChild(renderer.domElement);
const camera = new THREE.OrthographicCamera(-1.5, 1.5, 1, -1, -1, 1);
camera.position.z = 1;
const scene = new THREE.Scene();
const geometry = new THREE.PlaneGeometry(.5, .5);
[
  { color: 0xFF8080, x: -.6,  y:    0, z: 0.2, },
  { color: 0x008040, x: -.30, y: -.25, z: 0.1, },
  { color: 0x008040, x: -.90, y: -.25, z: 0.1, blend: nonPremultipledBlend, },
  { color: 0xFF8080, x:  .6,  y:    0, z: 0.2, },
  { color: 0x008040, x:  .30, y: -.25, z: 0.1, pre: true, },
  { color: 0x008040, x:  .90, y: -.25, z: 0.1, pre: true, blend: premultipledBlend, },
].forEach(info => {
  const material = new THREE.MeshBasicMaterial({
    color: info.color,
    transparent: true,
    opacity: .5,
  });
  if (info.pre) {
    material.premultipliedAlpha = info.pre;
  }
  if (info.blend) {
    Object.assign(material, info.blend);
  }
  const mesh = new THREE.Mesh(geometry, material);
  scene.add(mesh);
  mesh.position.x = info.x;
  mesh.position.y = info.y;
  mesh.position.z = info.z;
});
renderer.render(scene, camera);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body { margin: 0; }
canvas { width: 100vw; height: 100vh; display block; }</code>```

```

Body:
I can't find it in the document. Could anyone tell me what's the equation?

I thought it is equal to the following THREE.CustomBlending:

    blending: THREE.CustomBlending,
    blendEquation: THREE.AddEquation,
    blendSrc: THREE.SrcAlphaFactor,
    blendDst: THREE.OneMinusSrcAlphaFactor

But I get a different result when I change the material from NormalBlending to the above CustomBlending.

Here is the link about default CustomBlending.

Body:
Looking at the source code the various Three.js blending modes are different depending on whether or not the material is marked as using premultiplied alpha or not

So, if the material is considered pre-multiplied then it should be the same as

blending: THREE.CustomBlending,
blendEquation: THREE.AddEquation,
blendSrc: THREE.OneFactor,
blendDst: THREE.OneMinusSrcAlphaFactor

Otherwise it's

blending: THREE.CustomBlending,
blendEquation: THREE.AddEquation,
blendSrc: THREE.SrcAlphaFactor,
blendSrcAlpha: THREE.OneFactor,
blendDst: THREE.OneMinusSrcAlphaFactor

"use strict";

const nonPremultipledBlend = {
  blending: THREE.CustomBlending,
  blendEquation: THREE.AddEquation,
  blendSrc: THREE.SrcAlphaFactor,
  blendSrcAlpha: THREE.OneFactor,
  blendDst: THREE.OneMinusSrcAlphaFactor,
};

const premultipledBlend = {
  blending: THREE.CustomBlending,
  blendEquation: THREE.AddEquation,
  blendSrc: THREE.OneFactor,
  blendDst: THREE.OneMinusSrcAlphaFactor,
};

const renderer = new THREE.WebGLRenderer();
document.body.appendChild(renderer.domElement);
const camera = new THREE.OrthographicCamera(-1.5, 1.5, 1, -1, -1, 1);
camera.position.z = 1;
const scene = new THREE.Scene();
const geometry = new THREE.PlaneGeometry(.5, .5);
[
  { color: 0xFF8080, x: -.6,  y:    0, z: 0.2, },
  { color: 0x008040, x: -.30, y: -.25, z: 0.1, },
  { color: 0x008040, x: -.90, y: -.25, z: 0.1, blend: nonPremultipledBlend, },
  { color: 0xFF8080, x:  .6,  y:    0, z: 0.2, },
  { color: 0x008040, x:  .30, y: -.25, z: 0.1, pre: true, },
  { color: 0x008040, x:  .90, y: -.25, z: 0.1, pre: true, blend: premultipledBlend, },
].forEach(info => {
  const material = new THREE.MeshBasicMaterial({
    color: info.color,
    transparent: true,
    opacity: .5,
  });
  if (info.pre) {
    material.premultipliedAlpha = info.pre;
  }
  if (info.blend) {
    Object.assign(material, info.blend);
  }
  const mesh = new THREE.Mesh(geometry, material);
  scene.add(mesh);
  mesh.position.x = info.x;
  mesh.position.y = info.y;
  mesh.position.z = info.z;
});
renderer.render(scene, camera);

body { margin: 0; }
canvas { width: 100vw; height: 100vh; display block; }

<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/85/three.min.js"></script>


问:
how to get the cookies of two servers 1. runs application (HTTP) , 2. runs websocket(WS) server?
I have an application which is hosted on a tomcat server on port 8080. and the same application using websocket connection which is pointing to another tomcat server on port 1234. But when i executing "document.cookie" from web browser console it showing the cookies from websocket server(2nd server. port 1234) only, but i need all cookies from both servers.
can anybody help me?

答:
There's no way around this as that's the way cookies were designed - one server can't see another's cookies.

The easiest way for you to do this would be to add some proxy code into the Tomcat server that forwards all requests sent to a certain endpoint to your server on port 1234.

For example, if you want all requests going to http://localhost:8080/websockets to be forwarded to your server at http://localhost:1234 then configure Tomcat running on port 8080 like this:

```<code>ProxyPass         /websockets  http://localhost:1234/webapp
ProxyPassReverse  /websockets  http://localhost:1234/webapp
</code>```

Here are the docs for Tomcat proxy, they're a good start but are fairly basic:

https://tomcat.apache.org/tomcat-6.0-doc/proxy-howto.html

In production you'll probably have a dedicated proxy server in front of both (like Apache HTTP or NGINX) and that will also solve your cookie issue given that the browser will only be sending requests to a single server/port.

Body:
There's no way around this as that's the way cookies were designed - one server can't see another's cookies.

The easiest way for you to do this would be to add some proxy code into the Tomcat server that forwards all requests sent to a certain endpoint to your server on port 1234.

For example, if you want all requests going to http://localhost:8080/websockets to be forwarded to your server at http://localhost:1234 then configure Tomcat running on port 8080 like this:

ProxyPass         /websockets  http://localhost:1234/webapp
ProxyPassReverse  /websockets  http://localhost:1234/webapp

Here are the docs for Tomcat proxy, they're a good start but are fairly basic:

https://tomcat.apache.org/tomcat-6.0-doc/proxy-howto.html

In production you'll probably have a dedicated proxy server in front of both (like Apache HTTP or NGINX) and that will also solve your cookie issue given that the browser will only be sending requests to a single server/port.


问:
Trying to parse log file with regex
I am trying to parse a log file with a regex and I understand the first of pulling out the IP addressed but I am stuck on how to move beyond the rest of it for the log file. So to start parsing the rest do I just tack on the regex to parse out the date and etc?  So i would 2nd element to be the second ip of 72.37.100.86. Then I would like to exclude the "- - -" and have the date be the 4th element along with "GET / HTTP/1.1:" to be the 8th index along with the status code of 200 to be the 9th index.  Any help with this would be much appreciated in understanding what I need to do next.  </p>

```<code>package com.text.nginx_log_parser;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegExTester {

// Actual Entry : 10.10.100.151 - 72.37.100.86, 192.36.20.508 - - - [04/Jul/2016:12:50:06 +0000]  https https https "GET / HTTP/1.1" 200 20027 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.107 Safari/537.36"
public static String logEntry = "10.10.100.151 - 72.37.100.86, 192.36.20.508 - - - [04/Jul/2016:12:50:06 +0000]  https https https \"GET / HTTP/1.1\" 200 20027 \"-\" \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.107 Safari/537.36\"\r\n";

//public static String regex = "(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})";
//public static String regex = "(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})";
public static void main (String [] args){

    String regex = "(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})\\s*-*\\s*-*\\s*-*";
    regexChecker(regex, logEntry);
    regex = "\\[*\\]\\s.";
    regexChecker(regex, logEntry);
}

public static void regexChecker(String regex, String str){

    Pattern pattern = Pattern.compile(regex);

    Matcher matcher = pattern.matcher(logEntry);
    //String firstIP = matcher.group(0);
    //String secondIP = matcher.group();
    //String timestamp =
    while(matcher.find()){
        System.out.println( matcher.group(0));
    }
  }
}
</code>```

Title: Trying to parse log file with regex

Body:
I am trying to parse a log file with a regex and I understand the first of pulling out the IP addressed but I am stuck on how to move beyond the rest of it for the log file. So to start parsing the rest do I just tack on the regex to parse out the date and etc?  So i would 2nd element to be the second ip of 72.37.100.86. Then I would like to exclude the "- - -" and have the date be the 4th element along with "GET / HTTP/1.1:" to be the 8th index along with the status code of 200 to be the 9th index.  Any help with this would be much appreciated in understanding what I need to do next.

package com.text.nginx_log_parser;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegExTester {

// Actual Entry : 10.10.100.151 - 72.37.100.86, 192.36.20.508 - - - [04/Jul/2016:12:50:06 +0000]  https https https "GET / HTTP/1.1" 200 20027 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.107 Safari/537.36"
public static String logEntry = "10.10.100.151 - 72.37.100.86, 192.36.20.508 - - - [04/Jul/2016:12:50:06 +0000]  https https https \"GET / HTTP/1.1\" 200 20027 \"-\" \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.107 Safari/537.36\"\r\n";

//public static String regex = "(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})";
//public static String regex = "(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})";
public static void main (String [] args){

    String regex = "(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})\\s*-*\\s*-*\\s*-*";
    regexChecker(regex, logEntry);
    regex = "\\[*\\]\\s.";
    regexChecker(regex, logEntry);
}

public static void regexChecker(String regex, String str){

    Pattern pattern = Pattern.compile(regex);

    Matcher matcher = pattern.matcher(logEntry);
    //String firstIP = matcher.group(0);
    //String secondIP = matcher.group();
    //String timestamp =
    while(matcher.find()){
        System.out.println( matcher.group(0));
    }
  }
}

Body:
With the following regex:

(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})[-\s]+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}).+?\[(.+?)\].*?\"(.+?)\"\s(\d{3}).*$

you are looking at capture groups 1 through 5 as per this entry on regex101.com


问:
Android phone is not detected in visual studio 2015
I am developing Xamarin forms app. I am not able to deploy app in nexus 6p( phone is not listed in device list ). Tried below steps, still phone is not detected.

I have installed Google USB Driver using Android SDK manager.

I have downloaded usb driver for nexus 6p and done 'Update driver software'
option in device manager under 'Portable devices' section. Device
gets displayed as 'Nexus 6p' within Portable devices section in
device manager and also seen as local drive( next to C: drive ).

Selected droid project as startup project.

But phone is not listed in visual studio device list. Any help?

答:
Make sure the 'USB DEBUGGING' option in DEVELOPER OPTIONS remains checked on your connected Android Device.

I've lost lots of time because this item would uncheck itself for some reason between reboots/restarts and Enabling/Disabling the DEVELOPER OPTIONS.


问:
Setting edit text of fragment from Activity giving null pointer
I have just started using fragments. I have created a edit text in fragment and I want to fill it from activity but it is giving me null pointer exception. May be OnCreateView runs after fragmenttransaction is committed. I have made it working from another way but I am just a little curious why it is not working. I have searched it but could not find answer of my problem. Any help would be appreciated

Here is my code In activity:

```<code>FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Myfragment mFragment = new Myfragment();
fragmentTransaction.replace(R.id.fragment_container, mFragment);
fragmentTransaction.commit();

mFragment.set_fragment_editext("Hello world");//setting edit text in fragment throws exception
</code>```

Then in fragment class:

```<code>public class Myfragment extends Fragment {
    EditText edittext_fragment;

    public static Myfragment newInstance() {
        return new Myfragment();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View myInflatedView = inflater.inflate(R.layout.Myfragment, container, false);
        InitializeFragment(myInflatedView);
        return myInflatedView;
    }

    private void InitializeFragment(View myInflatedView) {
        edittext_fragment = (EditText) myInflatedView.findViewById(R.id.edittext_fragment_caption);
    }

    public void set_fragment_editext(String value) {
        edittext_fragment.setText(value);
    }

}
</code>```

答:
1) It takes some time to pass through fragment lifecycle.

2) It happens in the background.

```<code>Myfragment mFragment = new Myfragment();
fragmentTransaction.replace(R.id.fragment_container, mFragment);
fragmentTransaction.commit();

// EditText is not yet initialized
mFragment.set_fragment_editext("Hello world");//setting edit text in fragment throws exception
</code>```

It is common android task that you should do some things only when some components are inittialized.

In your case you can do this in several ways:

1) Postpone string set.

```<code>class Myfragment extedns Fragment {
    private String mEditTextString;
    private EditText edittext_fragment;

    public void setEditText(String string) {
        mEditTextString = string;
        if (edittext_fragment != null) {
            edittext_fragment.setText(string);
        }
    }

    private void InitializeFragment(View myInflatedView) {
        edittext_fragment = (EditText) myInflatedView.findViewById(R.id.edittext_fragment_caption);
        if (mEditTextString != null) {
            edittext_fragment.setText(mEditTextString);
        }
    }
}
</code>```

2) By callback to activity when edit text is inititlized. Please take a look at this guide https://developer.android.com/guide/components/fragments.html#CommunicatingWithActivity

3) As mentioned by @Karishnu Poddar if you want to set edit text just once you can pass it to fragment arguments

Body:
I have just started using fragments. I have created a edit text in fragment and I want to fill it from activity but it is giving me null pointer exception. May be OnCreateView runs after fragmenttransaction is committed. I have made it working from another way but I am just a little curious why it is not working. I have searched it but could not find answer of my problem. Any help would be appreciated

Here is my code In activity:

FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Myfragment mFragment = new Myfragment();
fragmentTransaction.replace(R.id.fragment_container, mFragment);
fragmentTransaction.commit();

mFragment.set_fragment_editext("Hello world");//setting edit text in fragment throws exception

Then in fragment class:

public class Myfragment extends Fragment {
    EditText edittext_fragment;

    public static Myfragment newInstance() {
        return new Myfragment();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View myInflatedView = inflater.inflate(R.layout.Myfragment, container, false);
        InitializeFragment(myInflatedView);
        return myInflatedView;
    }

    private void InitializeFragment(View myInflatedView) {
        edittext_fragment = (EditText) myInflatedView.findViewById(R.id.edittext_fragment_caption);
    }

    public void set_fragment_editext(String value) {
        edittext_fragment.setText(value);
    }

}

Body:
1) It takes some time to pass through fragment lifecycle.

2) It happens in the background.

Myfragment mFragment = new Myfragment();
fragmentTransaction.replace(R.id.fragment_container, mFragment);
fragmentTransaction.commit();

// EditText is not yet initialized
mFragment.set_fragment_editext("Hello world");//setting edit text in fragment throws exception

It is common android task that you should do some things only when some components are inittialized.

In your case you can do this in several ways:

1) Postpone string set.

class Myfragment extedns Fragment {
    private String mEditTextString;
    private EditText edittext_fragment;

    public void setEditText(String string) {
        mEditTextString = string;
        if (edittext_fragment != null) {
            edittext_fragment.setText(string);
        }
    }

    private void InitializeFragment(View myInflatedView) {
        edittext_fragment = (EditText) myInflatedView.findViewById(R.id.edittext_fragment_caption);
        if (mEditTextString != null) {
            edittext_fragment.setText(mEditTextString);
        }
    }
}

2) By callback to activity when edit text is inititlized. Please take a look at this guide https://developer.android.com/guide/components/fragments.html#CommunicatingWithActivity

3) As mentioned by @Karishnu Poddar if you want to set edit text just once you can pass it to fragment arguments


问:
PHPUnit LogicException: The request was not redirected. Symfony
I am trying to test a simple registration with phpunit with a redirect, I have all the time this error:

Test class:

```<code><?php

namespace Tests\AppBundle\Services;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class SecuriteTest extends WebTestCase
{

    private $user;

    public function __construct() {
        $this->user = static::createClient();
    }

    public function testsendCreateAccountMail(){

        $crawler = $this->user->request('GET', '/inscription');

        $this->assertEquals(1, $crawler->filter('h1:contains("Informations personnelles")')->count());

        $form = $crawler->selectButton('submitInscription')->form();

        $form['inscription[gender]']     = 'Masculin';
        $form['inscription[name]']       = 'Test';
        $form['inscription[firstName]']      = 'Test';
        $form['inscription[username]']    = 'Test-25@gmail.com';
        $form['inscription[birthDate]']    =  '05/10/1992';
        $form['inscription[pseudo]']    = 'Test';
        $form['inscription[password][first]']    = 'blablabla';
        $form['inscription[password][second]']    = 'blablabla';
        $form['inscription[account]']    = 'Particulier';
        $form['inscription[mentionsLegales]']    = '1';

        $this->user->submit($form);

        $crawler = $this->user->followRedirect();

        $this->assertEquals(1, $crawler->filter('.testFlash:contains("Vous allez recevoir une demande de confirmation sur votre adresse email")')->count());

    }
}
</code>```

I also try to test with a contact form with only 3 inputs, I still have the same error.

Thank you

答:
I suggest you to add more test about every aspect of the flow as example the http communication's status. As example you can add after every server interaction that the request was fine:

```<code>    $crawler = $this->user->request('GET', '/inscription');
    // check server response:
    $this->assertEquals(200, $client->getResponse()->getStatusCode(), $client->getResponse()->getContent());
    // or more simply:
    $this->assertTrue($client->getResponse()->isSuccessful());
    // then check the response content
    $this->assertEquals(1, $crawler->filter('h1:contains("Informations personnelles")')->count());
</code>```

In the same manner, before follow redirection test that the post work fine and don't give an error like 500:

```<code>    $this->user->submit($form);
    $this->assertTrue($client->getResponse()->isRedirection());
    $crawler = $this->user->followRedirect();
</code>```

Hope this help

Body:
I am trying to test a simple registration with phpunit with a redirect, I have all the time this error:

Test class:

<?php

namespace Tests\AppBundle\Services;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class SecuriteTest extends WebTestCase
{

    private $user;

    public function __construct() {
        $this->user = static::createClient();
    }

    public function testsendCreateAccountMail(){

        $crawler = $this->user->request('GET', '/inscription');

        $this->assertEquals(1, $crawler->filter('h1:contains("Informations personnelles")')->count());

        $form = $crawler->selectButton('submitInscription')->form();

        $form['inscription[gender]']     = 'Masculin';
        $form['inscription[name]']       = 'Test';
        $form['inscription[firstName]']      = 'Test';
        $form['inscription[username]']    = 'Test-25@gmail.com';
        $form['inscription[birthDate]']    =  '05/10/1992';
        $form['inscription[pseudo]']    = 'Test';
        $form['inscription[password][first]']    = 'blablabla';
        $form['inscription[password][second]']    = 'blablabla';
        $form['inscription[account]']    = 'Particulier';
        $form['inscription[mentionsLegales]']    = '1';

        $this->user->submit($form);

        $crawler = $this->user->followRedirect();

        $this->assertEquals(1, $crawler->filter('.testFlash:contains("Vous allez recevoir une demande de confirmation sur votre adresse email")')->count());

    }
}

I also try to test with a contact form with only 3 inputs, I still have the same error.

Thank you

Body:
I suggest you to add more test about every aspect of the flow as example the http communication's status. As example you can add after every server interaction that the request was fine:

    $crawler = $this->user->request('GET', '/inscription');
    // check server response:
    $this->assertEquals(200, $client->getResponse()->getStatusCode(), $client->getResponse()->getContent());
    // or more simply:
    $this->assertTrue($client->getResponse()->isSuccessful());
    // then check the response content
    $this->assertEquals(1, $crawler->filter('h1:contains("Informations personnelles")')->count());

In the same manner, before follow redirection test that the post work fine and don't give an error like 500:

    $this->user->submit($form);
    $this->assertTrue($client->getResponse()->isRedirection());
    $crawler = $this->user->followRedirect();

Hope this help


问:
Why does C# disallow readonly local variables?
Having a friendly debate with a co-worker about this.  We have some thoughts about this, but wondering what the SO crowd thinks about this?</p>

答: I think that's because a function that has a readonly variable may never be called, and there's probably something about it going out of scope, and when would you need to?</p>

OwnerDisplayName: Brian Genisio


问:
How to write a JASMINE test case for my method. Have been trying to mock the event listener. Please point to link or provide me with the mocks
Trying to write a jasmine test for the below code...

refreshCacheIfNewVersionIsAvailable();

```<code>//Check if a new cache is available on page load and reload the page to refresh app cache to the newer version of files
function refreshCacheIfNewVersionIsAvailable() {
    $window.addEventListener('load', function (e) {
        $window.applicationCache.addEventListener('updateready', function (e) {
            if ($window.applicationCache.status == window.applicationCache.UPDATEREADY) {
                // Manifest changed. Now Browser downloadeds a new app cache.
                alert(textService.versioning.newVersionMessage);
                $window.location.reload(true);
            } else {
                // Manifest didn't change. Nothing new to server.
            }
        }, false);
    }, false);
}
</code>```

答:
Your challenge

I assume the challenge you are facing is that you are unable to see how to test the code in the callback functions. You just have to realize that you have access to the callback function when you spy on addEventListener, after the spy is executed in your service under test (refreshCacheIfNewVersionIsAvailable). Since you can get a reference to it, you can execute it, just as if it was the function you were testing.

Sample solution

The following is untested, written off the top of my head, but something along the lines of what I would expect to write if I had to test that code.

```<code>describe('refreshCacheIfNewVersionIsAvailable()', function() {
  beforeEach(function() {
    spyOn($window, 'addEventListener');
  });

  it('should register a load event handler on the window', function() {
    refreshCacheIfNewVersionIsAvailable();

    expect($window.addEventListener.calls.count()).toBe(1);

    var args = $window.addEventListener.calls.argsFor(0);
    expect(args.length).toBe(3);
    expect(args[0]).toBe('load');
    expect(typeof args[1]).toBe('function');
    expect(args[2]).toBe(false);
  });

  describe('load event', function() {
    var loadFunction;

    beforeEach(function() {
      refreshCacheIfNewVersionIsAvailable();
      var args = $window.addEventListener.calls.argsFor(0);
      loadFunction = args[1];

      spyOn($window.applicationCache, 'addEventListener');
    });

    it('should register an updateready event handler in the window application cache', function() {
      loadFunction();

      expect($window.applicationCache.addEventListener.calls.count()).toBe(1);

      var args = $window.applicationCache.addEventListener.calls.argsFor(0);
      expect(args.length).toBe(3);
      expect(args[0]).toBe('updateReady');
      expect(typeof args[1]).toBe('function');
      expect(args[2]).toBe(false);
    });

    describe('updateready event', function() {
      var updateReadyFunction;

      beforeEach(function() {
        loadFunction();
        var args = $window.applicationCache.addEventListener.calls.argsFor(0);
        updateReadyFunction = args[1];
      });

      it('should reload the window if the status is UPDATEREADY', function() {
        // You get the point
      });
    });
  });
});
</code>```

Body:
Trying to write a jasmine test for the below code...

refreshCacheIfNewVersionIsAvailable();

//Check if a new cache is available on page load and reload the page to refresh app cache to the newer version of files
function refreshCacheIfNewVersionIsAvailable() {
    $window.addEventListener('load', function (e) {
        $window.applicationCache.addEventListener('updateready', function (e) {
            if ($window.applicationCache.status == window.applicationCache.UPDATEREADY) {
                // Manifest changed. Now Browser downloadeds a new app cache.
                alert(textService.versioning.newVersionMessage);
                $window.location.reload(true);
            } else {
                // Manifest didn't change. Nothing new to server.
            }
        }, false);
    }, false);
}

Body:
Your challenge

I assume the challenge you are facing is that you are unable to see how to test the code in the callback functions. You just have to realize that you have access to the callback function when you spy on addEventListener, after the spy is executed in your service under test (refreshCacheIfNewVersionIsAvailable). Since you can get a reference to it, you can execute it, just as if it was the function you were testing.

Sample solution

The following is untested, written off the top of my head, but something along the lines of what I would expect to write if I had to test that code.

describe('refreshCacheIfNewVersionIsAvailable()', function() {
  beforeEach(function() {
    spyOn($window, 'addEventListener');
  });

  it('should register a load event handler on the window', function() {
    refreshCacheIfNewVersionIsAvailable();

    expect($window.addEventListener.calls.count()).toBe(1);

    var args = $window.addEventListener.calls.argsFor(0);
    expect(args.length).toBe(3);
    expect(args[0]).toBe('load');
    expect(typeof args[1]).toBe('function');
    expect(args[2]).toBe(false);
  });

  describe('load event', function() {
    var loadFunction;

    beforeEach(function() {
      refreshCacheIfNewVersionIsAvailable();
      var args = $window.addEventListener.calls.argsFor(0);
      loadFunction = args[1];

      spyOn($window.applicationCache, 'addEventListener');
    });

    it('should register an updateready event handler in the window application cache', function() {
      loadFunction();

      expect($window.applicationCache.addEventListener.calls.count()).toBe(1);

      var args = $window.applicationCache.addEventListener.calls.argsFor(0);
      expect(args.length).toBe(3);
      expect(args[0]).toBe('updateReady');
      expect(typeof args[1]).toBe('function');
      expect(args[2]).toBe(false);
    });

    describe('updateready event', function() {
      var updateReadyFunction;

      beforeEach(function() {
        loadFunction();
        var args = $window.applicationCache.addEventListener.calls.argsFor(0);
        updateReadyFunction = args[1];
      });

      it('should reload the window if the status is UPDATEREADY', function() {
        // You get the point
      });
    });
  });
});


问:
Android app layout: elements appear on different places
I'm developing Android version of our iOS app, but having layout issues. Elements appear on different places on different screen sizes. Here's the iOS counterpart I have to replicate.
iPhone's layout

Here's my app. What will be the best layout combination to replicate the iOS counterpart.

Here's my version:

Android layout image

Here's the xml of my layout:

```<code>    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000">

    <TextView
        android:id="@+id/text_rssi"
        android:layout_width="@dimen/_90sdp"
        android:layout_height="@dimen/_16sdp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="@dimen/_50sdp"
        android:background="@drawable/btn_indicators_disconnect" />

    <TextView
        android:id="@+id/text_rssi_val"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/text_rssi"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="@dimen/_5sdp"
        android:text="0"
        android:textColor="#FFF"
        android:textSize="@dimen/_12sdp" />

    <LinearLayout
        android:id="@+id/layout_circle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/searching_all_off_circle"
        android:orientation="vertical"
        android:padding="@dimen/_5sdp"
        android:layout_below="@+id/text_rssi_val"
        android:layout_alignParentEnd="true"
        android:layout_marginEnd="53dp">

        <Button
            android:id="@+id/btn_CheckLister"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_margin="@dimen/_45sdp"
            android:background="@drawable/searching_all_off" />
    </LinearLayout>

    <RelativeLayout
        android:id="@+id/rl_btnLock"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/btn_parked_location"
        android:layout_marginBottom="@dimen/_20sdp">

        <Button
            android:id="@+id/btn_unlock"
            android:layout_width="@dimen/_55sdp"
            android:layout_height="@dimen/_55sdp"
            android:layout_alignParentLeft="true"
            android:layout_marginLeft="@dimen/_65sdp"
            android:background="@drawable/unlock_unpressed" />

        <Button
            android:id="@+id/btn_lock"
            android:layout_width="@dimen/_55sdp"
            android:layout_height="@dimen/_55sdp"
            android:layout_alignParentRight="true"
            android:layout_marginRight="@dimen/_65sdp"
            android:background="@drawable/lock_unpressed" />
    </RelativeLayout>

    <Button
        android:id="@+id/btn_parked_location"
        android:layout_width="@dimen/_150sdp"
        android:layout_height="@dimen/_35sdp"
        android:layout_above="@+id/ble_list_devices"
        android:layout_centerHorizontal="true"
        android:layout_centerInParent="true"
        android:layout_marginBottom="@dimen/_12sdp"
        android:background="@drawable/parked_icon" />

    <TextView
        android:id="@+id/ble_list_devices"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="#565656"
        android:padding="@dimen/_8sdp"
        android:text="Searching..."
        android:textAlignment="center"
        android:textColor="#FFF"
        android:textSize="@dimen/_14sdp" />

</RelativeLayout>
</code>```

答:
I modified your code. Since I'm not having corresponding images I used ic_launcher image to all images you can replace it, wrt your requirement here is the following code</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000">

    <TextView
        android:id="@+id/text_rssi"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:background="@mipmap/ic_launcher"  />

    <TextView
        android:id="@+id/text_rssi_val"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/text_rssi"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="5dp"
        android:text="0"
        android:textColor="#FFF"
        android:textSize="12dp" />

        <ImageButton
            android:layout_below="@+id/text_rssi_val"
            android:id="@+id/btn_CheckLister"
            android:layout_centerInParent="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_margin="45dp"
            android:src="@mipmap/ic_launcher"
            android:background="@null"/>

    <LinearLayout
        android:orientation="horizontal"
        android:id="@+id/rl_btnLock"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:weightSum="2"
        android:layout_above="@+id/btn_parked_location"
        android:layout_marginBottom="20dp">

        <ImageButton
            android:id="@+id/btn_unlock"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_weight="1"
            android:background="@null"
            android:src="@mipmap/ic_launcher"/>

        <ImageButton
            android:id="@+id/btn_lock"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@null"
            android:src="@mipmap/ic_launcher"/>
    </LinearLayout>

    <ImageButton
        android:id="@+id/btn_parked_location"
        android:layout_width="150dp"
        android:layout_height="35dp"
        android:layout_above="@+id/ble_list_devices"
        android:layout_centerHorizontal="true"
        android:layout_centerInParent="true"
        android:layout_marginBottom="12dp"
        android:background="@null"
        android:src="@mipmap/ic_launcher"/>

    <TextView
        android:id="@+id/ble_list_devices"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="#565656"
        android:padding="8dp"
        android:text="Searching..."
        android:textAlignment="center"
        android:textColor="#FFF"
        android:textSize="14dp" />
</RelativeLayout>
</code>```

Body:
I'm developing Android version of our iOS app, but having layout issues. Elements appear on different places on different screen sizes. Here's the iOS counterpart I have to replicate.
iPhone's layout

Here's my app. What will be the best layout combination to replicate the iOS counterpart.

Here's my version:

Android layout image

Here's the xml of my layout:

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000">

    <TextView
        android:id="@+id/text_rssi"
        android:layout_width="@dimen/_90sdp"
        android:layout_height="@dimen/_16sdp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="@dimen/_50sdp"
        android:background="@drawable/btn_indicators_disconnect" />

    <TextView
        android:id="@+id/text_rssi_val"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/text_rssi"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="@dimen/_5sdp"
        android:text="0"
        android:textColor="#FFF"
        android:textSize="@dimen/_12sdp" />

    <LinearLayout
        android:id="@+id/layout_circle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/searching_all_off_circle"
        android:orientation="vertical"
        android:padding="@dimen/_5sdp"
        android:layout_below="@+id/text_rssi_val"
        android:layout_alignParentEnd="true"
        android:layout_marginEnd="53dp">

        <Button
            android:id="@+id/btn_CheckLister"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_margin="@dimen/_45sdp"
            android:background="@drawable/searching_all_off" />
    </LinearLayout>

    <RelativeLayout
        android:id="@+id/rl_btnLock"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/btn_parked_location"
        android:layout_marginBottom="@dimen/_20sdp">

        <Button
            android:id="@+id/btn_unlock"
            android:layout_width="@dimen/_55sdp"
            android:layout_height="@dimen/_55sdp"
            android:layout_alignParentLeft="true"
            android:layout_marginLeft="@dimen/_65sdp"
            android:background="@drawable/unlock_unpressed" />

        <Button
            android:id="@+id/btn_lock"
            android:layout_width="@dimen/_55sdp"
            android:layout_height="@dimen/_55sdp"
            android:layout_alignParentRight="true"
            android:layout_marginRight="@dimen/_65sdp"
            android:background="@drawable/lock_unpressed" />
    </RelativeLayout>

    <Button
        android:id="@+id/btn_parked_location"
        android:layout_width="@dimen/_150sdp"
        android:layout_height="@dimen/_35sdp"
        android:layout_above="@+id/ble_list_devices"
        android:layout_centerHorizontal="true"
        android:layout_centerInParent="true"
        android:layout_marginBottom="@dimen/_12sdp"
        android:background="@drawable/parked_icon" />

    <TextView
        android:id="@+id/ble_list_devices"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="#565656"
        android:padding="@dimen/_8sdp"
        android:text="Searching..."
        android:textAlignment="center"
        android:textColor="#FFF"
        android:textSize="@dimen/_14sdp" />

</RelativeLayout>

Body:
I modified your code. Since I'm not having corresponding images I used ic_launcher image to all images you can replace it, wrt your requirement here is the following code

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000">

    <TextView
        android:id="@+id/text_rssi"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:background="@mipmap/ic_launcher"  />

    <TextView
        android:id="@+id/text_rssi_val"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/text_rssi"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="5dp"
        android:text="0"
        android:textColor="#FFF"
        android:textSize="12dp" />

        <ImageButton
            android:layout_below="@+id/text_rssi_val"
            android:id="@+id/btn_CheckLister"
            android:layout_centerInParent="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_margin="45dp"
            android:src="@mipmap/ic_launcher"
            android:background="@null"/>

    <LinearLayout
        android:orientation="horizontal"
        android:id="@+id/rl_btnLock"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:weightSum="2"
        android:layout_above="@+id/btn_parked_location"
        android:layout_marginBottom="20dp">

        <ImageButton
            android:id="@+id/btn_unlock"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_weight="1"
            android:background="@null"
            android:src="@mipmap/ic_launcher"/>

        <ImageButton
            android:id="@+id/btn_lock"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@null"
            android:src="@mipmap/ic_launcher"/>
    </LinearLayout>

    <ImageButton
        android:id="@+id/btn_parked_location"
        android:layout_width="150dp"
        android:layout_height="35dp"
        android:layout_above="@+id/ble_list_devices"
        android:layout_centerHorizontal="true"
        android:layout_centerInParent="true"
        android:layout_marginBottom="12dp"
        android:background="@null"
        android:src="@mipmap/ic_launcher"/>

    <TextView
        android:id="@+id/ble_list_devices"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="#565656"
        android:padding="8dp"
        android:text="Searching..."
        android:textAlignment="center"
        android:textColor="#FFF"
        android:textSize="14dp" />
</RelativeLayout>


问:
Get date of creation for article in google analytics api
How I can get date of creation for article from google analytics api?
For example, for page title I use dimensions with name ga:pageTitle, but can I get page creation date?

答:
Unless you've deliberately fed this information to Google Analytics (using a Custom Dimension, uploaded data, or similar), there's no way to get this.

What you can do is find the first time the page was ever visited, but that's not available through a dimension; instead you'd have to pick a series of date ranges and check for presence of the page; this would also only work if the page has consistently had traffic.


问:
Django web app deploy in Azure via Visual Studio 2017
I've made a simple app with Django in Visual Studio 2017, utilizing the default template in Visual Studio (file - new - project - python - django web application).
The app runs properly locally, but after i deploy it to Azure via Visual Studio, i can only access the page that shows:

```<code>Your App Service app has been created.
</code>```

The files are all properly uploaded (i can see them in the 'site\wwwroot' folder), but the app doesn't work!

I have tried every thing that i was able to find in my searches such as: following this tutorial; adding '.azurewebsites.net' to the allowed hosts, installing azure sdk in my project virtual environment via: 'pip install azure', adding 'manage.py' to default documents, among many other things.

The thing is when i deploy (in the exact same way: right click the project, select publish, azure...) my ASP.NET apps to Azure, they work properly with minimum effort.

I am very frustated, because i really like Django framework and Azure, please help.

Thanks in advance!

答:
In consideration of using Visual Studio to create & deploy a Django App for Azure, I suggest that you can follow the Azure offical tutorial Django and MySQL on Azure with Python Tools 2.2 for Visual Studio to inspect & make sure your steps correctly.

There are some checkpoints as below.

Make sure PTVS installed correctly, please move to here to know more details of PTVS.

Create a virtual environment for a Python version like 2.7 via PTVS.

Edit the requirements.txt file of your project, and make sure there is a record for Django like Django==1.11.2.

When you want to deploy it to Azure WebApps, please check the Python version for Azure WebApps that is the same with your project.

If your Django App doesn't still work as you want, please refer to the document to check the configuration of the web.config file via access the Kudu tool https://<your app name>.scm.azurewebsites.net and other troubleshooting content, and refer to the document to check the application settings on Azure portal.

Hope it helps. Any concern, please feel free to let me know.

Body:
I've made a simple app with Django in Visual Studio 2017, utilizing the default template in Visual Studio (file - new - project - python - django web application).
The app runs properly locally, but after i deploy it to Azure via Visual Studio, i can only access the page that shows:

Your App Service app has been created.

The files are all properly uploaded (i can see them in the 'site\wwwroot' folder), but the app doesn't work!

I have tried every thing that i was able to find in my searches such as: following this tutorial; adding '.azurewebsites.net' to the allowed hosts, installing azure sdk in my project virtual environment via: 'pip install azure', adding 'manage.py' to default documents, among many other things.

The thing is when i deploy (in the exact same way: right click the project, select publish, azure...) my ASP.NET apps to Azure, they work properly with minimum effort.

I am very frustated, because i really like Django framework and Azure, please help.

Thanks in advance!


问:
What is this GUID?
After connect a network-drive, when we open a Windows Explorer or a File Dialog,
the process find this key in the registry to show it's volume name.

HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\MountPoints2\{A45BA3B2-F3
  96-4F67-8375-ECC2CA1EBBFC}\_LabelFromReg

I don't know what the GUID is.

What is it?

Who(When) does create the key?

How does the application(in this case, Windows Explorer) know the key?

I'm developing a network-redirector like SMB.

I should write a volume name to the key.

Once my network volume connected, the registry key also created. (of cource the GUID is different with SMB's. It even changes whenever each connection created and deleted)

But I don't know how I can get the my volume's(?) GUID.(Even who creates the key)

I tried to find DefineDosDeviceW(suspected) in ReactOS source. But it hasn't implemented yet. T.T

-Of course, I also write the volume name to \MountPoints2\##UNCNAME\_LabelFromReg

But it doesn't work for WOW64 applications in 64Bit Windows.

答: This is not a specific GUID; it's a volume identifier. Windows Explorer creates these keys when volumes are mounted. You can see a list of currently mounted volume IDs by running mountvol without parameters. Programmatically (on Win32 level), you can obtain it with FindFirstVolume and friends. I don't know anything about network redirector; however, it doesn't seem right to poke within Explorer registry key manually. It's Explorer's private territory. What are you trying to accomplish? Maybe there is a documented API for that.

Title: What is this GUID?


问:
Return Object of Class to Main Program
I am not so familiar with C++ and currently trying to code a class 'fraction'. I want to code a method 'Input' where a user gives values to a fraction. These values should be available throughout the program. This is what I have so far:

Call:

```<code>BRUCH t1;
   t1.Eingabe();
</code>```

Method:

```<code>    BRUCH BRUCH::Eingabe()
{
    int _z, _n;
    BRUCH bruch;
    cout << "Bitte einen Zaehlerwert eingeben: " << endl;
    cin >> _z;
    cout << "Bitte einen Nennerwert eingeben: " << endl;
    cin >> _n;
    while(_n==0)
    {
        cout << "Bitte einen gültigen Wert eingeben!" << endl;
        cin >> _n;
    }
    bruch.z = _z;
    bruch.n = _n;
    return bruch;
}
</code>```

When I return the object the values vanish and the constructor creates a new object with default values.

What must I do to get the correct return?

Bruch - Fraction (math.) | Eingabe - Input

答:
It doesn't look like you ever assigned the new value to anything</p>

```<code>BRUCH t1;
BRUCH new_value = t1.Eingabe();
</code>```

Title: Return Object of Class to Main Program

Body:
I am not so familiar with C++ and currently trying to code a class 'fraction'. I want to code a method 'Input' where a user gives values to a fraction. These values should be available throughout the program. This is what I have so far:

Call:

BRUCH t1;
   t1.Eingabe();

Method:

    BRUCH BRUCH::Eingabe()
{
    int _z, _n;
    BRUCH bruch;
    cout << "Bitte einen Zaehlerwert eingeben: " << endl;
    cin >> _z;
    cout << "Bitte einen Nennerwert eingeben: " << endl;
    cin >> _n;
    while(_n==0)
    {
        cout << "Bitte einen gültigen Wert eingeben!" << endl;
        cin >> _n;
    }
    bruch.z = _z;
    bruch.n = _n;
    return bruch;
}

When I return the object the values vanish and the constructor creates a new object with default values.

What must I do to get the correct return?

Bruch - Fraction (math.) | Eingabe - Input

Body:
It doesn't look like you ever assigned the new value to anything

BRUCH t1;
BRUCH new_value = t1.Eingabe();


问:
how to refresh data every 5 second using observable
I am quite new to angular2 and rxjs. I am trying to create an angular2 app that gets some data from jsonAPI,

i want to get data every 5 second,
i found a solution with Observable.interval(5000) but i have some error while compiling,

how to insert Observable.interval(500) in ngOnInit() code

please!!

```<code>   import { Component, OnInit }  from '@angular/core';

import { IProduct } from './product';
import { ProductService } from './product.service';

@Component({
    templateUrl: 'app/products/product-list.component.html',
    styleUrls: ['app/products/product-list.component.css']
})
export class ProductListComponent implements OnInit {
    pageTitle: string = 'Product List';
    imageWidth: number = 50;
    imageMargin: number = 2;
    showImage: boolean = false;
    listFilter: string;
    errorMessage: string;

    products: IProduct[];

    constructor(private _productService: ProductService) {

    }

    toggleImage(): void {
        this.showImage = !this.showImage;
    }

    ngOnInit(): void {
        this._productService.getProducts()
                .subscribe(products => this.products = products,
                           error => this.errorMessage = <any>error);
    }

    onRatingClicked(message: string): void {
        this.pageTitle = 'Product List: ' + message;
    }
}
</code>```

productservice.ts

```<code>import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/throw';

import { IProduct } from './product';

@Injectable()
export class ProductService {
    private _productUrl = 'api/products/products.json';

    constructor(private _http: Http) { }

    getProducts(): Observable<IProduct[]> {
        return this._http.get(this._productUrl)
            .map((response: Response) => <IProduct[]> response.json())
            .do(data => console.log('All: ' +  JSON.stringify(data)))
            .catch(this.handleError);
    }

    getProduct(id: number): Observable<IProduct> {
        return this.getProducts()
            .map((products: IProduct[]) => products.find(p => p.productId === id));
    }

    private handleError(error: Response) {
        // in a real world app, we may send the server to some remote logging infrastructure
        // instead of just logging it to the console
        console.error(error);
        return Observable.throw(error.json().error || 'Server error');
    }
}
</code>```

答:
make sure your service look like this and you don't miss any imports:

```<code>import 'rxjs/Rx';
import {Injectable} from '@angular/core';
import {Http} from '@angular/http';

  @Injectable()
    export class ProductService{
      constructor(private _http:Http) {}

      getData() {
        return Observable.interval(5000).flatMap(() => {
          return this._http.get(`URL GOES HERE`)
            .map(res => res.json());
        });
      }
    }
</code>```

and in your component:

```<code>import { Component, OnInit }  from '@angular/core';
import { ProductService } from './product.service';

export class ProductListComponent implements OnInit {
    constructor(public _productService: ProductService) {}

 ngOnInit() {
    this._productService.getData()
      .subscribe(data => this.products = data,
               err => console.log(err));
  }
}
</code>```

This should work but make sure that you share any errors that you get in the console as your question is missing that.

Body:
I am quite new to angular2 and rxjs. I am trying to create an angular2 app that gets some data from jsonAPI,

i want to get data every 5 second,
i found a solution with Observable.interval(5000) but i have some error while compiling,

how to insert Observable.interval(500) in ngOnInit() code

please!!

   import { Component, OnInit }  from '@angular/core';

import { IProduct } from './product';
import { ProductService } from './product.service';

@Component({
    templateUrl: 'app/products/product-list.component.html',
    styleUrls: ['app/products/product-list.component.css']
})
export class ProductListComponent implements OnInit {
    pageTitle: string = 'Product List';
    imageWidth: number = 50;
    imageMargin: number = 2;
    showImage: boolean = false;
    listFilter: string;
    errorMessage: string;

    products: IProduct[];

    constructor(private _productService: ProductService) {

    }

    toggleImage(): void {
        this.showImage = !this.showImage;
    }

    ngOnInit(): void {
        this._productService.getProducts()
                .subscribe(products => this.products = products,
                           error => this.errorMessage = <any>error);
    }

    onRatingClicked(message: string): void {
        this.pageTitle = 'Product List: ' + message;
    }
}

productservice.ts

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/throw';

import { IProduct } from './product';

@Injectable()
export class ProductService {
    private _productUrl = 'api/products/products.json';

    constructor(private _http: Http) { }

    getProducts(): Observable<IProduct[]> {
        return this._http.get(this._productUrl)
            .map((response: Response) => <IProduct[]> response.json())
            .do(data => console.log('All: ' +  JSON.stringify(data)))
            .catch(this.handleError);
    }

    getProduct(id: number): Observable<IProduct> {
        return this.getProducts()
            .map((products: IProduct[]) => products.find(p => p.productId === id));
    }

    private handleError(error: Response) {
        // in a real world app, we may send the server to some remote logging infrastructure
        // instead of just logging it to the console
        console.error(error);
        return Observable.throw(error.json().error || 'Server error');
    }
}

Body:
make sure your service look like this and you don't miss any imports:

import 'rxjs/Rx';
import {Injectable} from '@angular/core';
import {Http} from '@angular/http';

  @Injectable()
    export class ProductService{
      constructor(private _http:Http) {}

      getData() {
        return Observable.interval(5000).flatMap(() => {
          return this._http.get(`URL GOES HERE`)
            .map(res => res.json());
        });
      }
    }

and in your component:

import { Component, OnInit }  from '@angular/core';
import { ProductService } from './product.service';

export class ProductListComponent implements OnInit {
    constructor(public _productService: ProductService) {}

 ngOnInit() {
    this._productService.getData()
      .subscribe(data => this.products = data,
               err => console.log(err));
  }
}

This should work but make sure that you share any errors that you get in the console as your question is missing that.


问:
JQuery .text() Multi-Line
Is there a way I can turn this obnoxiously long line of text into a paragraph?

Before:

```<code>$('.ContText-1').text('For a business to thrive, it needs a team of people who are dedicated to its success. Paul Lister, Bryan Jeter, and Bryan Lloyd are committed to being a part of that team for each of their clients.');
</code>```

After:

```<code>$('.ContText-1').text('
             For a business to thrive, it needs a team of people who are dedicated to its
        success. Paul Lister, Bryan Jeter, and Bryan Lloyd are committed to being a part of
        that team for each of their clients.
');
</code>```

If I run the paragraph one I get this error: Uncaught SyntaxError: Invalid or unexpected token

Its referencing to the single quotation mark after the (.

答:
instead of text() method use html() method and use
 to break the line

```<code>$('.ContText-1').html('<br/>For a business to thrive, it needs a team of people who are dedicated to its <br/>success. Paul Lister, Bryan Jeter, and Bryan Lloyd are committed to being a part of <br/> that team for each of their clients.');
</code>```

Title: JQuery .text() Multi-Line

Body:
Is there a way I can turn this obnoxiously long line of text into a paragraph?

Before:

$('.ContText-1').text('For a business to thrive, it needs a team of people who are dedicated to its success. Paul Lister, Bryan Jeter, and Bryan Lloyd are committed to being a part of that team for each of their clients.');

After:

$('.ContText-1').text('
             For a business to thrive, it needs a team of people who are dedicated to its
        success. Paul Lister, Bryan Jeter, and Bryan Lloyd are committed to being a part of
        that team for each of their clients.
');

If I run the paragraph one I get this error: Uncaught SyntaxError: Invalid or unexpected token

Its referencing to the single quotation mark after the (.

Body:
instead of text() method use html() method and use <br/> to break the line

$('.ContText-1').html('<br/>For a business to thrive, it needs a team of people who are dedicated to its <br/>success. Paul Lister, Bryan Jeter, and Bryan Lloyd are committed to being a part of <br/> that team for each of their clients.');


问:
Functional switch statement in Javascript
Say I have a switch statement that takes a variable myData between 1 and some larger value, i.e. 300.

Depending on the "status code" variable, the result is the text value of another variable. For example, if myData == 1, I want to return the a variable called code1. If myData == 300, I want to return the a variable called code300. Code1 and code300 variables store unrelated strings, i.e. "This is a summary", or "This is a note". Some psuedo-code below:

```<code>var myData = statusCode;

var code1 = "This is a summary";
var code300 = "This is a note";

switch(myData) {
    case statusCode:
        scriptletResult = returnCode("code", statusCode); // code1 if myData == 1
        break;
    default:
        scriptletResult = code1;
}

function returnCode(code, statusCode) {
    return code + statusCode; // Returns a variable "code1" if statusCode == 1
}
</code>```

How can I get this to work?

答:
@Bergi's answer is the best approach, but if you can't change the way your code-message combos are stored, and the variables are globals, you can use:</p>

```<code>scriptletResult=window["code"+myData];
</code>```

Body:
Say I have a switch statement that takes a variable myData between 1 and some larger value, i.e. 300.

Depending on the "status code" variable, the result is the text value of another variable. For example, if myData == 1, I want to return the a variable called code1. If myData == 300, I want to return the a variable called code300. Code1 and code300 variables store unrelated strings, i.e. "This is a summary", or "This is a note". Some psuedo-code below:

var myData = statusCode;

var code1 = "This is a summary";
var code300 = "This is a note";

switch(myData) {
    case statusCode:
        scriptletResult = returnCode("code", statusCode); // code1 if myData == 1
        break;
    default:
        scriptletResult = code1;
}

function returnCode(code, statusCode) {
    return code + statusCode; // Returns a variable "code1" if statusCode == 1
}

How can I get this to work?

Body:
@Bergi's answer is the best approach, but if you can't change the way your code-message combos are stored, and the variables are globals, you can use:

scriptletResult=window["code"+myData];


问:
Combining two python codes for raspberry pi with a servo and ldr sensor
I have Python code running on my raspberry pi 2b and a light sensor, which measures the amount of time it takes for the capacitor of the light sensor to charge and send the pin high:

```<code>import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BOARD)

pin_to_circuit = 7

def rc_time (pin_to_circuit):
    count = 0

    #Output on the pin for
    GPIO.setup(pin_to_circuit, GPIO.OUT)
    GPIO.output(pin_to_circuit, GPIO.LOW)
    time.sleep(0.1)

    #Change the pin back to input
    GPIO.setup(pin_to_circuit, GPIO.IN)

    #Count until the pin goes high
    while (GPIO.input(pin_to_circuit) == GPIO.LOW):
        count += 1

    if count > 1000000:
        return True
    else:
        return count

#Catch when script is interrupted, cleanup correctly
try:
# Main loop
while True:
    print rc_time(pin_to_circuit)
except KeyboardInterrupt:
    pass
finally:
    GPIO.cleanup()
</code>```

I want when the count goes higher than 1000000, a MG90S, that I have also connected to the pi and a 4AA battery pack, moves about 90 degrees.
The code I was trying to integrate to move the servo:

```<code>import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BOARD)
GPIO.setup(12, GPIO.OUT)

p.ChangeDutyCycle(7.5)  # turn towards 90 degree
time.sleep(1) # sleep 1 second
p.stop()
GPIO.cleanup()
</code>```

I want to combine these two Python codes. I tried for a bit, but I have almost no Python experience.

答:
The code is now:

```<code>import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BOARD)
pin_to_circuit = 7

def move_90_degrees():
    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(12, GPIO.OUT)
    p = GPIO.PWM(12, 50)
    p.start(7.5)
    p.ChangeDutyCycle(7.5)  # turn towards 90 degree
    time.sleep(1) # sleep 1 second
    p.stop()

def rc_time (pin_to_circuit):
    count = 0

    #Output on the pin for
    GPIO.setup(pin_to_circuit, GPIO.OUT)
    GPIO.output(pin_to_circuit, GPIO.LOW)
    time.sleep(0.1)

    #Change the pin back to input
    GPIO.setup(pin_to_circuit, GPIO.IN)

    #Count until the pin goes high
    while (GPIO.input(pin_to_circuit) == GPIO.LOW):
        count += 1

    if count > 1000000:
        return True
        move_90_degrees()
    else:
        return count

#Catch when script is interrupted, cleanup correctly
try:
    # Main loop
    while True:
        print rc_time(pin_to_circuit)
except KeyboardInterrupt:
    pass
finally:
    GPIO.cleanup()
</code>```

The code does print True when the count exceeds 1000000, but the servo still doesn't move. The servo code on its own does however work correctly. (I forgot a bit of the servo code, that's why p wasn't defined, sorry.)

Body:
I have Python code running on my raspberry pi 2b and a light sensor, which measures the amount of time it takes for the capacitor of the light sensor to charge and send the pin high:

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BOARD)

pin_to_circuit = 7

def rc_time (pin_to_circuit):
    count = 0

    #Output on the pin for
    GPIO.setup(pin_to_circuit, GPIO.OUT)
    GPIO.output(pin_to_circuit, GPIO.LOW)
    time.sleep(0.1)

    #Change the pin back to input
    GPIO.setup(pin_to_circuit, GPIO.IN)

    #Count until the pin goes high
    while (GPIO.input(pin_to_circuit) == GPIO.LOW):
        count += 1

    if count > 1000000:
        return True
    else:
        return count

#Catch when script is interrupted, cleanup correctly
try:
# Main loop
while True:
    print rc_time(pin_to_circuit)
except KeyboardInterrupt:
    pass
finally:
    GPIO.cleanup()

I want when the count goes higher than 1000000, a MG90S, that I have also connected to the pi and a 4AA battery pack, moves about 90 degrees.
The code I was trying to integrate to move the servo:

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BOARD)
GPIO.setup(12, GPIO.OUT)

p.ChangeDutyCycle(7.5)  # turn towards 90 degree
time.sleep(1) # sleep 1 second
p.stop()
GPIO.cleanup()

I want to combine these two Python codes. I tried for a bit, but I have almost no Python experience.

Body:
The code is now:

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BOARD)
pin_to_circuit = 7

def move_90_degrees():
    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(12, GPIO.OUT)
    p = GPIO.PWM(12, 50)
    p.start(7.5)
    p.ChangeDutyCycle(7.5)  # turn towards 90 degree
    time.sleep(1) # sleep 1 second
    p.stop()

def rc_time (pin_to_circuit):
    count = 0

    #Output on the pin for
    GPIO.setup(pin_to_circuit, GPIO.OUT)
    GPIO.output(pin_to_circuit, GPIO.LOW)
    time.sleep(0.1)

    #Change the pin back to input
    GPIO.setup(pin_to_circuit, GPIO.IN)

    #Count until the pin goes high
    while (GPIO.input(pin_to_circuit) == GPIO.LOW):
        count += 1

    if count > 1000000:
        return True
        move_90_degrees()
    else:
        return count

#Catch when script is interrupted, cleanup correctly
try:
    # Main loop
    while True:
        print rc_time(pin_to_circuit)
except KeyboardInterrupt:
    pass
finally:
    GPIO.cleanup()

The code does print True when the count exceeds 1000000, but the servo still doesn't move. The servo code on its own does however work correctly. (I forgot a bit of the servo code, that's why p wasn't defined, sorry.)


问:
Add a Character Between Strings in C++
So basically I'm trying to add a character in the middle of a string. Normally in something like Python, this would be pretty straightforward, but I'm really not sure how to achieve this in C++. What I'm trying to achieve is something like this:

```<code>void converter(){
    converted = ":regional_indicator_" + character + ":";

}
</code>```

So basically, I'm trying to add the variable character of a type char in a string. Should I be storing character as a string instead?

For reference here's all of my code:

```<code>#include <iostream>

using namespace std;

string inputLine;
char character;
string converted;

void input(){
    cout << "Please input the text in which you would like to be converted" << endl;
    cin >> inputLine;
}

void converter(){
    converted = ":regional_indicator_" + character + ":";

}
int main(){
    input();
    for (int i = 0; i < inputLine.length(); i++ ){
        character = tolower(inputLine[i]);
    }
    return 0;
}
</code>```

答:
You can do it like this:

```<code>converted = ":regional_indicator_" + std::string(1, character) + ":";
</code>```

This works because adding a string literal (const char *) to a string yields a string. But adding const char * and char results in pointer arithmetic. So, by constructing a std::string from "character" you end up with const char * + std::string yielding a string and then std::string + const char * again yields a string as the final result.

Title: Add a Character Between Strings in C++

Body:
So basically I'm trying to add a character in the middle of a string. Normally in something like Python, this would be pretty straightforward, but I'm really not sure how to achieve this in C++. What I'm trying to achieve is something like this:

void converter(){
    converted = ":regional_indicator_" + character + ":";

}

So basically, I'm trying to add the variable character of a type char in a string. Should I be storing character as a string instead?

For reference here's all of my code:

#include <iostream>

using namespace std;

string inputLine;
char character;
string converted;

void input(){
    cout << "Please input the text in which you would like to be converted" << endl;
    cin >> inputLine;
}

void converter(){
    converted = ":regional_indicator_" + character + ":";

}
int main(){
    input();
    for (int i = 0; i < inputLine.length(); i++ ){
        character = tolower(inputLine[i]);
    }
    return 0;
}

Body:
You can do it like this:

converted = ":regional_indicator_" + std::string(1, character) + ":";

This works because adding a string literal (const char *) to a string yields a string. But adding const char * and char results in pointer arithmetic. So, by constructing a std::string from "character" you end up with const char * + std::string yielding a string and then std::string + const char * again yields a string as the final result.