问:
How to Search for two separate parameters in a SQL statement in C#?
I'm trying to select movies from a database and I'm trying to make sure that the IsRented value is 0 (bit statement). The user types in the MovieID being a integer value and if the user enters a MovieId with the IsRented=1, it should throw an error.

```<code>private void AddToCartButon_Click(object sender, EventArgs e)
{
        int movieid;

        bool result = Int32.TryParse(MovieIDTextBox.Text, out movieid);

        if (result)
        {
            SQLiteCommand cmd = new SQLiteCommand("select * from Movies where IsRented=0", conn);
            conn.Open();
            SQLiteDataReader rdr = cmd.ExecuteReader();

            if (rdr.Read() == true)
            {
                using (SQLiteCommand search = new SQLiteCommand("select * from Movies where MovieID LIKE @id", conn))
                {
                    search.Parameters.AddWithValue("@id", movieid);

                    var DataTable = new DataTable();
                    var dataAdapter = new SQLiteDataAdapter(search);
                    dataAdapter.Fill(DataTable);
                    dataGridView1.DataSource = DataTable;
                }

                using (SQLiteCommand update = new SQLiteCommand("update Movies set IsRented=@rented where MovieID like @id", conn))
                {
                    update.Parameters.AddWithValue("@id", movieid);
                }
            }
        }
}
</code>```

答:
Both your SELECT queries return a set of rows, but these sets are independent.

You have to check the IsRented value of the row that you are searching:

```<code>using (var cmd = new SQLiteCommand("SELECT IsRented FROM Movies WHERE MoveID LIKE @ID", conn))
{
    cmd.Parameters.AddWithValue("@ID", movieid);
    using (var reader = cmd.ExecuteReader())
    {
        if (!reader.Read())
        {
            // movie not found
        }
        else if (reader.GetBoolean(0))
        {
            // is rented
        }
        else
        {
            // not yet rented
        }
    }
}
</code>```

Body:
I'm trying to select movies from a database and I'm trying to make sure that the IsRented value is 0 (bit statement). The user types in the MovieID being a integer value and if the user enters a MovieId with the IsRented=1, it should throw an error.

private void AddToCartButon_Click(object sender, EventArgs e)
{
        int movieid;

        bool result = Int32.TryParse(MovieIDTextBox.Text, out movieid);

        if (result)
        {
            SQLiteCommand cmd = new SQLiteCommand("select * from Movies where IsRented=0", conn);
            conn.Open();
            SQLiteDataReader rdr = cmd.ExecuteReader();

            if (rdr.Read() == true)
            {
                using (SQLiteCommand search = new SQLiteCommand("select * from Movies where MovieID LIKE @id", conn))
                {
                    search.Parameters.AddWithValue("@id", movieid);

                    var DataTable = new DataTable();
                    var dataAdapter = new SQLiteDataAdapter(search);
                    dataAdapter.Fill(DataTable);
                    dataGridView1.DataSource = DataTable;
                }

                using (SQLiteCommand update = new SQLiteCommand("update Movies set IsRented=@rented where MovieID like @id", conn))
                {
                    update.Parameters.AddWithValue("@id", movieid);
                }
            }
        }
}

Body:
Both your SELECT queries return a set of rows, but these sets are independent.

You have to check the IsRented value of the row that you are searching:

using (var cmd = new SQLiteCommand("SELECT IsRented FROM Movies WHERE MoveID LIKE @ID", conn))
{
    cmd.Parameters.AddWithValue("@ID", movieid);
    using (var reader = cmd.ExecuteReader())
    {
        if (!reader.Read())
        {
            // movie not found
        }
        else if (reader.GetBoolean(0))
        {
            // is rented
        }
        else
        {
            // not yet rented
        }
    }
}


来源: stackexchange

问:
I need to change the stroke color to a user defined color. Nothing to do with the state
I need to change the stroke color from the app.  The user is able to change the background color so I need to also let them change the stroke (outline) of the button. As its is already set in the drawable (sample below) I have not found a way to change this. Seems like all of the other questions like this just said to use the XML file.... but that doesnt let me make it dynamic.  Thank you for any help!

I need to change the stroke color to a user defined color.  Nothing to do with the state.

```<code><?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <solid android:color="#ffffffff"/>
      <stroke
                android:width="3dp"
                android:color="@color/Dim_Gray" />  <<<<--- This is what I need to change

    <padding android:left="10dp"
             android:top="10dp"
             android:right="10dp"
             android:bottom="10dp"
             />

    <corners android:bottomRightRadius="12dp" android:bottomLeftRadius="12dp"
     android:topLeftRadius="12dp" android:topRightRadius="12dp"/>

</shape>
</code>```

答: Perhaps they are referring to Color State Lists which allows you to change the color based on whether the button was pressed/focused/enabled/etc</p>

ContentLicense: CC BY-SA 2.5

Body:
I need to change the stroke color from the app.  The user is able to change the background color so I need to also let them change the stroke (outline) of the button. As its is already set in the drawable (sample below) I have not found a way to change this. Seems like all of the other questions like this just said to use the XML file.... but that doesnt let me make it dynamic.  Thank you for any help!

I need to change the stroke color to a user defined color.  Nothing to do with the state.

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <solid android:color="#ffffffff"/>
      <stroke
                android:width="3dp"
                android:color="@color/Dim_Gray" />  <<<<--- This is what I need to change

    <padding android:left="10dp"
             android:top="10dp"
             android:right="10dp"
             android:bottom="10dp"
             />

    <corners android:bottomRightRadius="12dp" android:bottomLeftRadius="12dp"
     android:topLeftRadius="12dp" android:topRightRadius="12dp"/>

</shape>


问:
No Items in RecyclerView after adding item in sqlite
I am trying to add a name in sqlite and as soon as data is inserted in sqlite, i am updating the recyclerview. Following is my code

```<code>public class DbContract {
    public static final int SYNC_STATUS_OK=0;
    public static final int SYNC_STATUS_FAILED=1;
    public static final String DATABASE_NAME="contactdb";
    public static final String TABLE_NAME="contactinfo";
    public static final String NAME="name";
    public static final String SYNC_STATUS="syncstatus";
}

public class DbHelper extends SQLiteOpenHelper {
    public static final int DATABASE_VERSION=1;
    public static final String CREATE_TABLE="create table "+DbContract.TABLE_NAME+" (id integer primary key autoincrement, "+DbContract.NAME+" text,"+
            DbContract.SYNC_STATUS+" integer);";
    public static final String DROP_TABLE="drop table if exists "+DbContract.TABLE_NAME;

    public DbHelper(Context context) {
        super(context, DbContract.DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
            sqLiteDatabase.execSQL(CREATE_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        sqLiteDatabase.execSQL(DROP_TABLE);
        onCreate(sqLiteDatabase);
    }

    public void saveToLocalDatabase(String name,int syncstatus,SQLiteDatabase sqLiteDatabase){
        ContentValues contentValues=new ContentValues();
        contentValues.put(DbContract.NAME,name);
        contentValues.put(DbContract.SYNC_STATUS,syncstatus);
        sqLiteDatabase.insert(DbContract.TABLE_NAME,null,contentValues);
    }

    public Cursor readFromLocalDatabase(SQLiteDatabase sqLiteDatabase){
        String[] projection={DbContract.NAME,DbContract.SYNC_STATUS};
      //  Log.i("frff", "readFromLocalDatabase: "+projection.toString());
        return (sqLiteDatabase.query(DbContract.TABLE_NAME,projection,null,null,null,null,null));
    }

    public void updateLocalDatabase(String name, int syncstatus,SQLiteDatabase sqLiteDatabase){
        ContentValues contentValues=new ContentValues();
        contentValues.put(DbContract.SYNC_STATUS,syncstatus);
        String selection = DbContract.NAME+" LIKE ? ";
        String[] selection_args={name};
        sqLiteDatabase.update(DbContract.TABLE_NAME,contentValues,selection,selection_args);
    }
}

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private EditText editText;
    private Button button;
    private ArrayList<Contact> arrayList;
    private RecyclerAdapter recyclerAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView = findViewById(R.id.recyclerview);
        editText = findViewById(R.id.et);
        button = findViewById(R.id.button);
        arrayList = new ArrayList<>();
        recyclerAdapter = new RecyclerAdapter(arrayList);
        recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(recyclerAdapter);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String name = editText.getText().toString();
                saveToLocalStorage(name);
                editText.setText("");
            }
        });
    }

    public void submitName(View view) {

    }

    public boolean checkNetworkConnection() {
        ConnectivityManager connectivityManager = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        return (networkInfo != null && networkInfo.isConnected());
    }

    private void readFromLocalStorage() {
        arrayList.clear();
        DbHelper dbHelper = new DbHelper(this);
        SQLiteDatabase sqLiteDatabase = dbHelper.getReadableDatabase();
        Cursor cursor = dbHelper.readFromLocalDatabase(sqLiteDatabase);
        while (cursor.moveToNext()) {
            String name = cursor.getString(cursor.getColumnIndex(DbContract.NAME));
            int sync_status = cursor.getInt(cursor.getColumnIndex(DbContract.SYNC_STATUS));
            arrayList.add(new Contact(name, sync_status));

        }
        recyclerAdapter.notifyDataSetChanged();
        cursor.close();
        dbHelper.close();
    }

    private void saveToLocalStorage(String name) {
        DbHelper dbHelper = new DbHelper(this);
        SQLiteDatabase sqLiteDatabase = dbHelper.getWritableDatabase();
        if (checkNetworkConnection()) {

        } else {
            dbHelper.saveToLocalDatabase(name, DbContract.SYNC_STATUS_FAILED, sqLiteDatabase);
        }
        readFromLocalStorage();
        dbHelper.close();
    }
}
</code>```

Whenever an item is added through edittext and button is cliked,  no item can be seen in my recyclerview . I am not getting any error in my logcat and neither does the app crashes. Any help would be  greatly appreciated.

答:
why are you checking internet connection would you check that?
i think i notice that in your code compiler check connection and compile if condition and not make any entry to database please check that once.</p>

ContentLicense: CC BY-SA 3.0

Body:
I am trying to add a name in sqlite and as soon as data is inserted in sqlite, i am updating the recyclerview. Following is my code

public class DbContract {
    public static final int SYNC_STATUS_OK=0;
    public static final int SYNC_STATUS_FAILED=1;
    public static final String DATABASE_NAME="contactdb";
    public static final String TABLE_NAME="contactinfo";
    public static final String NAME="name";
    public static final String SYNC_STATUS="syncstatus";
}

public class DbHelper extends SQLiteOpenHelper {
    public static final int DATABASE_VERSION=1;
    public static final String CREATE_TABLE="create table "+DbContract.TABLE_NAME+" (id integer primary key autoincrement, "+DbContract.NAME+" text,"+
            DbContract.SYNC_STATUS+" integer);";
    public static final String DROP_TABLE="drop table if exists "+DbContract.TABLE_NAME;

    public DbHelper(Context context) {
        super(context, DbContract.DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
            sqLiteDatabase.execSQL(CREATE_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        sqLiteDatabase.execSQL(DROP_TABLE);
        onCreate(sqLiteDatabase);
    }

    public void saveToLocalDatabase(String name,int syncstatus,SQLiteDatabase sqLiteDatabase){
        ContentValues contentValues=new ContentValues();
        contentValues.put(DbContract.NAME,name);
        contentValues.put(DbContract.SYNC_STATUS,syncstatus);
        sqLiteDatabase.insert(DbContract.TABLE_NAME,null,contentValues);
    }

    public Cursor readFromLocalDatabase(SQLiteDatabase sqLiteDatabase){
        String[] projection={DbContract.NAME,DbContract.SYNC_STATUS};
      //  Log.i("frff", "readFromLocalDatabase: "+projection.toString());
        return (sqLiteDatabase.query(DbContract.TABLE_NAME,projection,null,null,null,null,null));
    }

    public void updateLocalDatabase(String name, int syncstatus,SQLiteDatabase sqLiteDatabase){
        ContentValues contentValues=new ContentValues();
        contentValues.put(DbContract.SYNC_STATUS,syncstatus);
        String selection = DbContract.NAME+" LIKE ? ";
        String[] selection_args={name};
        sqLiteDatabase.update(DbContract.TABLE_NAME,contentValues,selection,selection_args);
    }
}

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private EditText editText;
    private Button button;
    private ArrayList<Contact> arrayList;
    private RecyclerAdapter recyclerAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView = findViewById(R.id.recyclerview);
        editText = findViewById(R.id.et);
        button = findViewById(R.id.button);
        arrayList = new ArrayList<>();
        recyclerAdapter = new RecyclerAdapter(arrayList);
        recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(recyclerAdapter);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String name = editText.getText().toString();
                saveToLocalStorage(name);
                editText.setText("");
            }
        });
    }

    public void submitName(View view) {

    }

    public boolean checkNetworkConnection() {
        ConnectivityManager connectivityManager = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        return (networkInfo != null && networkInfo.isConnected());
    }

    private void readFromLocalStorage() {
        arrayList.clear();
        DbHelper dbHelper = new DbHelper(this);
        SQLiteDatabase sqLiteDatabase = dbHelper.getReadableDatabase();
        Cursor cursor = dbHelper.readFromLocalDatabase(sqLiteDatabase);
        while (cursor.moveToNext()) {
            String name = cursor.getString(cursor.getColumnIndex(DbContract.NAME));
            int sync_status = cursor.getInt(cursor.getColumnIndex(DbContract.SYNC_STATUS));
            arrayList.add(new Contact(name, sync_status));

        }
        recyclerAdapter.notifyDataSetChanged();
        cursor.close();
        dbHelper.close();
    }

    private void saveToLocalStorage(String name) {
        DbHelper dbHelper = new DbHelper(this);
        SQLiteDatabase sqLiteDatabase = dbHelper.getWritableDatabase();
        if (checkNetworkConnection()) {

        } else {
            dbHelper.saveToLocalDatabase(name, DbContract.SYNC_STATUS_FAILED, sqLiteDatabase);
        }
        readFromLocalStorage();
        dbHelper.close();
    }
}

Whenever an item is added through edittext and button is cliked,  no item can be seen in my recyclerview . I am not getting any error in my logcat and neither does the app crashes. Any help would be  greatly appreciated.


问:
Angular 4 Cannot read property 'push' of undefined
```<code>export interface IComments{
    comments: string;
}

export interface IReport {
   reportdesc: string;
   comnts: [IComments]
}

export interface IRecord{
   rdesc: string;
   reportcomments: [IReport]
}

In template I get a single value of IRecord using comment
<div>
<input [(ngModel)]="record.rdesc" name="rdesc">
<table>
<thead *ngFor="let d of record.reportcomments">
   <tr>
     <td>{{d.reportdesc}}</td>
  </tr>
  <tr *ngFor="let a of d.comnts">
    <td>{{a.comments}}</td>
   </tr>
</thead>
</table>
</code>```

In component I am trying to push an empty row like this

```<code>record=IRecord[]=[];

addRow(){
   this.record.reportcomments.push({
    rdes:'',
    comnts: {
         comments: ''
});
</code>```

when I call addRow() from template to push the empty row i get error

```<code>Error: TypeError: cannot read property 'push' if undefined.
</code>```

Please let me know how to fix my approach so I can add empty row.
I already checked the previous similar questions without any luck.
Thank

答:
```<code>record=IRecord[]=[];
record.reportcomments = [];

addRow(){
   this.record.reportcomments.push({
    rdes:'',
    comnts: {
         comments: ''}
});
</code>```

Defining the reportcomments as empty array wont give you error as reportcomments is undefined

```<code>record.reportcomments = [];
</code>```

and one more thing there is missing closing brace for comments which i believe you forget to add while copy pasting the code, please check this line comments: ''}

Body:
export interface IComments{
    comments: string;
}

export interface IReport {
   reportdesc: string;
   comnts: [IComments]
}

export interface IRecord{
   rdesc: string;
   reportcomments: [IReport]
}

In template I get a single value of IRecord using comment

<input [(ngModel)]="record.rdesc" name="rdesc">

     {{d.reportdesc}}

    {{a.comments}}

In component I am trying to push an empty row like this

record=IRecord[]=[];

addRow(){
   this.record.reportcomments.push({
    rdes:'',
    comnts: {
         comments: ''
});

when I call addRow() from template to push the empty row i get error

Error: TypeError: cannot read property 'push' if undefined.

Please let me know how to fix my approach so I can add empty row.
I already checked the previous similar questions without any luck.
Thank

Body:
record=IRecord[]=[];
record.reportcomments = [];

addRow(){
   this.record.reportcomments.push({
    rdes:'',
    comnts: {
         comments: ''}
});

Defining the reportcomments as empty array wont give you error as reportcomments is undefined

record.reportcomments = [];

and one more thing there is missing closing brace for comments which i believe you forget to add while copy pasting the code, please check this line comments: ''}


问:
Inserting values into list
I am trying to insert values in a list which is part of while loop, instead of inserting the last value is replacing the one before, so the list will always have only one value!, I am trying to add the values not replacing them, here is my code:

```<code>while X != 1:
    resultList = [];
    #extList = []
    count += 1
    if X % 2:
        X = 3 * X + 1
    elif not X % 2:
        X = X // 2 #important to use double slash to have a integer division
    print(X)
    resultList.insert(count-1, X)
    #print("the resultList is " + str(resultList))

    #extList.extend(resultList)

print("The inputValue "+str(originalValue)+" took "+str(count)+" calculations to reach 1")
print (resultList)
</code>```

any help is appreciated

答:
The problem is here:

```<code>while X != 1:
    resultList = [];
    #etc
</code>```

You are re-creating the list with every iteration of the loop. Hence, it will only have one value at the end, the one given by the only insert in the final iteration.

Taking the assignment out of the loop like so:

```<code>resultList = [];
while X != 1:
    #etc
</code>```

..fixes the problem.

An additional note, what you have done here is unnecessary:

```<code>    elif not X % 2:
    X = X // 2
</code>```

You needn't repeat and invert your original condition. You can simply make it an else.

```<code>if X % 2:
    X = 3 * X + 1
else:
    X = X // 2
</code>```

Title: Inserting values into list

Body:
I am trying to insert values in a list which is part of while loop, instead of inserting the last value is replacing the one before, so the list will always have only one value!, I am trying to add the values not replacing them, here is my code:

while X != 1:
    resultList = [];
    #extList = []
    count += 1
    if X % 2:
        X = 3 * X + 1
    elif not X % 2:
        X = X // 2 #important to use double slash to have a integer division
    print(X)
    resultList.insert(count-1, X)
    #print("the resultList is " + str(resultList))

    #extList.extend(resultList)

print("The inputValue "+str(originalValue)+" took "+str(count)+" calculations to reach 1")
print (resultList)

any help is appreciated

Body:
The problem is here:

while X != 1:
    resultList = [];
    #etc

You are re-creating the list with every iteration of the loop. Hence, it will only have one value at the end, the one given by the only insert in the final iteration.

Taking the assignment out of the loop like so:

resultList = [];
while X != 1:
    #etc

..fixes the problem.

An additional note, what you have done here is unnecessary:

    elif not X % 2:
    X = X // 2

You needn't repeat and invert your original condition. You can simply make it an else.

if X % 2:
    X = 3 * X + 1
else:
    X = X // 2


答:
On each iteration of while loop you creates new instance of resultList list.

```<code>while X != 1:
    resultList = [];
...
</code>```

should be replaced with

```<code>resultList = [];
while X != 1:
    ...
</code>```

And to add new element to the end of list you could use append method. Like

```<code>resultList = [];
while X != 1:
    if X % 2:
        X = 3 * X + 1
    else:
        X = X // 2 #important to use double slash to have a integer division
    print(X)
    resultList.append(X)
</code>```

Title: Inserting values into list

Body:
On each iteration of while loop you creates new instance of resultList list.

while X != 1:
    resultList = [];
...

should be replaced with

resultList = [];
while X != 1:
    ...

And to add new element to the end of list you could use append method. Like

resultList = [];
while X != 1:
    if X % 2:
        X = 3 * X + 1
    else:
        X = X // 2 #important to use double slash to have a integer division
    print(X)
    resultList.append(X)


问:
How do I run a copied project in Node.js
https://github.com/gleitz/mahjong

I want to run this app on my windows,
the directions say:
-Install dependencies with npm update
-Start the application with node app.js

it's sound easy so I try myself.

1.Fist of all , I install node.js on it's official website (https://nodejs.org/en/)
I　download the 8.9.3 version.

after installing node.js
2.open the command line and go to the project path.

3.then I input the command npm update.
it works,and the node_modules folder is created.But there are some warn message

4.finally input the command node app.js... it's not work with many error message

following is wrong message

I wonder know how should I do.Is any thing I didn't installed?

Please help me.I really want to research this mahjong project.

答:
Update: If you just want to try it online and not run it locally they've hosted a version on the web: http://gleitzman.com/apps/mahjong.

It's not your fault.

What you did was correct, but the project documentation needs to be updated. It's not a turn-key solution and you'll need to figure a few things out to get it working.

The error message is says it wants a mongo db instance, but you don't have one running. Try the mongodb home page or google for instructions. If you have docker it is pretty easy: docker run -it -p 27017:27017 mongo.

Even after spinning up mongodb I wasn't able to get the app to work locally. You could try contacting the repo maintainer for assistance. They may be happy to help given you've shown interest in their project.

Good Luck!


问:
ggplot2 bar plot does not display labels as defined in scale_x_discrete()
My dataset is the following:

```<code> Index  Feature scaled_Gain sign_Correlation
    1   a   1.00000000  1
    2   b   0.60999674  1
    3   c   0.54824913  1
    4   d   0.11134079  1
    5   e   0.06530486  1
    6   f   0.06470836  1
    7   g   0.06263247  1
    8   h   0.04166633  1
    9   i   0.03242897  -1
    10  j   0.02913138  1
</code>```

My code is the following:

```<code>ggplot(data = plot_data) +
geom_bar(aes(x = Index, y = scaled_Gain, fill = sign_Correlation), stat = "identity", alpha = 0.5) +
theme_economist() + ggtitle("Scaled Gain")  + scale_x_discrete(labels = plot_data$Feature)
</code>```

The plot is the following:

My question is: Why the labels do not appear in the x-axis?

答:
Try the following:

```<code>library(ggplot2)

ggplot(df, aes(Feature, scaled_Gain, fill = factor(sign_Correlation))) +
  geom_bar(stat = "identity", alpha = 0.5) +
  ggtitle("Scaled Gain") +
  labs(fill = "Sign Correlation") +
  ggthemes::theme_economist()
</code>```

I think the only problem here is that you're using aes(Index, scaled_Gain) instead of aes(Feature, scaled_Gain).

Body:
My dataset is the following:

 Index  Feature scaled_Gain sign_Correlation
    1   a   1.00000000  1
    2   b   0.60999674  1
    3   c   0.54824913  1
    4   d   0.11134079  1
    5   e   0.06530486  1
    6   f   0.06470836  1
    7   g   0.06263247  1
    8   h   0.04166633  1
    9   i   0.03242897  -1
    10  j   0.02913138  1

My code is the following:

ggplot(data = plot_data) +
geom_bar(aes(x = Index, y = scaled_Gain, fill = sign_Correlation), stat = "identity", alpha = 0.5) +
theme_economist() + ggtitle("Scaled Gain")  + scale_x_discrete(labels = plot_data$Feature)

The plot is the following:

My question is: Why the labels do not appear in the x-axis?

Body:
Try the following:

library(ggplot2)

ggplot(df, aes(Feature, scaled_Gain, fill = factor(sign_Correlation))) +
  geom_bar(stat = "identity", alpha = 0.5) +
  ggtitle("Scaled Gain") +
  labs(fill = "Sign Correlation") +
  ggthemes::theme_economist()

I think the only problem here is that you're using aes(Index, scaled_Gain) instead of aes(Feature, scaled_Gain).


问:
PHP url recognition
How can you check if text typed in from a user is an url?

Lets say I want to check if the text is a url and then check if the string has "youtube.com" in it.  Afterwards, I want to get the portion of the link which is of interest for me between the substrings "watch?v=" and any "&" parameters if they do exist.

答:
parse_url() is probably a good choice here.  If you get a bad URL, the function will return false.  Otherwise, it will break the URL up into its component pieces and you can use the ones you need.

Example:

```<code>$urlParts = parse_url('http://www.youtube.com/watch?v=MX0D4oZwCsA');
if ($urlParts == false) echo "Bad URL";
else echo "Param string is ".$urlParts['query'];
</code>```

Outputs:

```<code>Param string is v=MX0D4oZwCsA
</code>```

You could split the query portion as needed using explode() for specific parameters.

Edit: Keep in mind that parse_url() tries as hard as possible to parse the string it is given, so bad URLs will often succeed, although the resulting data array will be very odd.  It's obviously up to you how definitive you want your validation to be and what exactly you require out of your user input.

Title: PHP url recognition

Body:
parse_url() is probably a good choice here.  If you get a bad URL, the function will return false.  Otherwise, it will break the URL up into its component pieces and you can use the ones you need.

Example:

$urlParts = parse_url('http://www.youtube.com/watch?v=MX0D4oZwCsA');
if ($urlParts == false) echo "Bad URL";
else echo "Param string is ".$urlParts['query'];

Outputs:

Param string is v=MX0D4oZwCsA

You could split the query portion as needed using explode() for specific parameters.

Edit: Keep in mind that parse_url() tries as hard as possible to parse the string it is given, so bad URLs will often succeed, although the resulting data array will be very odd.  It's obviously up to you how definitive you want your validation to be and what exactly you require out of your user input.


问:
C# Windows form algorithm calculation
I'm new to c# development. I have a label on the form that shows the following sequence 1,1,1,3,5,9 and a button. When the button is clicked I want it to add the sequence of numbers to the label. For example :
I know how the the above sequence works 1+1+1=3,3+1+1=5,5+3+1=9 ,so it calculates the previous 3 numbers to add to the sequence.
What I'm trying to achieve is when the button is clicked each time it must show the next numbers that come in ex: after 9, will be 17 because 3+5+9=17 And so on... It must go up every time it's clicked .your help will be highly appreciated. </p>

答:
I believe the algorithm you are looking to do is create a List<int> to contain the ints that are going to be used on the label.

```<code>List<int> numbers = new List<int>();
</code>```

Then you are trying to .Add the first 6 starting numbers into the list like so:

```<code>numbers.Add(1);
numbers.Add(1);
numbers.Add(1);
numbers.Add(3);
numbers.Add(5);
numbers.Add(9);
</code>```

Once the user clicks the button, change the original label's text information to also have the result of adding the last three elements of int within the List<int>.

This can be done by using .Count to get the length/size of the List<int> in the following fashion:

```<code>int x = numbers[numbers.Count - 1];  //Last number/element in List
int y = numbers[numbers.Count - 2];  //Second to last
int z = numbers[numbers.Count - 3];  //Third to last
int result = x + y + z;  //sum of   last number   plus   second to last number plus   third to last   number
</code>```

Don't forget to .Add the result of adding the last three elements to the end of the List<int>.

```<code>numbers.Add(result);
</code>```

Once you have the result added, you can set the label's .Text value to the joining of a string in the following way:

```<code>numbersLabel.Text = string.Join(", ", numbers);
</code>```

A sample demonstration of a class that contains a button, and a label that accomplishes this algorithm is below.

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class LabelAlgorithm : Form
    {
        public List<int> numbers = new List<int>();

        public LabelAlgorithm()
        {
            numbers.Add(1);
            numbers.Add(1);
            numbers.Add(1);
            numbers.Add(3);
            numbers.Add(5);
            numbers.Add(9);

            InitializeComponent();
            numbersLabel.Text = string.Join(", ", numbers);
        }

        private void SubmissionButton_Click(object sender, EventArgs e)
        {
            int x = numbers[numbers.Count - 1];
            int y = numbers[numbers.Count - 2];
            int z = numbers[numbers.Count - 3];

            int result = x + y + z;

            numbers.Add(result);

            numbersLabel.Text = string.Join(", ", numbers);

        }
    }
}
</code>```

Output to Label:

```<code>1, 3, 5, 9, 17, 31, 57, 105, 193, 355, 653, 1201, 2209, 4063...
</code>```

Title: C# Windows form algorithm calculation

Body:
I believe the algorithm you are looking to do is create a List<int> to contain the ints that are going to be used on the label.

List<int> numbers = new List<int>();

Then you are trying to .Add the first 6 starting numbers into the list like so:

numbers.Add(1);
numbers.Add(1);
numbers.Add(1);
numbers.Add(3);
numbers.Add(5);
numbers.Add(9);

Once the user clicks the button, change the original label's text information to also have the result of adding the last three elements of int within the List<int>.

This can be done by using .Count to get the length/size of the List<int> in the following fashion:

int x = numbers[numbers.Count - 1];  //Last number/element in List
int y = numbers[numbers.Count - 2];  //Second to last
int z = numbers[numbers.Count - 3];  //Third to last
int result = x + y + z;  //sum of   last number   plus   second to last number plus   third to last   number

Don't forget to .Add the result of adding the last three elements to the end of the List<int>.

numbers.Add(result);

Once you have the result added, you can set the label's .Text value to the joining of a string in the following way:

numbersLabel.Text = string.Join(", ", numbers);

A sample demonstration of a class that contains a button, and a label that accomplishes this algorithm is below.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class LabelAlgorithm : Form
    {
        public List<int> numbers = new List<int>();

        public LabelAlgorithm()
        {
            numbers.Add(1);
            numbers.Add(1);
            numbers.Add(1);
            numbers.Add(3);
            numbers.Add(5);
            numbers.Add(9);

            InitializeComponent();
            numbersLabel.Text = string.Join(", ", numbers);
        }

        private void SubmissionButton_Click(object sender, EventArgs e)
        {
            int x = numbers[numbers.Count - 1];
            int y = numbers[numbers.Count - 2];
            int z = numbers[numbers.Count - 3];

            int result = x + y + z;

            numbers.Add(result);

            numbersLabel.Text = string.Join(", ", numbers);

        }
    }
}

Output to Label:

1, 3, 5, 9, 17, 31, 57, 105, 193, 355, 653, 1201, 2209, 4063...


问:
Loop through dictionary keys to get values based on input
1) In my program I start with prompting a user for input.

2) I would then like to loop through the users input to get all the characters in that string, query each character individually against the dictionaries keys.

3) If a character from the input matches a key in the dictionary, I want that key's value returned.

4) This needs to be repeated for each character and the result should print those values returned in a string

To try and explain further, here is my dictionary:

```<code>dataDict = {
"a":"1",
"b":"2",
"c":"3",
}
</code>```

For example:

If my input is abc, my result should be 123

If my input is cba, my result should be 321

and so on...

So far, this works if the string is only one character using the below code.
If i enter two characters, it just returns nothing.

```<code>dataInput=input("Enter stuff: ")

for key,value in dataDict.items():
    if dataInput == key:
    print(value)
</code>```

How can I acheive the results i'm after?

答:
You shouldn't be looping over the dict to find the matching keys, that's very inefficient. A dict is designed to do fast lookups: you give it the key and it gives you the value. Eg, dataDict["a"] results in "1".

Also, as Tim Pietzcker mentions, doing if dataInput == key will only work if dataInput consists of a single letter, because it compares the whole dataInput string to key.

Here's a simple way to do the desired conversion. We do the lookups in a list comprehension, which creates a list of the converted values, and then we pass that list to .join to create a string. (I've changed the names of your variables to conform with the PEP-008 style guide).

```<code>data_dict = {
    "a": "1",
    "b": "2",
    "c": "3",
}

data_input = "aabbccba"

s = ''.join([data_dict[c] for c in data_input])
print(s)
</code>```

output

```<code>11223321
</code>```

However, that's not safe: it will fail with KeyError if data_input contains a char that's not in the dictionary. Here's a better way: it adds an empty string if it gets a bad char.

```<code>data_input = "aaxbbcycbaz"
s = ''.join([data_dict.get(c, '') for c in data_input])
print(s)
</code>```

output

```<code>11223321
</code>```

Alternatively, we could convert bad data to some special value, eg 0.

```<code>data_input = "aaxbbcycbaz"
s = ''.join([data_dict.get(c, '0') for c in data_input])
print(s)
</code>```

output

```<code>11022303210
</code>```

Just for fun, here's a "functional" version. Guido would probably not approve of this one. :)

```<code>data_input = "aaxbbcycbaz"
print(''.join(filter(None, map(data_dict.get, data_input))))
11223321
</code>```

Body:
1) In my program I start with prompting a user for input.

2) I would then like to loop through the users input to get all the characters in that string, query each character individually against the dictionaries keys.

3) If a character from the input matches a key in the dictionary, I want that key's value returned.

4) This needs to be repeated for each character and the result should print those values returned in a string

To try and explain further, here is my dictionary:

dataDict = {
"a":"1",
"b":"2",
"c":"3",
}

For example:

If my input is abc, my result should be 123

If my input is cba, my result should be 321

and so on...

So far, this works if the string is only one character using the below code.
If i enter two characters, it just returns nothing.

dataInput=input("Enter stuff: ")

for key,value in dataDict.items():
    if dataInput == key:
    print(value)

How can I acheive the results i'm after?

Body:
You shouldn't be looping over the dict to find the matching keys, that's very inefficient. A dict is designed to do fast lookups: you give it the key and it gives you the value. Eg, dataDict["a"] results in "1".

Also, as Tim Pietzcker mentions, doing if dataInput == key will only work if dataInput consists of a single letter, because it compares the whole dataInput string to key.

Here's a simple way to do the desired conversion. We do the lookups in a list comprehension, which creates a list of the converted values, and then we pass that list to .join to create a string. (I've changed the names of your variables to conform with the PEP-008 style guide).

data_dict = {
    "a": "1",
    "b": "2",
    "c": "3",
}

data_input = "aabbccba"

s = ''.join([data_dict[c] for c in data_input])
print(s)

output

11223321

However, that's not safe: it will fail with KeyError if data_input contains a char that's not in the dictionary. Here's a better way: it adds an empty string if it gets a bad char.

data_input = "aaxbbcycbaz"
s = ''.join([data_dict.get(c, '') for c in data_input])
print(s)

output

11223321

Alternatively, we could convert bad data to some special value, eg 0.

data_input = "aaxbbcycbaz"
s = ''.join([data_dict.get(c, '0') for c in data_input])
print(s)

output

11022303210

Just for fun, here's a "functional" version. Guido would probably not approve of this one. :)

data_input = "aaxbbcycbaz"
print(''.join(filter(None, map(data_dict.get, data_input))))
11223321


问:
What is the purpose of the pause x86 instruction and the loop in the GetSystemTimeAsFileTime function disassembly?
I was researching the workings of the GetSystemTimeAsFileTime function to see how optimized it is internally and stumbled upon this seemingly simple set of instructions (in my Windows 10 system):

So as you see that function simply reads from 3 global variables: 2 are the system time (or FILETIME) and then compares the lower DWORD to the 3rd variable and if they are the same it loops around until they are not.

As far as I know the pause instruction is needed to halt the CPU for a short period of time to save power. Is that why it's there?

Also, if that is the case, why are they not using a critical section to prevent thread synchronization issues with those 3 global variables?

And lastly, what's the purpose of that loop?

EDIT: Interesting find. I looked into the x64 implementation and it is way more simple. It's just this:

答:
x64 implementation reads 64 bit values atomically (if correctly aligned).

Classic x86 instructions can't do this.

Lets assume we have values (these are example values, not real):

```<code>low part:  0xffffffff
high part: 0x00000001
</code>```

Because reading of two 32 bit values can be split by timer interrupt, there is small possibility of reading partly old and partly new value. If after interrupt we have:

```<code>low part:  0x00001111
high part: 0x00000002
</code>```

We could end with wrong values:

```<code>low part:  0x00001111
high part: 0x00000001 <- WRONG
</code>```

It looks that timer handler writes high part in two memory locations. This allows user code to detect overflow from low part to high part and initiate rereading of time. Thanks to this code there is no need for switch into kernel mode, time reading can be done in user mode.

It could be done with more advanced SSE instructions, but probably there is not point in changing working code.

PAUSE—Spin Loop Hint Instruction
 Improves
  the performance of spin-wait loops. When execut ing a “spin-wait
  loop,” processors will suffer a severe  performance penalty when
  exiting the loop because it  detects a possible memory order
  violation. The PAUSE  instruction provides a hint to the processor
  that the code sequence is a spin-wait loop. The processor uses this
  hint  to avoid the memory order violation in most situations, which
  greatly improves processor performance. For this  reason, it is
  recommended that a PAUSE inst ruction be placed in all spin-wait
  loops. An additional function of the PAUSE instruction is to re duce
  the power consumed by a processor while executing a  spin loop.

Intel® 64 and IA-32 Architectures
Software Developer’s Manual

Body:
x64 implementation reads 64 bit values atomically (if correctly aligned).

Classic x86 instructions can't do this.

Lets assume we have values (these are example values, not real):

low part:  0xffffffff
high part: 0x00000001

Because reading of two 32 bit values can be split by timer interrupt, there is small possibility of reading partly old and partly new value. If after interrupt we have:

low part:  0x00001111
high part: 0x00000002

We could end with wrong values:

low part:  0x00001111
high part: 0x00000001 <- WRONG

It looks that timer handler writes high part in two memory locations. This allows user code to detect overflow from low part to high part and initiate rereading of time. Thanks to this code there is no need for switch into kernel mode, time reading can be done in user mode.

It could be done with more advanced SSE instructions, but probably there is not point in changing working code.

PAUSE—Spin Loop Hint Instruction
 Improves
  the performance of spin-wait loops. When execut ing a “spin-wait
  loop,” processors will suffer a severe  performance penalty when
  exiting the loop because it  detects a possible memory order
  violation. The PAUSE  instruction provides a hint to the processor
  that the code sequence is a spin-wait loop. The processor uses this
  hint  to avoid the memory order violation in most situations, which
  greatly improves processor performance. For this  reason, it is
  recommended that a PAUSE inst ruction be placed in all spin-wait
  loops. An additional function of the PAUSE instruction is to re duce
  the power consumed by a processor while executing a  spin loop.

Intel® 64 and IA-32 Architectures
Software Developer’s Manual


问:
MediaPlayer: audio file on /res/raw detected as an Integer
I want to play an audio file when a Button clicked. But my code generate error code that says:

```<code>Cannot resolve method'create(context, int)'
</code>```

So, my audio file is detected as an integer.

this is my fragment code:

```<code>package com.example.suha.belajarhurufhijaiyah;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;

/**
* A simple {@link Fragment} subclass.
*/
public class Hijaiyah extends Fragment implements View.OnClickListener {

ImageButton alif;
View view;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    // Inflate the layout for this fragment
    view = inflater.inflate(R.layout.fragment_hijaiyah, container, false);
    alif = view.findViewById(R.id.alif_sound);

    alif.setOnClickListener(this);
    return view;
}

@Override
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.alif_sound:
            MediaPlayer mp = MediaPlayer.create(this, R.raw.sound_alif);
            mp.start();
    }
}
}
</code>```

That R.raw.sound_alif generate the error..

And it's my resource hier

答:
you are trying to create MediaPlayer in Fragment use getActivity() or getContext() instead of this so use below code

```<code>   @Override
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.alif_sound:
            MediaPlayer mp = MediaPlayer.create(getActivity(), R.raw.sound_alif);
            mp.start();
    }
</code>```

Body:
I want to play an audio file when a Button clicked. But my code generate error code that says:

Cannot resolve method'create(context, int)'

So, my audio file is detected as an integer.

this is my fragment code:

package com.example.suha.belajarhurufhijaiyah;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;

/**
* A simple {@link Fragment} subclass.
*/
public class Hijaiyah extends Fragment implements View.OnClickListener {

ImageButton alif;
View view;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    // Inflate the layout for this fragment
    view = inflater.inflate(R.layout.fragment_hijaiyah, container, false);
    alif = view.findViewById(R.id.alif_sound);

    alif.setOnClickListener(this);
    return view;
}

@Override
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.alif_sound:
            MediaPlayer mp = MediaPlayer.create(this, R.raw.sound_alif);
            mp.start();
    }
}
}

That R.raw.sound_alif generate the error..

And it's my resource hier

Body:
you are trying to create MediaPlayer in Fragment use getActivity() or getContext() instead of this so use below code

   @Override
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.alif_sound:
            MediaPlayer mp = MediaPlayer.create(getActivity(), R.raw.sound_alif);
            mp.start();
    }


问:
How do I add class to first paragraph and span to first letter
Example

```<code><p>Lorem ipsum dolor sit amet</p>
<p>Morbi elementum odio vel tortor adipiscing vel tempor risus ullamcorper.</p>
</code>```

I want add class for first paragraph and add span class to the first letter

```<code><p class="first-paragraph"><span class="first-letter">L</span>orem ipsum dolor sit amet</p>
</code>```

Let me know how can be with PHP

答:
You can make use of pure CSS3:

```<code>p:first-of-type {
    color: red;
}

p:first-of-type::first-letter {
    color: blue;
    font-size: x-large;
}
</code>```

fiddle here: http://jsfiddle.net/everton/vpcey/

Body:
Example

Lorem ipsum dolor sit amet

Morbi elementum odio vel tortor adipiscing vel tempor risus ullamcorper.

I want add class for first paragraph and add span class to the first letter

Lorem ipsum dolor sit amet

Let me know how can be with PHP

Body:
You can make use of pure CSS3:

p:first-of-type {
    color: red;
}

p:first-of-type::first-letter {
    color: blue;
    font-size: x-large;
}

fiddle here: http://jsfiddle.net/everton/vpcey/


问:
How to get a declaration for IsDebuggerPresent without including Windows.h?
This is related to How to install a DebugBreak handler? and How to get a declaration for DebugBreak without including Windows.h?. We would like to evaluate using IsDebuggerPresent() to avoid the crash when using DebugBreak() without a debugger present.

The problem we are having is, we have to include <windows.h>, and it brings in a lot of extra cruft, even with WIN32_LEAN_AND_MEAN defined. Some of the extra cruft, like min and max, breaks C++ compiles. In fact, testing our changes broke us.

Trying to do  it with a simple extern BOOL IsDebuggerPresent() requires a lot of preprocessor magic and does not match signatures on all versions of the function. Considering we like to ensure "things just work" for 15 years of OS and compilers, it seems to be a thorny issue.

Is it possible to use IsDebuggerPresent() without including <windows.h>? If so, then how do we do it?

答:
The code below is a runtime dubugger for windows that acts on the bare minimum without including windows.h itself. I know this doesn't answer the question directly but what you need to define specifically in order for your code to work is an architecture definition (preprocessor stuff), and <errhandlingapi.h>, and <windef.h>. I'm not completely sure what else so refer to my example below:

My code:

```<code>#if !defined(_68K_) && !defined(_MPPC_) && !defined(_X86_) && !defined(_IA64_) && !defined(_AMD64_) && !defined(_ARM_) && !defined(_ARM64_) && defined(_M_IX86)
#define _X86_
#if !defined(_CHPE_X86_ARM64_) && defined(_M_HYBRID)
#define _CHPE_X86_ARM64_
#endif
#endif

#if !defined(_68K_) && !defined(_MPPC_) && !defined(_X86_) && !defined(_IA64_) && !defined(_AMD64_) && !defined(_ARM_) && !defined(_ARM64_) && defined(_M_AMD64)
#define _AMD64_
#endif

#if !defined(_68K_) && !defined(_MPPC_) && !defined(_X86_) && !defined(_IA64_) && !defined(_AMD64_) && !defined(_ARM_) && !defined(_ARM64_) && defined(_M_ARM)
#define _ARM_
#endif

#if !defined(_68K_) && !defined(_MPPC_) && !defined(_X86_) && !defined(_IA64_) && !defined(_AMD64_) && !defined(_ARM_) && !defined(_ARM64_) && defined(_M_ARM64)
#define _ARM64_
#endif

#if !defined(_68K_) && !defined(_MPPC_) && !defined(_X86_) && !defined(_IA64_) && !defined(_AMD64_) && !defined(_ARM_) && !defined(_ARM64_) && defined(_M_M68K)
#define _68K_
#endif

#if !defined(_68K_) && !defined(_MPPC_) && !defined(_X86_) && !defined(_IA64_) && !defined(_AMD64_) && !defined(_ARM_) && !defined(_ARM64_) && defined(_M_MPPC)
#define _MPPC_
#endif

#if !defined(_68K_) && !defined(_MPPC_) && !defined(_X86_) && !defined(_M_IX86) && !defined(_AMD64_) && !defined(_ARM_) && !defined(_ARM64_) && defined(_M_IA64)
#if !defined(_IA64_)
#define _IA64_
#endif /* !_IA64_ */
#endif

#ifndef _MAC
#if defined(_68K_) || defined(_MPPC_)
#define _MAC
#endif
#endif
#include <string>
#include <windef.h>
#include <WinUser.h>
#include <WinNls.h>
#include <errhandlingapi.h>
#include <processthreadsapi.h>
#include <WinBase.h>

__pragma (comment(lib, "User32"));

namespace Microsoft {
void __stdcall rt_assert(const bool test, const wchar_t* FunctionName)
{
    if (test) return;

    // Retrieve the system error message for the last-error code
    unsigned __int32 ERROR_ID = GetLastError();
    void* MsgBuffer;
    LCID lcid; //language id
    GetLocaleInfoEx(L"en-US", LOCALE_RETURN_NUMBER | LOCALE_ILANGUAGE, (wchar_t*)&lcid, sizeof(lcid));

    //get error message and attach it to Msgbuffer
    FormatMessageW(
        FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL, ERROR_ID, lcid, (wchar_t*)&MsgBuffer, 0, NULL);

    //concatonate string to DisplayBuffer
    const std::wstring DisplayBuffer = (static_cast<std::wstring>(FunctionName) + L" failed with error " + std::to_wstring(ERROR_ID) + L": " + static_cast<const wchar_t*>(MsgBuffer)).c_str();

    // Display the error message and exit the process
    if (IsDebuggerPresent())
    {
        OutputDebugStringW(DisplayBuffer.c_str());
    }
    else
    {
        MessageBoxExW(NULL, DisplayBuffer.c_str(), L"Error", MB_ICONERROR | MB_OK, static_cast<unsigned __int16>(lcid));
    }
    ExitProcess(ERROR_ID);
}
}
</code>```

Body:
The code below is a runtime dubugger for windows that acts on the bare minimum without including windows.h itself. I know this doesn't answer the question directly but what you need to define specifically in order for your code to work is an architecture definition (preprocessor stuff), and <errhandlingapi.h>, and <windef.h>. I'm not completely sure what else so refer to my example below:

My code:

#if !defined(_68K_) && !defined(_MPPC_) && !defined(_X86_) && !defined(_IA64_) && !defined(_AMD64_) && !defined(_ARM_) && !defined(_ARM64_) && defined(_M_IX86)
#define _X86_
#if !defined(_CHPE_X86_ARM64_) && defined(_M_HYBRID)
#define _CHPE_X86_ARM64_
#endif
#endif

#if !defined(_68K_) && !defined(_MPPC_) && !defined(_X86_) && !defined(_IA64_) && !defined(_AMD64_) && !defined(_ARM_) && !defined(_ARM64_) && defined(_M_AMD64)
#define _AMD64_
#endif

#if !defined(_68K_) && !defined(_MPPC_) && !defined(_X86_) && !defined(_IA64_) && !defined(_AMD64_) && !defined(_ARM_) && !defined(_ARM64_) && defined(_M_ARM)
#define _ARM_
#endif

#if !defined(_68K_) && !defined(_MPPC_) && !defined(_X86_) && !defined(_IA64_) && !defined(_AMD64_) && !defined(_ARM_) && !defined(_ARM64_) && defined(_M_ARM64)
#define _ARM64_
#endif

#if !defined(_68K_) && !defined(_MPPC_) && !defined(_X86_) && !defined(_IA64_) && !defined(_AMD64_) && !defined(_ARM_) && !defined(_ARM64_) && defined(_M_M68K)
#define _68K_
#endif

#if !defined(_68K_) && !defined(_MPPC_) && !defined(_X86_) && !defined(_IA64_) && !defined(_AMD64_) && !defined(_ARM_) && !defined(_ARM64_) && defined(_M_MPPC)
#define _MPPC_
#endif

#if !defined(_68K_) && !defined(_MPPC_) && !defined(_X86_) && !defined(_M_IX86) && !defined(_AMD64_) && !defined(_ARM_) && !defined(_ARM64_) && defined(_M_IA64)
#if !defined(_IA64_)
#define _IA64_
#endif /* !_IA64_ */
#endif

#ifndef _MAC
#if defined(_68K_) || defined(_MPPC_)
#define _MAC
#endif
#endif
#include <string>
#include <windef.h>
#include <WinUser.h>
#include <WinNls.h>
#include <errhandlingapi.h>
#include <processthreadsapi.h>
#include <WinBase.h>

__pragma (comment(lib, "User32"));

namespace Microsoft {
void __stdcall rt_assert(const bool test, const wchar_t* FunctionName)
{
    if (test) return;

    // Retrieve the system error message for the last-error code
    unsigned __int32 ERROR_ID = GetLastError();
    void* MsgBuffer;
    LCID lcid; //language id
    GetLocaleInfoEx(L"en-US", LOCALE_RETURN_NUMBER | LOCALE_ILANGUAGE, (wchar_t*)&lcid, sizeof(lcid));

    //get error message and attach it to Msgbuffer
    FormatMessageW(
        FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL, ERROR_ID, lcid, (wchar_t*)&MsgBuffer, 0, NULL);

    //concatonate string to DisplayBuffer
    const std::wstring DisplayBuffer = (static_cast<std::wstring>(FunctionName) + L" failed with error " + std::to_wstring(ERROR_ID) + L": " + static_cast<const wchar_t*>(MsgBuffer)).c_str();

    // Display the error message and exit the process
    if (IsDebuggerPresent())
    {
        OutputDebugStringW(DisplayBuffer.c_str());
    }
    else
    {
        MessageBoxExW(NULL, DisplayBuffer.c_str(), L"Error", MB_ICONERROR | MB_OK, static_cast<unsigned __int16>(lcid));
    }
    ExitProcess(ERROR_ID);
}
}


问:
What is the correct way to install bootstrap and babel in webpack
I am facing difficulty in installing bootstrap in webpack, it say it requires jquery and if i include that, it says it requires popper and when i install popper it says export not supported(I am using ES6).
And also please tell me how to include bootstrap and babel in my project.

Someone please help me out..
Thank you

答:
The key is to make sure that the scripts are loaded in proper order. That would mean jquery has to be loaded by the time the bootstrap css is loaded.

For bootstrap with webpack please refer the code here.

Adding babel shouldnt be hard. You can see the required changes in this diff.


答:
All resources are represented as Integers in the R class that is not your problem the problem is the Context your passing in a Fragment change this to getActivity So change your line to:

```<code>MediaPlayer mp = MediaPlayer.create(getActivity, R.raw.sound_alif);
</code>```

Title: MediaPlayer: audio file on /res/raw detected as an Integer

Body:
All resources are represented as Integers in the R class that is not your problem the problem is the Context your passing in a Fragment change this to getActivity So change your line to:

MediaPlayer mp = MediaPlayer.create(getActivity, R.raw.sound_alif);


问:
mysqli cannot display full data
I have a table named testads and the data are as below

Link to table image

I want to make an update page where the data are select by row. I have no problem with updating the data however when the data is displayed in update page, instead of the company name Subway Malaysia, it only shows Subway. This happens to all the data with more than one word. I can't seem to find what's the problem

Here are the php code:

```<code><?php
    include('./include/connection.php');

    $ID=$_GET['no'];

    $query = "SELECT no, id_company, company_name, jobName,state, location, jobDesc, contact FROM testads where no='$ID'";

    $result = mysqli_query($link, $query) or die ("error.");

    while ($row = mysqli_fetch_array($result)){
    $id=$row['no'];
?>

<form class="form-horizontal form-label-left" method="post" action="edit_query.php<?php echo '?no='.$id; ?>">
     <div class="form-group">
         <label class="control-label col-md-3 col-sm-3 col-xs-12" for="comp-name">Company Name <span class="required"></span>
         </label>
         <div class="col-md-6 col-sm-6 col-xs-12">
              <input type="text" id="comp-name" required="required" name="cname" class="form-control col-md-7 col-xs-12" value=<?php echo $row['company_name']; ?>>
        </div>
     </div>

     <div class="form-group">
         <label class="control-label col-md-3 col-sm-3 col-xs-12" for="comp-id">Company ID <span class="required"></span>
         </label>
         <div class="col-md-6 col-sm-6 col-xs-12">
              <input type="text" id="comp-id" required="required" name="cid" class="form-control col-md-7 col-xs-12" value=<?php echo $row['id_company']; ?>>
         </div>
      </div>

      <div class="form-group">
          <label class="control-label col-md-3 col-sm-3 col-xs-12" for="job-name">Job Name <span class="required"></span>
          </label>
          <div class="col-md-6 col-sm-6 col-xs-12">
                <input type="text" id="job-name" required="required" name="jname" class="form-control col-md-7 col-xs-12" value=<?php echo $row['jobName']; ?>>
          </div>
       </div>

      <div class="form-group">
           <label class="control-label col-md-3 col-sm-3 col-xs-12" for="desc">Job Description<span class="required"></span>
           </label>
           <div class="col-md-6 col-sm-6 col-xs-12">
                <textarea id="desc" name="description" class="form-control" maxlength="2000" value=<?php echo $row['jobDesc']; ?>></textarea>
            </div>
       </div>

       <div class="form-group">
            <label class="control-label col-md-3 col-sm-3 col-xs-12" for="stt">State</label>
            <div class="col-md-6 col-sm-6 col-xs-12">
                 <select name="state" class="form-control">
                        <option value="Johor"<?php echo $row['state'] == 'Johor' ? 'selected="selected"' : '' ; ?>>Johor</option>
                        <option value="Malacca"<?php echo $row['state'] == 'Malacca' ? 'selected="selected"' : '' ; ?>>Malacca</option>
                        <option value="Pahang"<?php echo $row['state'] == 'Pahang' ? 'selected="selected"' : '' ; ?>>Pahang</option>
                        <option value="Selangor"<?php echo $row['state'] == 'Selangor' ? 'selected="selected"' : '' ; ?>>Selangor</option>
                   </select>
              </div>
       </div>

       <div class="form-group">
            <label class="control-label col-md-3 col-sm-3 col-xs-12" for="loc">Location<span class="required"></span>
            </label>
            <div class="col-md-6 col-sm-6 col-xs-12">
                 <input type="text" id="loc" required="required" name="location" class="form-control col-md-7 col-xs-12" value=<?php echo $row['location']; ?>>
             </div>
        </div>

        <div class="form-group">
             <label class="control-label col-md-3 col-sm-3 col-xs-12" for="ctc">Contact<span class="required"></span>
             </label>
             <div class="col-md-6 col-sm-6 col-xs-12">
                  <input type="text" id="ctc" required="required" name="contact" class="form-control col-md-7 col-xs-12" value=<?php echo $row['contact']; ?>>
             </div>
        </div>

        <div class="form-group">
             <div class="col-md-6 col-sm-6 col-xs-12 col-md-offset-3">
                  <button class="btn btn-success" type="submit" name="submit">Update</button>
             </div>
        </div>

 </form>
</code>```

答:
You need to quote your values:</p>

```<code><input ... value="<?php echo $row['company_name']; ?>">
</code>```

Title: mysqli cannot display full data

Body:
I have a table named testads and the data are as below

Link to table image

I want to make an update page where the data are select by row. I have no problem with updating the data however when the data is displayed in update page, instead of the company name Subway Malaysia, it only shows Subway. This happens to all the data with more than one word. I can't seem to find what's the problem

Here are the php code:

<?php
    include('./include/connection.php');

    $ID=$_GET['no'];

    $query = "SELECT no, id_company, company_name, jobName,state, location, jobDesc, contact FROM testads where no='$ID'";

    $result = mysqli_query($link, $query) or die ("error.");

    while ($row = mysqli_fetch_array($result)){
    $id=$row['no'];
?>

<form class="form-horizontal form-label-left" method="post" action="edit_query.php<?php echo '?no='.$id; ?>">

         Company Name

              <input type="text" id="comp-name" required="required" name="cname" class="form-control col-md-7 col-xs-12" value=<?php echo $row['company_name']; ?>>

         Company ID

              <input type="text" id="comp-id" required="required" name="cid" class="form-control col-md-7 col-xs-12" value=<?php echo $row['id_company']; ?>>

          Job Name

                <input type="text" id="job-name" required="required" name="jname" class="form-control col-md-7 col-xs-12" value=<?php echo $row['jobName']; ?>>

           Job Description

                <textarea id="desc" name="description" class="form-control" maxlength="2000" value=<?php echo $row['jobDesc']; ?>></textarea>

            State

                 <select name="state" class="form-control">
                        <option value="Johor"<?php echo $row['state'] == 'Johor' ? 'selected="selected"' : '' ; ?>>Johor</option>
                        <option value="Malacca"<?php echo $row['state'] == 'Malacca' ? 'selected="selected"' : '' ; ?>>Malacca</option>
                        <option value="Pahang"<?php echo $row['state'] == 'Pahang' ? 'selected="selected"' : '' ; ?>>Pahang</option>
                        <option value="Selangor"<?php echo $row['state'] == 'Selangor' ? 'selected="selected"' : '' ; ?>>Selangor</option>
                   </select>

            Location

                 <input type="text" id="loc" required="required" name="location" class="form-control col-md-7 col-xs-12" value=<?php echo $row['location']; ?>>

             Contact

                  <input type="text" id="ctc" required="required" name="contact" class="form-control col-md-7 col-xs-12" value=<?php echo $row['contact']; ?>>

                  <button class="btn btn-success" type="submit" name="submit">Update</button>

 </form>

Body:
You need to quote your values:

<input ... value="<?php echo $row['company_name']; ?>">


问:
Why does this method of Java Scanner works in code 2 and not code 1?
What is the reason?Why does the code 2 works and  code 1 is showing error?

I  first used the code 1 approach..it displayed error and then I tried adding it in a method..it worked somehow..please let me know the reason

Code 1:

```<code>import java.util.*;
class alpha /*This is not the main class btw */
{
   Scanner x=new Scanner(System.in);
   int k;flag=0;
   String s1=new String();
   s1=x.nextLine(); /* This Line Produces error */
}
</code>```

Code 2:

```<code>import java.util.*;
class alpha /*This is not the main class btw */
{
   Scanner x=new Scanner(System.in);
   int k;flag=0;
   String s1=new String();
   void input()
   {
     s1=x.nextLine(); /* Voila this works */
   }
}
</code>```

答:
Your first example doesn't run because we can't put statements  outside any method,we  can only put declarations and initializers outside a method like

int x = 5;

Hello h = new Hello;

that is the reason your first example is showing error

You should not put statements like s1=x.nextLine(); outside any method.

Body:
What is the reason?Why does the code 2 works and  code 1 is showing error?

I  first used the code 1 approach..it displayed error and then I tried adding it in a method..it worked somehow..please let me know the reason

Code 1:

import java.util.*;
class alpha /*This is not the main class btw */
{
   Scanner x=new Scanner(System.in);
   int k;flag=0;
   String s1=new String();
   s1=x.nextLine(); /* This Line Produces error */
}

Code 2:

import java.util.*;
class alpha /*This is not the main class btw */
{
   Scanner x=new Scanner(System.in);
   int k;flag=0;
   String s1=new String();
   void input()
   {
     s1=x.nextLine(); /* Voila this works */
   }
}

ContentLicense: CC BY-SA 4.0


问:
Javascript count object's key having dot notation
Trying to count the arrays inside javascript object. This response is coming back from laravel validator

```<code>  {
   "message":"The given data was invalid.",
   "errors":{
      "roomtype_id":[
         "Please select a room type"
      ],
      "price":[
         "Price cannot be empty"
      ],
      "amenities":[
         "Atleast select one amenities"
      ],
      "floor.0":[
         "Please select a floor"
      ],
      "floor.1":[
         "Please select a floor"
      ],
      "floor.2":[
         "Please select a floor"
      ],
      "floor.3":[
         "Please select a floor"
      ],
      "floor.4":[
         "Please select a floor"
      ],
      "room_number.0":[
         "Room number cannot be empty"
      ],
      "room_number.1":[
         "Room number cannot be empty"
      ],
      "room_number.2":[
         "Room number cannot be empty"
      ],
      "room_number.3":[
         "Room number cannot be empty"
      ],
      "room_number.4":[
         "Room number cannot be empty"
      ],
      "room_number.5":[
         "Room number cannot be empty"
      ],
      "room_number.6":[
         "Room number cannot be empty"
      ],
      "room_number.7":[
         "Room number cannot be empty"
      ],
      "room_number.8":[
         "Room number cannot be empty"
      ],
      "room_number.9":[
         "Room number cannot be empty"
      ],
      "room_number.10":[
         "Room number cannot be empty"
      ],
      "room_number.11":[
         "Room number cannot be empty"
      ],
      "room_number.12":[
         "Room number cannot be empty"
      ],
      "room_number.13":[
         "Room number cannot be empty"
      ],
      "room_number.14":[
         "Room number cannot be empty"
      ],
      "room_number.15":[
         "Room number cannot be empty"
      ],
      "room_number.16":[
         "Room number cannot be empty"
      ],
      "room_number.17":[
         "Room number cannot be empty"
      ],
      "room_number.18":[
         "Room number cannot be empty"
      ],
      "room_number.19":[
         "Room number cannot be empty"
      ],
      "room_number.20":[
         "Room number cannot be empty"
      ],
      "room_number.21":[
         "Room number cannot be empty"
      ],
      "room_number.22":[
         "Room number cannot be empty"
      ],
      "room_number.23":[
         "Room number cannot be empty"
      ],
      "room_number.24":[
         "Room number cannot be empty"
      ],
      "room_number.25":[
         "Room number cannot be empty"
      ],
      "room_number.26":[
         "Room number cannot be empty"
      ],
      "room_number.27":[
         "Room number cannot be empty"
      ],
      "room_number.28":[
         "Room number cannot be empty"
      ]
   }
}
</code>```

In the above js object, the error object contains "floor.0":["Please select a floor"],"floor.1":["Please select a floor"],"floor.2":["Please select a floor"] and so on.

I want to count how many floor.* arrays is present

Note:
I am accessing the single values like the below

```<code>$("#floor_error_1").text(data.responseJSON.errors["floor.0"]);
$("#floor_error_2").text(data.responseJSON.errors["floor.1"]);
</code>```

how to count? and loop through and print the errors?

答:
You can use Object.keys() to get the keys of error in an array. Then filter only the items startsWith "floor" and take its length.

You can also use regex instead of startsWith.

```<code>Object.keys(data.errors).filter(x => x.startsWith('floor')).length
</code>```

To print errors you can try:

```<code>let errorKeys = Object.keys(data.errors).filter(x => x.startsWith('floor'));

let count = errorKeys.length;

let floorErrors = errorKeys.map(key => ({
    key: key,
    errors: data.errors[key]
}));
</code>```

let data = {
  "message": "The given data was invalid.",
  "errors": {
    "roomtype_id": [
      "Please select a room type"
    ],
    "price": [
      "Price cannot be empty"
    ],
    "amenities": [
      "Atleast select one amenities"
    ],
    "floor.0": [
      "Please select a floor"
    ],
    "floor.1": [
      "Please select a floor"
    ],
    "floor.2": [
      "Please select a floor"
    ],
    "floor.3": [
      "Please select a floor"
    ],
    "floor.4": [
      "Please select a floor"
    ],
    "room_number.0": [
      "Room number cannot be empty"
    ],
    "room_number.1": [
      "Room number cannot be empty"
    ],
    "room_number.2": [
      "Room number cannot be empty"
    ],
    "room_number.3": [
      "Room number cannot be empty"
    ],
    "room_number.4": [
      "Room number cannot be empty"
    ],
    "room_number.5": [
      "Room number cannot be empty"
    ],
    "room_number.6": [
      "Room number cannot be empty"
    ],
    "room_number.7": [
      "Room number cannot be empty"
    ],
    "room_number.8": [
      "Room number cannot be empty"
    ],
    "room_number.9": [
      "Room number cannot be empty"
    ],
    "room_number.10": [
      "Room number cannot be empty"
    ],
    "room_number.11": [
      "Room number cannot be empty"
    ],
    "room_number.12": [
      "Room number cannot be empty"
    ],
    "room_number.13": [
      "Room number cannot be empty"
    ],
    "room_number.14": [
      "Room number cannot be empty"
    ],
    "room_number.15": [
      "Room number cannot be empty"
    ],
    "room_number.16": [
      "Room number cannot be empty"
    ],
    "room_number.17": [
      "Room number cannot be empty"
    ],
    "room_number.18": [
      "Room number cannot be empty"
    ],
    "room_number.19": [
      "Room number cannot be empty"
    ],
    "room_number.20": [
      "Room number cannot be empty"
    ],
    "room_number.21": [
      "Room number cannot be empty"
    ],
    "room_number.22": [
      "Room number cannot be empty"
    ],
    "room_number.23": [
      "Room number cannot be empty"
    ],
    "room_number.24": [
      "Room number cannot be empty"
    ],
    "room_number.25": [
      "Room number cannot be empty"
    ],
    "room_number.26": [
      "Room number cannot be empty"
    ],
    "room_number.27": [
      "Room number cannot be empty"
    ],
    "room_number.28": [
      "Room number cannot be empty"
    ]
  }
}

let errorKeys = Object.keys(data.errors).filter(x => x.startsWith('floor'));

let count = errorKeys.length;

let floorErrors = errorKeys.map(key => ({
    key: key,
    errors: data.errors[key]
}));

console.log(errorKeys, count, floorErrors)

console.log()```

Body:
Trying to count the arrays inside javascript object. This response is coming back from laravel validator

  {
   "message":"The given data was invalid.",
   "errors":{
      "roomtype_id":[
         "Please select a room type"
      ],
      "price":[
         "Price cannot be empty"
      ],
      "amenities":[
         "Atleast select one amenities"
      ],
      "floor.0":[
         "Please select a floor"
      ],
      "floor.1":[
         "Please select a floor"
      ],
      "floor.2":[
         "Please select a floor"
      ],
      "floor.3":[
         "Please select a floor"
      ],
      "floor.4":[
         "Please select a floor"
      ],
      "room_number.0":[
         "Room number cannot be empty"
      ],
      "room_number.1":[
         "Room number cannot be empty"
      ],
      "room_number.2":[
         "Room number cannot be empty"
      ],
      "room_number.3":[
         "Room number cannot be empty"
      ],
      "room_number.4":[
         "Room number cannot be empty"
      ],
      "room_number.5":[
         "Room number cannot be empty"
      ],
      "room_number.6":[
         "Room number cannot be empty"
      ],
      "room_number.7":[
         "Room number cannot be empty"
      ],
      "room_number.8":[
         "Room number cannot be empty"
      ],
      "room_number.9":[
         "Room number cannot be empty"
      ],
      "room_number.10":[
         "Room number cannot be empty"
      ],
      "room_number.11":[
         "Room number cannot be empty"
      ],
      "room_number.12":[
         "Room number cannot be empty"
      ],
      "room_number.13":[
         "Room number cannot be empty"
      ],
      "room_number.14":[
         "Room number cannot be empty"
      ],
      "room_number.15":[
         "Room number cannot be empty"
      ],
      "room_number.16":[
         "Room number cannot be empty"
      ],
      "room_number.17":[
         "Room number cannot be empty"
      ],
      "room_number.18":[
         "Room number cannot be empty"
      ],
      "room_number.19":[
         "Room number cannot be empty"
      ],
      "room_number.20":[
         "Room number cannot be empty"
      ],
      "room_number.21":[
         "Room number cannot be empty"
      ],
      "room_number.22":[
         "Room number cannot be empty"
      ],
      "room_number.23":[
         "Room number cannot be empty"
      ],
      "room_number.24":[
         "Room number cannot be empty"
      ],
      "room_number.25":[
         "Room number cannot be empty"
      ],
      "room_number.26":[
         "Room number cannot be empty"
      ],
      "room_number.27":[
         "Room number cannot be empty"
      ],
      "room_number.28":[
         "Room number cannot be empty"
      ]
   }
}

In the above js object, the error object contains "floor.0":["Please select a floor"],"floor.1":["Please select a floor"],"floor.2":["Please select a floor"] and so on.

I want to count how many floor.* arrays is present

Note:
I am accessing the single values like the below

$("#floor_error_1").text(data.responseJSON.errors["floor.0"]);
$("#floor_error_2").text(data.responseJSON.errors["floor.1"]);

how to count? and loop through and print the errors?

Body:
You can use Object.keys() to get the keys of error in an array. Then filter only the items startsWith "floor" and take its length.

You can also use regex instead of startsWith.

Object.keys(data.errors).filter(x => x.startsWith('floor')).length

To print errors you can try:

let errorKeys = Object.keys(data.errors).filter(x => x.startsWith('floor'));

let count = errorKeys.length;

let floorErrors = errorKeys.map(key => ({
    key: key,
    errors: data.errors[key]
}));

let data = {
  "message": "The given data was invalid.",
  "errors": {
    "roomtype_id": [
      "Please select a room type"
    ],
    "price": [
      "Price cannot be empty"
    ],
    "amenities": [
      "Atleast select one amenities"
    ],
    "floor.0": [
      "Please select a floor"
    ],
    "floor.1": [
      "Please select a floor"
    ],
    "floor.2": [
      "Please select a floor"
    ],
    "floor.3": [
      "Please select a floor"
    ],
    "floor.4": [
      "Please select a floor"
    ],
    "room_number.0": [
      "Room number cannot be empty"
    ],
    "room_number.1": [
      "Room number cannot be empty"
    ],
    "room_number.2": [
      "Room number cannot be empty"
    ],
    "room_number.3": [
      "Room number cannot be empty"
    ],
    "room_number.4": [
      "Room number cannot be empty"
    ],
    "room_number.5": [
      "Room number cannot be empty"
    ],
    "room_number.6": [
      "Room number cannot be empty"
    ],
    "room_number.7": [
      "Room number cannot be empty"
    ],
    "room_number.8": [
      "Room number cannot be empty"
    ],
    "room_number.9": [
      "Room number cannot be empty"
    ],
    "room_number.10": [
      "Room number cannot be empty"
    ],
    "room_number.11": [
      "Room number cannot be empty"
    ],
    "room_number.12": [
      "Room number cannot be empty"
    ],
    "room_number.13": [
      "Room number cannot be empty"
    ],
    "room_number.14": [
      "Room number cannot be empty"
    ],
    "room_number.15": [
      "Room number cannot be empty"
    ],
    "room_number.16": [
      "Room number cannot be empty"
    ],
    "room_number.17": [
      "Room number cannot be empty"
    ],
    "room_number.18": [
      "Room number cannot be empty"
    ],
    "room_number.19": [
      "Room number cannot be empty"
    ],
    "room_number.20": [
      "Room number cannot be empty"
    ],
    "room_number.21": [
      "Room number cannot be empty"
    ],
    "room_number.22": [
      "Room number cannot be empty"
    ],
    "room_number.23": [
      "Room number cannot be empty"
    ],
    "room_number.24": [
      "Room number cannot be empty"
    ],
    "room_number.25": [
      "Room number cannot be empty"
    ],
    "room_number.26": [
      "Room number cannot be empty"
    ],
    "room_number.27": [
      "Room number cannot be empty"
    ],
    "room_number.28": [
      "Room number cannot be empty"
    ]
  }
}

let errorKeys = Object.keys(data.errors).filter(x => x.startsWith('floor'));

let count = errorKeys.length;

let floorErrors = errorKeys.map(key => ({
    key: key,
    errors: data.errors[key]
}));

console.log(errorKeys, count, floorErrors)

console.log()


问:
Next steps to take for an apache beam missing class?
I am receiving this error when trying to use apache beam

java.lang.NoClassDefFoundError:
  org/apache/beam/runners/dataflow/util/DoFnInfo

When trying to run

```<code>PCollection<ReadableFile> activities = p.apply(
  "ReadBatchFiles", FileIO.match().filepattern("<google cloud storage bucket taken out>"))
.apply(FileIO.readMatches());
</code>```

POM.xml:

```<code>  <dependencies>
    <dependency>
      <groupId>com.google.cloud.dataflow</groupId>
      <artifactId>google-cloud-dataflow-java-sdk-all</artifactId>
      <version>2.1.0</version>
    </dependency>
<dependency>
    <groupId>org.apache.beam</groupId>
    <artifactId>beam-sdks-java-core</artifactId>
    <version>2.2.0</version>
</dependency>
<dependency>
    <groupId>org.apache.beam</groupId>
    <artifactId>beam-sdks-java-io-google-cloud-platform</artifactId>
    <version>2.2.0</version>
</dependency>
<dependency>
    <groupId>org.apache.beam</groupId>
    <artifactId>beam-runners-direct-java</artifactId>
    <version>2.2.0</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.apache.beam</groupId>
    <artifactId>beam-runners-google-cloud-dataflow-java</artifactId>
    <version>2.2.0</version>
</dependency>
<dependency>
</code>```

It looks like this was moved at: link1

And possibly was at: link2

Any idea how I would link it to the needed location?

thanks

答: Google made DataflowJavaSDK compatible with Beam 2.2.0 only two days ago, but it has not been released yet. You'll have to wait for the maven release 2.2.0 of the SDK or compile the dependency from source yourself.</p>

Body:
I am receiving this error when trying to use apache beam

java.lang.NoClassDefFoundError:
  org/apache/beam/runners/dataflow/util/DoFnInfo

When trying to run

PCollection<ReadableFile> activities = p.apply(
  "ReadBatchFiles", FileIO.match().filepattern("<google cloud storage bucket taken out>"))
.apply(FileIO.readMatches());

POM.xml:

  <dependencies>
    <dependency>
      <groupId>com.google.cloud.dataflow</groupId>
      <artifactId>google-cloud-dataflow-java-sdk-all</artifactId>
      <version>2.1.0</version>
    </dependency>
<dependency>
    <groupId>org.apache.beam</groupId>
    <artifactId>beam-sdks-java-core</artifactId>
    <version>2.2.0</version>
</dependency>
<dependency>
    <groupId>org.apache.beam</groupId>
    <artifactId>beam-sdks-java-io-google-cloud-platform</artifactId>
    <version>2.2.0</version>
</dependency>
<dependency>
    <groupId>org.apache.beam</groupId>
    <artifactId>beam-runners-direct-java</artifactId>
    <version>2.2.0</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.apache.beam</groupId>
    <artifactId>beam-runners-google-cloud-dataflow-java</artifactId>
    <version>2.2.0</version>
</dependency>
<dependency>

It looks like this was moved at: link1

And possibly was at: link2

Any idea how I would link it to the needed location?

thanks


问:
How to dump a table to console?
I'm having trouble displaying the contents of a table which contains nested tables (n-deep). I'd like to just dump it to std out or the console via a print statement or something quick and dirty but I can't figure out how. I'm looking for the rough equivalent that I'd get when printing an NSDictionary using gdb.

答:
There are 2 solutions that I want to mention: a quick&dirty one, and another which properly escapes all keys and values but is bigger

Simple & fast solution (use only on "safe" inputs):

```<code>local function format_any_value(obj, buffer)
    local _type = type(obj)
    if _type == "table" then
        buffer[#buffer + 1] = '{"'
        for key, value in next, obj, nil do
            buffer[#buffer + 1] = tostring(key) .. '":'
            format_any_value(value, buffer)
            buffer[#buffer + 1] = ',"'
        end
        buffer[#buffer] = '}' -- note the overwrite
    elseif _type == "string" then
        buffer[#buffer + 1] = '"' .. obj .. '"'
    elseif _type == "boolean" or _type == "number" then
        buffer[#buffer + 1] = tostring(obj)
    else
        buffer[#buffer + 1] = '"???' .. _type .. '???"'
    end
end
</code>```

Usage:

```<code>local function format_as_json(obj)
    if obj == nil then return "null" else
        local buffer = {}
        format_any_value(obj, buffer)
        return table.concat(buffer)
    end
end

local function print_as_json(obj)
    print(_format_as_json(obj))
end

print_as_json {1, 2, 3}
print_as_json(nil)
print_as_json("string")
print_as_json {[1] = 1, [2] = 2, three = { { true } }, four = "four"}
</code>```

Correct solution with key/value escaping

Small library that I wrote in pure Lua for this specific use-case: https://github.com/vn971/fast_json_encode

Or specifically this 1 file that includes both a formatter and a printer: https://github.com/vn971/fast_json_encode/blob/master/json_format.lua

Title: How to dump a table to console?

Body:
There are 2 solutions that I want to mention: a quick&dirty one, and another which properly escapes all keys and values but is bigger

Simple & fast solution (use only on "safe" inputs):

local function format_any_value(obj, buffer)
    local _type = type(obj)
    if _type == "table" then
        buffer[#buffer + 1] = '{"'
        for key, value in next, obj, nil do
            buffer[#buffer + 1] = tostring(key) .. '":'
            format_any_value(value, buffer)
            buffer[#buffer + 1] = ',"'
        end
        buffer[#buffer] = '}' -- note the overwrite
    elseif _type == "string" then
        buffer[#buffer + 1] = '"' .. obj .. '"'
    elseif _type == "boolean" or _type == "number" then
        buffer[#buffer + 1] = tostring(obj)
    else
        buffer[#buffer + 1] = '"???' .. _type .. '???"'
    end
end

Usage:

local function format_as_json(obj)
    if obj == nil then return "null" else
        local buffer = {}
        format_any_value(obj, buffer)
        return table.concat(buffer)
    end
end

local function print_as_json(obj)
    print(_format_as_json(obj))
end

print_as_json {1, 2, 3}
print_as_json(nil)
print_as_json("string")
print_as_json {[1] = 1, [2] = 2, three = { { true } }, four = "four"}

Correct solution with key/value escaping

Small library that I wrote in pure Lua for this specific use-case: https://github.com/vn971/fast_json_encode

Or specifically this 1 file that includes both a formatter and a printer: https://github.com/vn971/fast_json_encode/blob/master/json_format.lua


问:
Calling a double array with parameters from field as method
disclaimer: Sorry if I used the terms incorrectly. It would be great if you could provide the correct terms (if I used them incorrectly!)

This is my class with the field and constructor:

```<code>double[] studentMathScores = {81.5,89.0,45.5,99.0,55.0,34.5,56.0,78.0,76.0,80.0};
public StudentDashboard(double[] studentMathScores)
    {
        this.studentMathScores = studentMathScores;
    }
</code>```

How do I declare an object in my main class using studentMathScores?

```<code>StudentDashboard test = new StudentDashboard(studentMathScores);
</code>```

`

答:
I'll start of with the OOP concepts.

this is how Declaration is done:

```<code>StudentDashboard test;
</code>```

Now i'll initialize the object by assigning it the constructor of the class. Also providing constructor the required parameter of an array:

```<code>StudentDashboard test = new StudentDashboard(studentMathScores);
</code>```

now whenever i'll need to use this array from this object this is how it will be done.

```<code>double Singleindex = test.studentMathScores[1];
double[] wholeArray = test.studentMathScores;
</code>```

Body:
disclaimer: Sorry if I used the terms incorrectly. It would be great if you could provide the correct terms (if I used them incorrectly!)

This is my class with the field and constructor:

double[] studentMathScores = {81.5,89.0,45.5,99.0,55.0,34.5,56.0,78.0,76.0,80.0};
public StudentDashboard(double[] studentMathScores)
    {
        this.studentMathScores = studentMathScores;
    }

How do I declare an object in my main class using studentMathScores?

StudentDashboard test = new StudentDashboard(studentMathScores);

`

Body:
I'll start of with the OOP concepts.

this is how Declaration is done:

StudentDashboard test;

Now i'll initialize the object by assigning it the constructor of the class. Also providing constructor the required parameter of an array:

StudentDashboard test = new StudentDashboard(studentMathScores);

now whenever i'll need to use this array from this object this is how it will be done.

double Singleindex = test.studentMathScores[1];
double[] wholeArray = test.studentMathScores;