问:
Kivy AttributeError: 'NoneType' object has no attribute 'get_screen'
I'm trying to get a Screen initialised with a number of Buttons depending on the result from a query to my database but I'm getting an AttributeError. I think this is because when I initialise my app there is no Information Screen and reading this answer: AttributeError: 'NoneType' object has no attribute 'current'
I need to use Clock to delay the initialisation of my Finder class so my Information class has time to be created but I'm not quite sure how I go about doing this in the __init__ method, or if this is even the right approach?

```<code>class Finder(Screen):
    layout_profiles = ObjectProperty(None)

    def __init__(self, **kwargs):
        super(Finder, self).__init__(**kwargs)
        self.mydb = mysql.connector.connect(host="localhost", user="root", passwd="", database="")
        self.cur = self.mydb.cursor(buffered=True)
        self.cur.execute("SELECT gender, age, name FROM users WHERE location = %s AND date_of_visit = %s",
                         (self.manager.get_screen('information').location.text,
                          self.manager.get_screen('information').date))
        self.mydb.commit()
        self.results = cur.fetchall()
        self.cur.close()
        self.mydb.close()
        if self.results:
            for result in self.results:
                if result[0] == "male":
                    male_btn = MaleButton(text="{}, {}".format(result[1], result[2]))
                    self.layout_profiles.add_widget(male_btn)
                elif result[0] == "female":
                    female_btn = FemaleButton(text="{}, {}".format(result[1], result[2]))
                    self.layout_profiles.add_widget(female_btn)
                else:
                    unknown_btn = NoGenderButton(text="{}, {}".format(result[1], result[2]))
                    self.layout_profiles.add_widget(unknown_btn)
</code>```

Error

```<code>line 249, in __init__
     (self.manager.get_screen('information').location.text,
 AttributeError: 'NoneType' object has no attribute 'get_screen'
</code>```

答:
, dtThis is a way to execute all the stuff after the screen's initialization

class Finder(Screen):
    layout_profiles = ObjectProperty(None)

    def __init__(self, **kwargs):
        super(Finder, self).__init__(**kwargs)
        self.mydb = mysql.connector.connect(host="localhost", user="root", passwd="", database="")
        self.cur = self.mydb.cursor(buffered=True)
        Clock.schedule_once(self.do_stuff)

    def do_stuff(self, dt):
        self.cur.execute("SELECT gender, age, name FROM users WHERE location = %s AND date_of_visit = %s",
                         (self.manager.get_screen('information').location.text,
                          self.manager.get_screen('information').date))
        self.mydb.commit()
        self.results = self.cur.fetchall()
        self.cur.close()
        self.mydb.close()
        if self.results:
            for result in self.results:
                if result[0] == "male":
                    male_btn = MaleButton(text="{}, {}".format(result[1], result[2]))
                    self.layout_profiles.add_widget(male_btn)
                elif result[0] == "female":
                    female_btn = FemaleButton(text="{}, {}".format(result[1], result[2]))
                    self.layout_profiles.add_widget(female_btn)
                else:
                    unknown_btn = NoGenderButton(
                        text="{}, {}".format(result[1], result[2]))
                    self.layout_profiles.add_widget(unknown_btn)
```

Body:
I'm trying to get a Screen initialised with a number of Buttons depending on the result from a query to my database but I'm getting an AttributeError. I think this is because when I initialise my app there is no Information Screen and reading this answer: AttributeError: 'NoneType' object has no attribute 'current'
I need to use Clock to delay the initialisation of my Finder class so my Information class has time to be created but I'm not quite sure how I go about doing this in the __init__ method, or if this is even the right approach?

class Finder(Screen):
    layout_profiles = ObjectProperty(None)

    def __init__(self, **kwargs):
        super(Finder, self).__init__(**kwargs)
        self.mydb = mysql.connector.connect(host="localhost", user="root", passwd="", database="")
        self.cur = self.mydb.cursor(buffered=True)
        self.cur.execute("SELECT gender, age, name FROM users WHERE location = %s AND date_of_visit = %s",
                         (self.manager.get_screen('information').location.text,
                          self.manager.get_screen('information').date))
        self.mydb.commit()
        self.results = cur.fetchall()
        self.cur.close()
        self.mydb.close()
        if self.results:
            for result in self.results:
                if result[0] == "male":
                    male_btn = MaleButton(text="{}, {}".format(result[1], result[2]))
                    self.layout_profiles.add_widget(male_btn)
                elif result[0] == "female":
                    female_btn = FemaleButton(text="{}, {}".format(result[1], result[2]))
                    self.layout_profiles.add_widget(female_btn)
                else:
                    unknown_btn = NoGenderButton(text="{}, {}".format(result[1], result[2]))
                    self.layout_profiles.add_widget(unknown_btn)

Error

line 249, in __init__
     (self.manager.get_screen('information').location.text,
 AttributeError: 'NoneType' object has no attribute 'get_screen'


来源: stackexchange

问:
Architecture for Reporting Web Site
I've alluded to this project before, in this question, but the scope of redesign has been slightly tightened, i.e. I can't redesign the whole thing, so I 'd like some general advice on how to structure the existing artefacts in the application as an incremental step in improving the design.

The site has two areas of functionality, v.i.z. reporting and maintenance.  This is the major function of the site, not data manipulation, but just presentation.  The site includes a small number of maintenance pages that use standard GridViews and FormViews for maintaining a small area of data.  This is why I have decided against a rich, complex DAL in favour of the Enterprise Library DAAB and plain vanilla datasets.

Each report is an isolated page that uses results of a dynamic SQL query to explicitly render HTML table rows for the report.  In order to not maintain one set of queries for both mySQL and MSSQL for each report, I will move all data access to stored procedures, removing coupling to either DB engine through the DAAB.

I am looking at reporting tools to decouple the report structure definition from the report presentation.  I would prefer to not define report structure in classes, as telerik reporting does, but have yet to look at other reporting tools.

All reports share a common filter page that is presented on choosing a report from a menu, which redirects to the chosen report once the user is happy with their filter selections.  Is there any guidance available for this very common scenario that I seem to have to keep reinventing?

I am looking for general advice on how to move this toward a better structured product, without actually restructuring the whole project.  Simple stuff like separating maintenance pages from report pages in sub-directories, etc.

I'm not looking for others to do my work, and will in due course have implemented many improvements of my own making, but I would appreciate general opinions on how other people would handle a project like this.

答:
I'm going to go with a management system for metadata on reports, with a simple directory structure for a page-per-report system, using the DevExpress ASPxGridView.  This grid is more than capable of meeting the reporting needs of this application.

I'll be implementing maintenance and admin as standard web forms, with a shared filter form for most reports, dynamically configured based on report metadata.  There will be no runtime maintenance of reports, as adding a report requires adding a page.  This is acceptable as maintenance will be infrequent.

OwnerDisplayName: ProfK

ContentLicense: CC BY-SA 2.5

Title: Architecture for Reporting Web Site


问:
Scope constants to an rspec context
I often want to do

```<code>context "empty stack" do
  SOME_CONSTANT = "value"
  it "should be empty" do
    # use SOME_CONSTANT
  end
end

context "populated stack" do
  SOME_CONSTANT = "a different value"
  it "should have some items" do
    # use SOME_CONSTANT
  end
end
</code>```

ruby doesn't scope constants to closures so they leak out. Does anyone have a trick for declaring constants that are scoped to a context?

答:
Change the declaration of the constant:

from SOME_CONSTANT = "value"

to self::SOME_CONSTANT = "value"

RSpec creates an anonymous class for each set of specs (context in your example) that it comes across. Declaring a constant without self:: in an anonymous class makes it available in global scope, and is visible to all the specs. Changing the constant declaration to self:: ensures that it is visible only within the anonymous class.

Title: Scope constants to an rspec context

Body:
I often want to do

context "empty stack" do
  SOME_CONSTANT = "value"
  it "should be empty" do
    # use SOME_CONSTANT
  end
end

context "populated stack" do
  SOME_CONSTANT = "a different value"
  it "should have some items" do
    # use SOME_CONSTANT
  end
end

ruby doesn't scope constants to closures so they leak out. Does anyone have a trick for declaring constants that are scoped to a context?

ContentLicense: CC BY-SA 3.0


问:
calculate date difference between today's date and pandas date series
Want to calculate the difference of days between pandas date series -

```<code>0      2013-02-16
1      2013-01-29
2      2013-02-21
3      2013-02-22
4      2013-03-01
5      2013-03-14
6      2013-03-18
7      2013-03-21
</code>```

and today's date.

I tried but could not come up with logical solution.
Please help me with the code. Actually I am new to python and there are lot of syntactical errors happening while applying any function.

答:
With numpy you can solve it like difference-two-dates-days-weeks-months-years-pandas-python-2
. bottom line

```<code>df['diff_days'] = df['First dates column'] - df['Second Date column']

# for days use 'D' for weeks use 'W', for month use 'M' and for years use 'Y'
df['diff_days']=df['diff_days']/np.timedelta64(1,'D')
print(df)
</code>```

if you want days as int and not as float use

```<code>df['diff_days']=df['diff_days']//np.timedelta64(1,'D')
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Want to calculate the difference of days between pandas date series -

0      2013-02-16
1      2013-01-29
2      2013-02-21
3      2013-02-22
4      2013-03-01
5      2013-03-14
6      2013-03-18
7      2013-03-21

and today's date.

I tried but could not come up with logical solution.
Please help me with the code. Actually I am new to python and there are lot of syntactical errors happening while applying any function.

Body:
With numpy you can solve it like difference-two-dates-days-weeks-months-years-pandas-python-2
. bottom line

df['diff_days'] = df['First dates column'] - df['Second Date column']

# for days use 'D' for weeks use 'W', for month use 'M' and for years use 'Y'
df['diff_days']=df['diff_days']/np.timedelta64(1,'D')
print(df)

if you want days as int and not as float use

df['diff_days']=df['diff_days']//np.timedelta64(1,'D')


问:
How to add a line break in an Android TextView?
I am trying to add a line break in the TextView.

I tried suggested \n but that does nothing. Here is how I set my texts.

```<code>TextView txtSubTitle = (TextView)findViewById(r.id.txtSubTitle);
txtSubTitle.setText(Html.fromHtml(getResources().getString(R.string.sample_string)));
</code>```

This is my String: <string name="sample_string">some test line 1 \n some test line 2</string>

It should show like so:

```<code>some test line 1
some test line 2
</code>```

But it shows like so: some test line 1 some test line 2.

Am I missing something?

答:
I would recommend querying the line.separator property, and using that whenever you want to add a line break.

Here is some sample code:

```<code>TextView calloutContent = new TextView(getApplicationContext());
calloutContent.setTextColor(Color.BLACK);
calloutContent.setSingleLine(false);
calloutContent.setLines(2);
calloutContent.setText(" line 1" + System.getProperty ("line.separator")+"  line2" );
</code>```

Body:
I am trying to add a line break in the TextView.

I tried suggested \n but that does nothing. Here is how I set my texts.

TextView txtSubTitle = (TextView)findViewById(r.id.txtSubTitle);
txtSubTitle.setText(Html.fromHtml(getResources().getString(R.string.sample_string)));

This is my String: <string name="sample_string">some test line 1 \n some test line 2</string>

It should show like so:

some test line 1
some test line 2

But it shows like so: some test line 1 some test line 2.

Am I missing something?

Body:
I would recommend querying the line.separator property, and using that whenever you want to add a line break.

Here is some sample code:

TextView calloutContent = new TextView(getApplicationContext());
calloutContent.setTextColor(Color.BLACK);
calloutContent.setSingleLine(false);
calloutContent.setLines(2);
calloutContent.setText(" line 1" + System.getProperty ("line.separator")+"  line2" );


问:
For a service bot, should I go with ChatScript or Rasa?
ChatScript runs fast and from my research it looks like it handles dialogue very well. On the other hand, it appears to have only a single active developer.

Rasa on the other hand, looks much more actively developed.

I guess I'd like to know the trade-off in terms of performance and complexity between the two.

答:
If you’re looking for Something simple give DeadLetter.io bot tool a go.

It’s kinda of difficult to get your head around but well worth it in the long run  rasa is still a very good tool and was my go to when staring from scratch.


问:
Android Adapter only fetching the last entered data
I tried looking around but cant seem to find an answer that could resolve it.
Here is the process of what I'm doing:

1: Users enter data in a alert dialog

2: Data get sent into sql.

3: Adapter runs, takes data and put into a cardview.

4: Cardview is displayed(Stacks according to number of inputs made).

What that is not working to plan, the data that is being outputted overrides all previous inputs,and updates all cardviews with the latest information.

EG: Input 1: Test 1, Input 2: Test 2. Output will be 2 cardviews of Test 2.

Contact Activity

```<code>import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.sp.R;

public class Contacts extends AppCompatActivity {

    private Button newContact;
    private AlertDialog.Builder builder;
    private AlertDialog dialog;
    private RecyclerView recyclerView;

    private ContactDatabaseHelper helper;
    private ContactAdapter mAdapter;

    private EditText new_contact_name;
    private EditText new_contact_number;
    private EditText new_contact_relation;
    private Button button_create_contact;
    private Button button_cancel_create;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.contacts);

        helper = new ContactDatabaseHelper(this);

        recyclerView = findViewById(R.id.contact_recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new ContactAdapter(this,getAllItems());
        recyclerView.setAdapter(mAdapter);

        newContact = findViewById(R.id.contact_button);
        // New Contact Button
        newContact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                builder = new AlertDialog.Builder(Contacts.this);
                builder.setTitle("Create New Contact");
                builder.setCancelable(false);
                View view = LayoutInflater.from(Contacts.this).inflate(R.layout.new_contact_dialog,null,false);
                CreateDialog(view);
                builder.setView(view);
                dialog = builder.create();
                dialog.show();
            }
        });

    }

    private void CreateDialog(View view) {

        // ContactDialog ID's
        new_contact_name = view.findViewById(R.id.new_contact_name);
        new_contact_number = view.findViewById(R.id.new_contact_number);
        new_contact_relation = view.findViewById(R.id.new_contact_relation);
        button_create_contact = view.findViewById(R.id.button_create_contact);
        button_cancel_create = view.findViewById(R.id.button_cancel_create);

        button_create_contact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                        // Get String of Name, Number, Relationship
                        String contactNameStr = new_contact_name.getText().toString();
                        String contactNumberStr = new_contact_number.getText().toString();
                        String contactRelationStr = new_contact_relation.getText().toString();

                        // Insert into ContactTable
                        helper.insertContactDatabase(contactNameStr,contactNumberStr,contactRelationStr);
                        mAdapter.swapCursor(getAllItems());

                        // Outputs a Toast
                        Toast.makeText(Contacts.this, "Contact Created", Toast.LENGTH_SHORT).show();
                        dialog.dismiss();
            }
        });

        button_cancel_create.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

    }

    private Cursor getAllItems(){
        return helper.getContactDatabase();
    }

}
</code>```

Contact Adapter

```<code>import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.sp.R;

public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.MyHolder>{

    private Context mContext;
    private Cursor c;
    private ContactDatabaseHelper helper;

    public ContactAdapter(Context context,Cursor cursor) {

        mContext = context;
        c = cursor;
        helper = new ContactDatabaseHelper(mContext);
    }

    public static class MyHolder extends RecyclerView.ViewHolder{

        private TextView contact_name;
        private TextView contact_number;
        private TextView contact_relation;

        public MyHolder(View itemView) {
            super(itemView);

            contact_name = itemView.findViewById(R.id.contact_list_name_item);
            contact_number = itemView.findViewById(R.id.contact_list_number_item);
            contact_relation = itemView.findViewById(R.id.contact_list_relation_item);
        }
    }

    @Override
    public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(mContext).inflate(R.layout.contact_list,parent,false);

        return new MyHolder(view);
    }

    @Override
    public void onBindViewHolder(MyHolder holder, final int position) {

        c.moveToFirst();

        holder.contact_name.setText(helper.getContactName(c));
        holder.contact_number.setText(helper.getContactNumber(c));
        holder.contact_relation.setText(helper.getContactRelation(c));

    }

    @Override
    public int getItemCount() {

        return c.getCount();
    }

    public void swapCursor(Cursor newCursor){
        if (c != null){
            c.close();
        }

        c = newCursor;

        if (newCursor != null){
            notifyDataSetChanged();
        }
    }

}
</code>```

Contact Database

```<code>import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class ContactDatabaseHelper extends SQLiteOpenHelper {

    public static String DATABASE_NAME = "contactlist.db";
    private static final int SCHEMA_VERSION = 1;

    public ContactDatabaseHelper(Context context) { super(context, DATABASE_NAME, null, SCHEMA_VERSION); }

    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL("CREATE TABLE contact_table( name TEXT, number TEXT , relation TEXT);");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

    // Adds data into Contact database
    public void insertContactDatabase (String contact_name, String contact_number, String contact_relation) {
        ContentValues cv = new ContentValues();

        cv.put("name", contact_name);
        cv.put("number", contact_number);
        cv.put("relation", contact_relation);

        getWritableDatabase().insert("contact_table", "name", cv);
    }

    // Read Contact database
    public Cursor getContactDatabase() {
        return  (getReadableDatabase().rawQuery(
                "SELECT name, number, relation  FROM contact_table ORDER BY  + name", null));
    }

    // Delete Contact database
    public Integer deleteContactDatabase () {
        SQLiteDatabase db = this.getWritableDatabase();
        return db.delete("contact_table",null,null);

    }

    public String getContactName (Cursor c){ return (c.getString(0)); }

    public String getContactNumber (Cursor c){ return (c.getString(1)); }

    public String getContactRelation (Cursor c){ return (c.getString(2)); }
}
</code>```

contacts

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/contact_background"
    tools:context=".Contact.Contacts">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">

                <androidx.recyclerview.widget.RecyclerView
                    android:id="@+id/contact_recycler_view"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_above="@id/contact_button"
                    android:layout_marginTop="10dp"
                    android:scrollbars="vertical">

                </androidx.recyclerview.widget.RecyclerView>

                <Button
                    android:id="@+id/contact_button"
                    android:layout_width="150dp"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginTop="10sp"
                    android:layout_marginBottom="10sp"
                    android:background="#43464B"
                    android:text="New Contact"
                    android:textAlignment="center"
                    android:textColor="#FFFFFF"
                    android:textSize="18sp" />
            </LinearLayout>
        </ScrollView>

    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

contact_list (Cardview)

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/list_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardBackgroundColor="#FFEAB8"
    app:cardCornerRadius="15dp"
    app:cardElevation="5dp"
    app:cardUseCompatPadding="true">

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:cardBackgroundColor="#00ACEE"
        app:cardCornerRadius="5dp"
        app:cardElevation="15dp"
        app:cardUseCompatPadding="true">

        <LinearLayout
            android:id="@+id/contact_layout_name"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="10dp"
            android:orientation="horizontal">

            <TextView
                android:layout_width="120dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:text="Name"
                android:textAlignment="center"
                android:textColor="#E6E6E6"
                android:textSize="20sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:text=":"
                android:textSize="20sp" />

            <TextView
                android:id="@+id/contact_list_name_item"
                android:layout_width="190dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:text="Name"
                android:textColor="#FFFF00"
                android:textSize="20sp" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/contact_layout_number"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="35dp"
            android:orientation="horizontal">

            <TextView
                android:layout_width="120dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:layout_marginTop="5dp"
                android:text="Number"
                android:textAlignment="center"
                android:textColor="#E6E6E6"
                android:textSize="20sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="5dp"
                android:text=":"
                android:textSize="20sp" />

            <TextView
                android:id="@+id/contact_list_number_item"
                android:layout_width="190dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="5dp"
                android:text="Number"
                android:textColor="#FFFF00"
                android:textSize="20sp" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/contact_layout_relation"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="60dp"
            android:layout_marginBottom="15dp"
            android:orientation="horizontal">

            <TextView
                android:layout_width="120dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:layout_marginTop="10dp"
                android:text="Relationship"
                android:textAlignment="center"
                android:textColor="#E6E6E6"
                android:textSize="20sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="10dp"
                android:text=":"
                android:textSize="20sp" />

            <TextView
                android:id="@+id/contact_list_relation_item"
                android:layout_width="190dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="10dp"
                android:text="Relationship"
                android:textColor="#FFFF00"
                android:textSize="20sp" />

        </LinearLayout>

    </androidx.cardview.widget.CardView>

</androidx.cardview.widget.CardView>
</code>```

答:
I didn't read through and understand all your code but those lines seems off to me:

```<code>holder.contact_name.setText(helper.getContactName(c));
holder.contact_number.setText(helper.getContactNumber(c));
holder.contact_relation.setText(helper.getContactRelation(c));
</code>```

maybe try using the position

Body:
I tried looking around but cant seem to find an answer that could resolve it.
Here is the process of what I'm doing:

1: Users enter data in a alert dialog

2: Data get sent into sql.

3: Adapter runs, takes data and put into a cardview.

4: Cardview is displayed(Stacks according to number of inputs made).

What that is not working to plan, the data that is being outputted overrides all previous inputs,and updates all cardviews with the latest information.

EG: Input 1: Test 1, Input 2: Test 2. Output will be 2 cardviews of Test 2.

Contact Activity

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.sp.R;

public class Contacts extends AppCompatActivity {

    private Button newContact;
    private AlertDialog.Builder builder;
    private AlertDialog dialog;
    private RecyclerView recyclerView;

    private ContactDatabaseHelper helper;
    private ContactAdapter mAdapter;

    private EditText new_contact_name;
    private EditText new_contact_number;
    private EditText new_contact_relation;
    private Button button_create_contact;
    private Button button_cancel_create;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.contacts);

        helper = new ContactDatabaseHelper(this);

        recyclerView = findViewById(R.id.contact_recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new ContactAdapter(this,getAllItems());
        recyclerView.setAdapter(mAdapter);

        newContact = findViewById(R.id.contact_button);
        // New Contact Button
        newContact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                builder = new AlertDialog.Builder(Contacts.this);
                builder.setTitle("Create New Contact");
                builder.setCancelable(false);
                View view = LayoutInflater.from(Contacts.this).inflate(R.layout.new_contact_dialog,null,false);
                CreateDialog(view);
                builder.setView(view);
                dialog = builder.create();
                dialog.show();
            }
        });

    }

    private void CreateDialog(View view) {

        // ContactDialog ID's
        new_contact_name = view.findViewById(R.id.new_contact_name);
        new_contact_number = view.findViewById(R.id.new_contact_number);
        new_contact_relation = view.findViewById(R.id.new_contact_relation);
        button_create_contact = view.findViewById(R.id.button_create_contact);
        button_cancel_create = view.findViewById(R.id.button_cancel_create);

        button_create_contact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                        // Get String of Name, Number, Relationship
                        String contactNameStr = new_contact_name.getText().toString();
                        String contactNumberStr = new_contact_number.getText().toString();
                        String contactRelationStr = new_contact_relation.getText().toString();

                        // Insert into ContactTable
                        helper.insertContactDatabase(contactNameStr,contactNumberStr,contactRelationStr);
                        mAdapter.swapCursor(getAllItems());

                        // Outputs a Toast
                        Toast.makeText(Contacts.this, "Contact Created", Toast.LENGTH_SHORT).show();
                        dialog.dismiss();
            }
        });

        button_cancel_create.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

    }

    private Cursor getAllItems(){
        return helper.getContactDatabase();
    }

}

Contact Adapter

import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.sp.R;

public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.MyHolder>{

    private Context mContext;
    private Cursor c;
    private ContactDatabaseHelper helper;

    public ContactAdapter(Context context,Cursor cursor) {

        mContext = context;
        c = cursor;
        helper = new ContactDatabaseHelper(mContext);
    }

    public static class MyHolder extends RecyclerView.ViewHolder{

        private TextView contact_name;
        private TextView contact_number;
        private TextView contact_relation;

        public MyHolder(View itemView) {
            super(itemView);

            contact_name = itemView.findViewById(R.id.contact_list_name_item);
            contact_number = itemView.findViewById(R.id.contact_list_number_item);
            contact_relation = itemView.findViewById(R.id.contact_list_relation_item);
        }
    }

    @Override
    public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(mContext).inflate(R.layout.contact_list,parent,false);

        return new MyHolder(view);
    }

    @Override
    public void onBindViewHolder(MyHolder holder, final int position) {

        c.moveToFirst();

        holder.contact_name.setText(helper.getContactName(c));
        holder.contact_number.setText(helper.getContactNumber(c));
        holder.contact_relation.setText(helper.getContactRelation(c));

    }

    @Override
    public int getItemCount() {

        return c.getCount();
    }

    public void swapCursor(Cursor newCursor){
        if (c != null){
            c.close();
        }

        c = newCursor;

        if (newCursor != null){
            notifyDataSetChanged();
        }
    }

}

Contact Database

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class ContactDatabaseHelper extends SQLiteOpenHelper {

    public static String DATABASE_NAME = "contactlist.db";
    private static final int SCHEMA_VERSION = 1;

    public ContactDatabaseHelper(Context context) { super(context, DATABASE_NAME, null, SCHEMA_VERSION); }

    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL("CREATE TABLE contact_table( name TEXT, number TEXT , relation TEXT);");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

    // Adds data into Contact database
    public void insertContactDatabase (String contact_name, String contact_number, String contact_relation) {
        ContentValues cv = new ContentValues();

        cv.put("name", contact_name);
        cv.put("number", contact_number);
        cv.put("relation", contact_relation);

        getWritableDatabase().insert("contact_table", "name", cv);
    }

    // Read Contact database
    public Cursor getContactDatabase() {
        return  (getReadableDatabase().rawQuery(
                "SELECT name, number, relation  FROM contact_table ORDER BY  + name", null));
    }

    // Delete Contact database
    public Integer deleteContactDatabase () {
        SQLiteDatabase db = this.getWritableDatabase();
        return db.delete("contact_table",null,null);

    }

    public String getContactName (Cursor c){ return (c.getString(0)); }

    public String getContactNumber (Cursor c){ return (c.getString(1)); }

    public String getContactRelation (Cursor c){ return (c.getString(2)); }
}

contacts

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/contact_background"
    tools:context=".Contact.Contacts">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">

                <androidx.recyclerview.widget.RecyclerView
                    android:id="@+id/contact_recycler_view"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_above="@id/contact_button"
                    android:layout_marginTop="10dp"
                    android:scrollbars="vertical">

                </androidx.recyclerview.widget.RecyclerView>

                <Button
                    android:id="@+id/contact_button"
                    android:layout_width="150dp"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginTop="10sp"
                    android:layout_marginBottom="10sp"
                    android:background="#43464B"
                    android:text="New Contact"
                    android:textAlignment="center"
                    android:textColor="#FFFFFF"
                    android:textSize="18sp" />
            </LinearLayout>
        </ScrollView>

    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

contact_list (Cardview)

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/list_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardBackgroundColor="#FFEAB8"
    app:cardCornerRadius="15dp"
    app:cardElevation="5dp"
    app:cardUseCompatPadding="true">

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:cardBackgroundColor="#00ACEE"
        app:cardCornerRadius="5dp"
        app:cardElevation="15dp"
        app:cardUseCompatPadding="true">

        <LinearLayout
            android:id="@+id/contact_layout_name"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="10dp"
            android:orientation="horizontal">

            <TextView
                android:layout_width="120dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:text="Name"
                android:textAlignment="center"
                android:textColor="#E6E6E6"
                android:textSize="20sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:text=":"
                android:textSize="20sp" />

            <TextView
                android:id="@+id/contact_list_name_item"
                android:layout_width="190dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:text="Name"
                android:textColor="#FFFF00"
                android:textSize="20sp" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/contact_layout_number"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="35dp"
            android:orientation="horizontal">

            <TextView
                android:layout_width="120dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:layout_marginTop="5dp"
                android:text="Number"
                android:textAlignment="center"
                android:textColor="#E6E6E6"
                android:textSize="20sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="5dp"
                android:text=":"
                android:textSize="20sp" />

            <TextView
                android:id="@+id/contact_list_number_item"
                android:layout_width="190dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="5dp"
                android:text="Number"
                android:textColor="#FFFF00"
                android:textSize="20sp" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/contact_layout_relation"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="60dp"
            android:layout_marginBottom="15dp"
            android:orientation="horizontal">

            <TextView
                android:layout_width="120dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:layout_marginTop="10dp"
                android:text="Relationship"
                android:textAlignment="center"
                android:textColor="#E6E6E6"
                android:textSize="20sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="10dp"
                android:text=":"
                android:textSize="20sp" />

            <TextView
                android:id="@+id/contact_list_relation_item"
                android:layout_width="190dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="10dp"
                android:text="Relationship"
                android:textColor="#FFFF00"
                android:textSize="20sp" />

        </LinearLayout>

    </androidx.cardview.widget.CardView>

</androidx.cardview.widget.CardView>

Body:
I didn't read through and understand all your code but those lines seems off to me:

holder.contact_name.setText(helper.getContactName(c));
holder.contact_number.setText(helper.getContactNumber(c));
holder.contact_relation.setText(helper.getContactRelation(c));

maybe try using the position


问:
Why operator AND returns error in tsql, that seems to be valid in general sql
I try to apply WHERE AND WHERE operators, but somehow AND returns an error, single WHERE for both cases works fine.

I don't feel like I made a mistake in code as well, at least not in general SQL syntax.

```<code>SELECT *
FROM dbo.flat_file
WHERE [Date] > '1/1/2020'
AND
WHERE [Deposit] > 1000
</code>```

I am new to T-SQL, so I may not be aware of basic principles.

tsql printscr

答:
There can only be one WHERE clause in a query. You try to have two. Instead just AND the second condition to the first in the first (and only) WHERE clause.

```<code>SELECT *
       FROM dbo.flat_file
       WHERE [Date] > '1/1/2020'
             AND [Deposit] > 1000;
</code>```

Side note: varchar is likely the wrong datatype for date and deposit. date and integer my be a better fit.

Body:
I try to apply WHERE AND WHERE operators, but somehow AND returns an error, single WHERE for both cases works fine.

I don't feel like I made a mistake in code as well, at least not in general SQL syntax.

SELECT *
FROM dbo.flat_file
WHERE [Date] > '1/1/2020'
AND
WHERE [Deposit] > 1000

I am new to T-SQL, so I may not be aware of basic principles.

tsql printscr

Body:
There can only be one WHERE clause in a query. You try to have two. Instead just AND the second condition to the first in the first (and only) WHERE clause.

SELECT *
       FROM dbo.flat_file
       WHERE [Date] > '1/1/2020'
             AND [Deposit] > 1000;

Side note: varchar is likely the wrong datatype for date and deposit. date and integer my be a better fit.


问:
Password-less website authentification / login
Many websites have a password-less authentification system, i.e. you can signup / login / logout only with an email, and no password is ever required.

How would one implement such a system? (framework and language-agnostic)

Note: I've already read:

The definitive guide to form-based website authentication,

Password-less authentication in web apps - How safe it is?
 and a few other security.SE posts

and searched for SO posts about how to actually implement a [password-less] login system, but without much success ; I haven't found a canonical question on SO about implementation of a password-less auth

Manually logging in a user without password is linked but not the same thing: there the idea is login immediately after a successful account creation, but not necessarily a 100% password-less authentification system.

答:
As I searched for a long time for this, here is a summary that I post with SO's "Answer your own question - Q&A-style"  feature. I'll update it as often as I can to improve it.

Password-less authentification method #1: "Click on the link in the email we just sent you to login"

Sign-up:

client fills signup form

client AJAX POST http://example.com/_signup {email: 'test@test.com', data: 'data'}

server checks if user already exists

client message: "Success: an email has been sent" or "Fail: already exists"

server creates DB record for user

server generates a random session ID + sends email with link: http://example.com/?sessid=f65a5bc45

Log-in:

client fills login form

client AJAX POST http://example.com/_login {email: 'test@test.com'}

client message: "An email has been sent if the account exists"

server checks if the email is in the database

server generates a random session ID + sends email with link: http://example.com/?sessid=f65a5bc45

Open link:

client opens the link http://example.com/?sessid=f65a5bc45

client: document.cookie = "sessid=f65a5bc45; expires=Fri, 31 Dec 9999 23:59:59 GMT" (or do this server side, e.g. with PHP)

client: ?sessid query string removed, navigate to /

Open /:

client: AJAX POST example.com/_load {sessid: getCookieValue('sessid')}

server checks if valid sessid. if so, sends user data to client

client xhr.onreadystatechange: fills page with user data

Password-less authentification method #2: "Enter the code in the email we just sent you to login, e.g. 123 456"

Sign-up:

client fills signup form

client AJAX POST http://example.com/_signup {email: 'test@test.com', data: 'data'}

client message "An email has been sent, please enter your code here:" or "Fail: already exists"

server creates DB record for user

idem next paragraph starting at (*)

Log-in:

client fills login form

client AJAX POST http://example.com/_login {email: 'test@test.com'}

client message "An email has been sent if the account exists, please enter your code here:"

server checks if email in database

(*) server generates random number + sends email: "Here is your code: 123 456"

client fills code form

client AJAX POST http://example.com/_login {email: 'test@test.com', code: '123456'}

server checks if valid code. if so, server generates a random session ID, and sends to client

client: document.cookie = "sessid=f65a5bc45; expires=Fri, 31 Dec 9999 23:59:59 GMT" (or do this server side with PHP)

client: navigate to /

Open /:

client AJAX POST http://example.com/_load {sessid: getCookieValue('sessid')}

server checks if valid sessid. if so, sends user data to client

client xhr.onreadystatechange: fills page with user data


问:
JavaScript Event Listeners inside methods
I was hoping to be able to call object methods from an event listener, however, I am unable to access object properties on the called function:

```<code>import {action} from '../desktopIntegration/actions.js'

class Object {
  constructor() {
    this.property = 2
  }

  addListener() {
     action.on("keyup", this.printEvent)
  }

  printEvent() {
    console.log(this.property)
  }

}
</code>```

This code gives the error:

```<code> unable to access property of undefined
</code>```

when addListener is called.

Is there a way to make this work? I want to keep the callback as a method function so that I can delete the listener on each instance of Object.

Thanks!

答:
Instance methods are not bound to the class instance by default. If a method is being used as an event listener, it is by default bound to the element emitting the event.

To fix that, you need to overwrite your method in the constructor, by a version bound to the class instance:

class Foo {
  constructor() {
    this.property = 2
    this.printEvent = this.printEvent.bind(this)
    this.addListener()
  }

  addListener() {
     document.getElementById('action').addEventListener("keyup", this.printEvent)
  }

  printEvent(event) { // added the event argument, gets automatically passed to the listener
    console.log(this.property)
    console.log(event.target.value) // to access the event emitting element, use event.target
  }

}

const bar = new Foo();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="action" /></code>```

Also note that you should NEVER call your class Object.

Body:
I was hoping to be able to call object methods from an event listener, however, I am unable to access object properties on the called function:

import {action} from '../desktopIntegration/actions.js'

class Object {
  constructor() {
    this.property = 2
  }

  addListener() {
     action.on("keyup", this.printEvent)
  }

  printEvent() {
    console.log(this.property)
  }

}

This code gives the error:

 unable to access property of undefined

when addListener is called.

Is there a way to make this work? I want to keep the callback as a method function so that I can delete the listener on each instance of Object.

Thanks!

Body:
Instance methods are not bound to the class instance by default. If a method is being used as an event listener, it is by default bound to the element emitting the event.

To fix that, you need to overwrite your method in the constructor, by a version bound to the class instance:

class Foo {
  constructor() {
    this.property = 2
    this.printEvent = this.printEvent.bind(this)
    this.addListener()
  }

  addListener() {
     document.getElementById('action').addEventListener("keyup", this.printEvent)
  }

  printEvent(event) { // added the event argument, gets automatically passed to the listener
    console.log(this.property)
    console.log(event.target.value) // to access the event emitting element, use event.target
  }

}

const bar = new Foo();

<input id="action" />

Also note that you should NEVER call your class Object.


问:
finding the maximum number of columns in a file or csv using Python
I am trying to evaluate some data using Python.  A sample of the data is as follows

```<code>****************************************************************
*                       SAMPLE DATA                            *
****************************************************************
* Date      Times    Severity  Source  Machine     State
18-May-2019 16:28:18    I   StatesLog   Off-Line   States: IALT-1
18-May-2019 16:28:19    I   StatesLog   Off-Line   States: TdALclr-0
18-May-2019 16:28:19    I   StatesLog   Off-Line   States: S722a1-0, S722a2-0, S722ascon-0
18-May-2019 16:28:19    I   StatesLog   Off-Line   States: !S722a1-1, S722(OFF)-0, !S722a2-1
</code>```

What I'm after (eventually) is

```<code>Time                    Data
18-May-2019 16:28:18    IALT-1
18-May-2019 16:28:19    TdALclr-0
18-May-2019 16:28:19    S722a1-0,
18-May-2019 16:28:19    S722a2-0,
18-May-2019 16:28:19    S722ascon-0
18-May-2019 16:28:19    !S722a1-1,
18-May-2019 16:28:19    S722(OFF)-0,
18-May-2019 16:28:19    !S722a2-1
</code>```

With data this short I can manually adjust the amount of columns I need, but as some of the data is over 100Mb in size I have no idea of how many columns I'll need to put it into a DataFrame.

I have tried the code below to remove the large header

```<code>import pandas as pd

with open('test.txt') as oldfile, open('newtest.txt', 'w') as newfile:
    newfile.write('Date      Times    Severity  Source  Machine State  Data Data1 Data2')
    for line in oldfile:
        if '*' not in line:
            newfile.write(line)

df = pd.read_table('newtest.txt', sep ='\s+', engine = 'python')
df[['Date', 'Times', 'Data', 'Data1', 'Data2']].to_csv('trial.csv')
</code>```

Which has worked up to a point but after a while with the normal data I get the a parse error that there were too many fields in the line from the "read_table" command "Expected X fields in line Z, saw Y".  I presume this is because the number of columns is taken from the top line?

I need a way to read file to know the maximum amount of columns to pass somehow to pandas to eleviate the error.  The column names don't matter for now as I can always adjust them later in the code.

Then hopefully the bottom part of my code will give me the results I'm after

```<code>df['Time'] = df['Date'].astype(str) + ' ' +df['Times']
a = df.set_index('Time').stack()
df = a[a !=0].reset_index(drop=True, level=1).reset_index(name='Data').to_csv('output.csv')
</code>```

答:
I am new to python. But you can call Bash scripts to get what you want.

```<code>import os
filename="test.txt"
cmd = "awk '{print NF}' " + filename + " |sort -unk 1,1 | tail -n 1"
max = os.system(cmd)
cmd = "awk '{print NF}' " + filename + " |sort -unk 1,1 | head -n 1"
min = os.system(cmd)
print(min, max)
</code>```

if the separator in your file is not space/TAB, you can add -F ',' (for csv file).

Body:
I am trying to evaluate some data using Python.  A sample of the data is as follows

****************************************************************
*                       SAMPLE DATA                            *
****************************************************************
* Date      Times    Severity  Source  Machine     State
18-May-2019 16:28:18    I   StatesLog   Off-Line   States: IALT-1
18-May-2019 16:28:19    I   StatesLog   Off-Line   States: TdALclr-0
18-May-2019 16:28:19    I   StatesLog   Off-Line   States: S722a1-0, S722a2-0, S722ascon-0
18-May-2019 16:28:19    I   StatesLog   Off-Line   States: !S722a1-1, S722(OFF)-0, !S722a2-1

What I'm after (eventually) is

Time                    Data
18-May-2019 16:28:18    IALT-1
18-May-2019 16:28:19    TdALclr-0
18-May-2019 16:28:19    S722a1-0,
18-May-2019 16:28:19    S722a2-0,
18-May-2019 16:28:19    S722ascon-0
18-May-2019 16:28:19    !S722a1-1,
18-May-2019 16:28:19    S722(OFF)-0,
18-May-2019 16:28:19    !S722a2-1

With data this short I can manually adjust the amount of columns I need, but as some of the data is over 100Mb in size I have no idea of how many columns I'll need to put it into a DataFrame.

I have tried the code below to remove the large header

import pandas as pd

with open('test.txt') as oldfile, open('newtest.txt', 'w') as newfile:
    newfile.write('Date      Times    Severity  Source  Machine State  Data Data1 Data2')
    for line in oldfile:
        if '*' not in line:
            newfile.write(line)

df = pd.read_table('newtest.txt', sep ='\s+', engine = 'python')
df[['Date', 'Times', 'Data', 'Data1', 'Data2']].to_csv('trial.csv')

Which has worked up to a point but after a while with the normal data I get the a parse error that there were too many fields in the line from the "read_table" command "Expected X fields in line Z, saw Y".  I presume this is because the number of columns is taken from the top line?

I need a way to read file to know the maximum amount of columns to pass somehow to pandas to eleviate the error.  The column names don't matter for now as I can always adjust them later in the code.

Then hopefully the bottom part of my code will give me the results I'm after

df['Time'] = df['Date'].astype(str) + ' ' +df['Times']
a = df.set_index('Time').stack()
df = a[a !=0].reset_index(drop=True, level=1).reset_index(name='Data').to_csv('output.csv')

Body:
I am new to python. But you can call Bash scripts to get what you want.

import os
filename="test.txt"
cmd = "awk '{print NF}' " + filename + " |sort -unk 1,1 | tail -n 1"
max = os.system(cmd)
cmd = "awk '{print NF}' " + filename + " |sort -unk 1,1 | head -n 1"
min = os.system(cmd)
print(min, max)

if the separator in your file is not space/TAB, you can add -F ',' (for csv file).


问:
Eclipse: Android not adding id class to R.java
I am currently writing a program for an android app and I keep running into a problem where I get an error "id cannot be resolved or is not a field". For example I have a line of code:

```<code>mBodyText = (EditText) findViewById(R.id.body);
</code>```

After viewing the R.java class there is no id class. I previously copied and pasted an example online and it also implemented a line of code that was similar and it added the id class to R.java.

I'm just wondering how to correct this problem. I have researched it and some people suggested to others to import android.R and this corrects some errors but then creates new ones saying that the part after is not in that category.

答: If you are using the Eclipse development environment, try just deleting the R.java file and re running the project. I ran into a couple of issues where Eclipse wouldn't update the file right away and I had to delete it to get Eclipse to regenerate it (with the updated values).</p>

Body:
I am currently writing a program for an android app and I keep running into a problem where I get an error "id cannot be resolved or is not a field". For example I have a line of code:

mBodyText = (EditText) findViewById(R.id.body);

After viewing the R.java class there is no id class. I previously copied and pasted an example online and it also implemented a line of code that was similar and it added the id class to R.java.

I'm just wondering how to correct this problem. I have researched it and some people suggested to others to import android.R and this corrects some errors but then creates new ones saying that the part after is not in that category.


问:
Remove numbers if greater than X - PHP
I am removing numbers from $name, as follows:

```<code>$name = str_replace (array ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'), '' , $namewithoutnumber);
</code>```

Is it possible to remove numbers only if there are more than X numbers, example: joe123456 (six characters) and not if: joe123 or 1joe1234?

答:
Absolutely; just run it through the strlen() function:

```<code>if (strlen($namewithoutnumber) > 5) {
  $name = str_replace (array ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'), '' , $namewithoutnumber);
}
</code>```

Title: Remove numbers if greater than X - PHP

Body:
I am removing numbers from $name, as follows:

$name = str_replace (array ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'), '' , $namewithoutnumber);

Is it possible to remove numbers only if there are more than X numbers, example: joe123456 (six characters) and not if: joe123 or 1joe1234?

Body:
Absolutely; just run it through the strlen() function:

if (strlen($namewithoutnumber) > 5) {
  $name = str_replace (array ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'), '' , $namewithoutnumber);
}


问:
Replace duplicate elements in an Array with minimum steps
I should make a program where in a given array of elements I should calculate the minimum amount of elements I should change in order to have no duplicates next to each other.

The windows are in every room and they are all at the same height, so when Mendo walks around the house and looks at them from the outside the windows look like they are stacked in a row. Mendo has three types of colors (white, gray and blue) and wants to color the windows so that there are no two windows that are the same color and are one after the other.
Write a program that will read from the standard input information about the number of windows and the price of coloring each of them with a certain color, and then print the minimum coloring cost of all windows on standard output.

The first line contains an integer N (2 <= N <= 20), which indicates the number of windows. In each of the following N rows are written 3 integers Ai, Bi, Ci (1 <= Ai, Bi, Ci <= 1000), where Ai, Bi, and Ci denote the coloring values of the i window in white , gray and blue, respectively.

Test case:
Input:
3 5 1 5
1 5 5
5 1 1
Output:
3

Also, I should keep in mind that the first element and the last one are considered neighbour-elements.

I started by sorting the array for some reason.

```<code>int main()
{
    int N;
    cin >> N;
    int Ai, Bi, Ci;

    int A[N * 3];
    int A_space = 0;

    for (int i = 0; i < N; i++) {
        cin >> Ai >> Bi >> Ci;
        A[A_space] = Ai;
        A[A_space + 1] = Bi;
        A[A_space + 2] = Ci;
        A_space += 3;
    }

    for (int i = 0; i < N * 3; i++) {
        for (int j = 0; j < N * 3; j++) {
            if (A[j] > A[j + 1]) {
                swap(A[j], A[j + 1]);
            }
        }
    }

    return 0;
}
</code>```

答: This problem can be solved by dynamic programming. You will need an N x 3 matrix for this. You will need to calculate the minimum cost of painting the window on each of the 3 colors for each of the N windows. Note that for each color it is enough to take the minimum from the cost of painting N-1 windows on the other two colors because you cannot use the same color 2 times in a row.</p>

Body:
I should make a program where in a given array of elements I should calculate the minimum amount of elements I should change in order to have no duplicates next to each other.

The windows are in every room and they are all at the same height, so when Mendo walks around the house and looks at them from the outside the windows look like they are stacked in a row. Mendo has three types of colors (white, gray and blue) and wants to color the windows so that there are no two windows that are the same color and are one after the other.
Write a program that will read from the standard input information about the number of windows and the price of coloring each of them with a certain color, and then print the minimum coloring cost of all windows on standard output.

The first line contains an integer N (2 <= N <= 20), which indicates the number of windows. In each of the following N rows are written 3 integers Ai, Bi, Ci (1 <= Ai, Bi, Ci <= 1000), where Ai, Bi, and Ci denote the coloring values of the i window in white , gray and blue, respectively.

Test case:
Input:
3 5 1 5
1 5 5
5 1 1
Output:
3

Also, I should keep in mind that the first element and the last one are considered neighbour-elements.

I started by sorting the array for some reason.

int main()
{
    int N;
    cin >> N;
    int Ai, Bi, Ci;

    int A[N * 3];
    int A_space = 0;

    for (int i = 0; i < N; i++) {
        cin >> Ai >> Bi >> Ci;
        A[A_space] = Ai;
        A[A_space + 1] = Bi;
        A[A_space + 2] = Ci;
        A_space += 3;
    }

    for (int i = 0; i < N * 3; i++) {
        for (int j = 0; j < N * 3; j++) {
            if (A[j] > A[j + 1]) {
                swap(A[j], A[j + 1]);
            }
        }
    }

    return 0;
}


问:
Encrypting files you create in R
Just want to say I am new to R. I have a file that I need to send to different clients, these clients have different passwords they use to open the file so i need to create multiple version of the file with a different password for each one. Can i create multiple files in R that are password protected? The file type is excel but it would be really handy if i can encrypt microsoft word documents as well.</p>

答:
To create a password protected xls file in R you can use the xlsx package write function with password option as below:

```<code>write.xlsx(x, file, sheetName="Sheet2", col.names=TRUE, row.names=TRUE, append=FALSE, password=NULL)
</code>```

For protecting and zipping any file you can use:

```<code>PASSWORD <- "YourPassword"

zip("C:/Users/Downloads/MyArchive.zip",
    files="C:/Users/Downloads/example.docx",
    flags = paste("--password", PASSWORD))
</code>```

Title: Encrypting files you create in R

Body:
To create a password protected xls file in R you can use the xlsx package write function with password option as below:

write.xlsx(x, file, sheetName="Sheet2", col.names=TRUE, row.names=TRUE, append=FALSE, password=NULL)

For protecting and zipping any file you can use:

PASSWORD <- "YourPassword"

zip("C:/Users/Downloads/MyArchive.zip",
    files="C:/Users/Downloads/example.docx",
    flags = paste("--password", PASSWORD))


问:
wxPython screenshot Windows
I've got an (apparently) cross-platform screenshot function using wxPython:

```<code>def take_screenshot(x=0, y=0, width=None, height=None):
try:
    import wx
except ImportError as e:
    return 'Screenshot could not be taken - wx could not be imported: %s' %(e)
import os, datetime
folder_name = datetime.date.today().strftime('%Y-%m-%d')
file_name = datetime.datetime.now().strftime('%H-%M-%S') + '.png'
directory = os.path.join(os.getcwd(), 'screenshots', folder_name)
make_directory(directory)
filename = os.path.join(directory, file_name)

app = wx.App()
screen = wx.ScreenDC()

size = screen.GetSize()
if width == None:
    width = size[0]
if height == None:
    height = size[1]
bmp = wx.EmptyBitmap(width, height)
mem = wx.MemoryDC(bmp)
mem.Blit(0, 0, width, height, screen, x, y)

del mem
bmp.SaveFile(filename, wx.BITMAP_TYPE_PNG)
return 'Screenshot saved to file: %s' %(filename)
</code>```

Here is a screenshot I took on Windows 7. This code works fine on Linux. I'm running on Python 2.7.8 and wxPython 3.0.2.0

Has anyone seen any similar problems? Am I doing something wrong?

答:
Update for wxPython 4 and higher

```<code>import wx

app = wx.App(False)
screen = wx.ScreenDC()

size = screen.GetSize()
width = size.width
height = size.height
bmp = wx.Bitmap(width, height)

# Create a memory DC that will be used for actually taking the screenshot
memDC = wx.MemoryDC()
# Tell the memory DC to use our Bitmap
# all drawing action on the memory DC will go to the Bitmap now
memDC.SelectObject(bmp)
# Blit (in this case copy) the actual screen on the memory DC
memDC.Blit(
    0, 0,
    width, height,
    screen,
    0, 0
)
# Select the Bitmap out of the memory DC by selecting a new bitmap
memDC.SelectObject(wx.NullBitmap)
im = bmp.ConvertToImage()
im.SaveFile('screenshot.png', wx.BITMAP_TYPE_PNG)
</code>```

Title: wxPython screenshot Windows

Body:
I've got an (apparently) cross-platform screenshot function using wxPython:

def take_screenshot(x=0, y=0, width=None, height=None):
try:
    import wx
except ImportError as e:
    return 'Screenshot could not be taken - wx could not be imported: %s' %(e)
import os, datetime
folder_name = datetime.date.today().strftime('%Y-%m-%d')
file_name = datetime.datetime.now().strftime('%H-%M-%S') + '.png'
directory = os.path.join(os.getcwd(), 'screenshots', folder_name)
make_directory(directory)
filename = os.path.join(directory, file_name)

app = wx.App()
screen = wx.ScreenDC()

size = screen.GetSize()
if width == None:
    width = size[0]
if height == None:
    height = size[1]
bmp = wx.EmptyBitmap(width, height)
mem = wx.MemoryDC(bmp)
mem.Blit(0, 0, width, height, screen, x, y)

del mem
bmp.SaveFile(filename, wx.BITMAP_TYPE_PNG)
return 'Screenshot saved to file: %s' %(filename)

Here is a screenshot I took on Windows 7. This code works fine on Linux. I'm running on Python 2.7.8 and wxPython 3.0.2.0

Has anyone seen any similar problems? Am I doing something wrong?

Body:
Update for wxPython 4 and higher

import wx

app = wx.App(False)
screen = wx.ScreenDC()

size = screen.GetSize()
width = size.width
height = size.height
bmp = wx.Bitmap(width, height)

# Create a memory DC that will be used for actually taking the screenshot
memDC = wx.MemoryDC()
# Tell the memory DC to use our Bitmap
# all drawing action on the memory DC will go to the Bitmap now
memDC.SelectObject(bmp)
# Blit (in this case copy) the actual screen on the memory DC
memDC.Blit(
    0, 0,
    width, height,
    screen,
    0, 0
)
# Select the Bitmap out of the memory DC by selecting a new bitmap
memDC.SelectObject(wx.NullBitmap)
im = bmp.ConvertToImage()
im.SaveFile('screenshot.png', wx.BITMAP_TYPE_PNG)


答:
You could use preg_replace for this.</p>

```<code>$name = preg_replace('/[0-9]{6,}/', '', $name_with_too_long_numbers);
</code>```

Title: Remove numbers if greater than X - PHP

Body:
You could use preg_replace for this.

$name = preg_replace('/[0-9]{6,}/', '', $name_with_too_long_numbers);


问:
With serverless-bundle, how can I run tests over code that uses the sharp package?
I am using the sharp package and serverless-bundle together in a serverless-framework project. I am able to run and deploy my code just fine with this custom.bundle.packagerOptions.scripts script: rm -rf node_modules/sharp && npm install --arch=x64 --platform=linux --target=10.15.0 sharp.

When I try to run a test over code that touches the sharp package, I get the following error: 'linux-x64' binaries cannot be used on the 'darwin-x64' platform. Please remove the 'node_modules/sharp/vendor' directory and run 'npm install'.

I don't plan on testing the implementation of sharp, rather, I am mocking the JavaScript file that is importing it. Here is the test file where I am running into this issue: https://github.com/groffcole/art-center-service/blob/master/ports/GalleriesHttpPort.test.js

What am I doing wrong?

Thanks.

答:
I have resolved the issue just by chance. I deleted my entire node_modules directory and ran npm install. I believe because I'm using the serverless-bundle package, wires were getting crossed. I can now run tests successfully using the serverless-bundle test command.

For reference, here are my custom serverless-bundle settings in my serverless.yml file:

```<code>custom:
  bundle:
    caching: false
    packagerOptions:
      scripts:
        - rm -rf node_modules/sharp && npm install --arch=x64 --platform=linux --target=10.15.0 sharp
</code>```

Body:
I have resolved the issue just by chance. I deleted my entire node_modules directory and ran npm install. I believe because I'm using the serverless-bundle package, wires were getting crossed. I can now run tests successfully using the serverless-bundle test command.

For reference, here are my custom serverless-bundle settings in my serverless.yml file:

custom:
  bundle:
    caching: false
    packagerOptions:
      scripts:
        - rm -rf node_modules/sharp && npm install --arch=x64 --platform=linux --target=10.15.0 sharp


问:
Poem (random words) generator: How can I get each paragraph to display a different set of random words?
I'm working on a little practice project that should generate poems. I created a couple of arrays full of different types of words, which I'm then grabbing randomly and adding into paragraphs. It's working, but not how I would like it to.

Since each "phrase" variable is pulling from the same set of randomly selected words, the poems are all repetitive. Whatever random noun is selected will appear in each noun slot, each random verb appears in every verb slot etc.

What I want to happen is: each slot will generate a different random word from the array. If a two of the same words are coincidentally selected at random, that's ok.

For now each type of words selected randomly once, and repeated along all the sentences.

What can I do for i't will selected randomly any time?

Here's the code.

    function makeAPoem() {
      var nouns = ["cat", "crow", "snow", "home", "boy", "raven", "tree", "moon", "night", "day", "winter", "heart", "angel", "madam", "darkness", "chamber", "lady", "bird", "person", "eye", "darkness", "air"];
      var verbs = ["ran", "felt", "fell", "focused", "looked", "stared", "sat", "sighed", "blew", "whimpered", "embraced", "hugged"];
      var articles = ["a", "the"];
      var adjectives = ["shiny", "sad", "cold", "cheerfully", "sweet", "evil"];
      var pronouns = ["I", "we", "you", "they", "she", "it", "he"];

      var randNoun = Math.floor(Math.random() * nouns.length);
      var randVerb = Math.floor(Math.random() * verbs.length);
      var randArticle = Math.floor(Math.random() * articles.length);
      var randAdjective = Math.floor(Math.random() * adjectives.length);
      var randPronoun = Math.floor(Math.random() * pronouns.length);

      var phrase1 = pronouns[randPronoun] + " " + verbs[randVerb] + " " + adjectives[randAdjective];
      var phrase2 = articles[randArticle] + " " + nouns[randNoun] + " " + verbs[randVerb] + " " + adjectives[randAdjective];
      var phrase3 = pronouns[randPronoun] + " " + verbs[randVerb] + ". " + articles[randArticle] + " " + nouns[randNoun] + " " +  verbs[randVerb] + " " + adjectives[randAdjective];
      var phrase4 = articles[randArticle] + " " + nouns[randNoun] + " " + verbs[randVerb] + " " + adjectives[randAdjective];
      var phrase5 = pronouns[randPronoun] + " " + verbs[randVerb];

      document.getElementsByClassName('poem')[0].innerHTML = phrase1;
      document.getElementsByClassName('poem')[1].innerHTML = phrase2;
      document.getElementsByClassName('poem')[2].innerHTML = phrase3;
      document.getElementsByClassName('poem')[3].innerHTML = phrase4;
      document.getElementsByClassName('poem')[4].innerHTML = phrase5;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>

    <div id="poemBox">
    <div id="edgar">
      <img src="https://cdn.britannica.com/52/76652-050-F4A6B093/Edgar-Allan-Poe.jpg" width="150px" alt="avatar">
      <p>Press the button below for a poem from Poe.</p>
      <button onclick="makeAPoem()">Go</button>
    </div>
    <div id="poetry">
      <p class="poem"></p>
      <p class="poem"></p>
      <p class="poem"></p>
      <p class="poem"></p>
      <p class="poem"></p>
    </div></code>```

In the Screenshot example here, every occurrence of a random adjective is using "sweet". Every random verb is "focused" and so on.

答:
Right now you generate any word type just once.
Just generate the randoms before any phase

function makeAPoem() {
  var nouns = ["cat", "crow", "snow", "home", "boy", "raven", "tree", "moon", "night", "day", "winter", "heart", "angel", "madam", "darkness", "chamber", "lady", "bird", "person", "eye", "darkness", "air"];
  var verbs = ["ran", "felt", "fell", "focused", "looked", "stared", "sat", "sighed", "blew", "whimpered", "embraced", "hugged"];
  var articles = ["a", "the"];
  var adjectives = ["shiny", "sad", "cold", "cheerfully", "sweet", "evil"];
  var pronouns = ["I", "we", "you", "they", "she", "it", "he"];

  function randNoun(){return nouns[Math.floor(Math.random() * nouns.length)]}
  function randVerb(){return verbs[Math.floor(Math.random() * verbs.length)]}
  function randArticle(){return articles[Math.floor(Math.random() * articles.length)]}
  function randAdjective(){return adjectives[Math.floor(Math.random() * adjectives.length)]}
  function randPronoun(){return pronouns[Math.floor(Math.random() * pronouns.length)]}

  var phrase1 = randPronoun() + " " + randVerb() + " " + randAdjective();
  var phrase2 = randArticle() + " " + randNoun() + " " + randVerb() + " " + randAdjective();
  var phrase3 = randPronoun() + " " + randVerb() + ". " + randArticle() + " " + randNoun() + " " +  randVerb() + " " + randAdjective();
  var phrase4 = randArticle() + " " + randNoun() + " " + randVerb() + " " + randAdjective();
  var phrase5 = randPronoun() + " " + randVerb();

  document.getElementsByClassName('poem')[0].innerHTML = phrase1;
  document.getElementsByClassName('poem')[1].innerHTML = phrase2;
  document.getElementsByClassName('poem')[2].innerHTML = phrase3;
  document.getElementsByClassName('poem')[3].innerHTML = phrase4;
  document.getElementsByClassName('poem')[4].innerHTML = phrase5;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="poemBox">
<div id="edgar">
  <img src="https://cdn.britannica.com/52/76652-050-F4A6B093/Edgar-Allan-Poe.jpg" width="150px" alt="avatar">
  <p>Press the button below for a poem from Poe.</p>
  <button onclick="makeAPoem()">Go</button>
</div>
<div id="poetry">
  <p class="poem"></p>
  <p class="poem"></p>
  <p class="poem"></p>
  <p class="poem"></p>
  <p class="poem"></p>
</div></code>```

Body:
I'm working on a little practice project that should generate poems. I created a couple of arrays full of different types of words, which I'm then grabbing randomly and adding into paragraphs. It's working, but not how I would like it to.

Since each "phrase" variable is pulling from the same set of randomly selected words, the poems are all repetitive. Whatever random noun is selected will appear in each noun slot, each random verb appears in every verb slot etc.

What I want to happen is: each slot will generate a different random word from the array. If a two of the same words are coincidentally selected at random, that's ok.

For now each type of words selected randomly once, and repeated along all the sentences.

What can I do for i't will selected randomly any time?

Here's the code.

    function makeAPoem() {
      var nouns = ["cat", "crow", "snow", "home", "boy", "raven", "tree", "moon", "night", "day", "winter", "heart", "angel", "madam", "darkness", "chamber", "lady", "bird", "person", "eye", "darkness", "air"];
      var verbs = ["ran", "felt", "fell", "focused", "looked", "stared", "sat", "sighed", "blew", "whimpered", "embraced", "hugged"];
      var articles = ["a", "the"];
      var adjectives = ["shiny", "sad", "cold", "cheerfully", "sweet", "evil"];
      var pronouns = ["I", "we", "you", "they", "she", "it", "he"];

      var randNoun = Math.floor(Math.random() * nouns.length);
      var randVerb = Math.floor(Math.random() * verbs.length);
      var randArticle = Math.floor(Math.random() * articles.length);
      var randAdjective = Math.floor(Math.random() * adjectives.length);
      var randPronoun = Math.floor(Math.random() * pronouns.length);

      var phrase1 = pronouns[randPronoun] + " " + verbs[randVerb] + " " + adjectives[randAdjective];
      var phrase2 = articles[randArticle] + " " + nouns[randNoun] + " " + verbs[randVerb] + " " + adjectives[randAdjective];
      var phrase3 = pronouns[randPronoun] + " " + verbs[randVerb] + ". " + articles[randArticle] + " " + nouns[randNoun] + " " +  verbs[randVerb] + " " + adjectives[randAdjective];
      var phrase4 = articles[randArticle] + " " + nouns[randNoun] + " " + verbs[randVerb] + " " + adjectives[randAdjective];
      var phrase5 = pronouns[randPronoun] + " " + verbs[randVerb];

      document.getElementsByClassName('poem')[0].innerHTML = phrase1;
      document.getElementsByClassName('poem')[1].innerHTML = phrase2;
      document.getElementsByClassName('poem')[2].innerHTML = phrase3;
      document.getElementsByClassName('poem')[3].innerHTML = phrase4;
      document.getElementsByClassName('poem')[4].innerHTML = phrase5;
    }

Press the button below for a poem from Poe.

      <button onclick="makeAPoem()">Go</button>

In the Screenshot example here, every occurrence of a random adjective is using "sweet". Every random verb is "focused" and so on.

Body:
Right now you generate any word type just once.
Just generate the randoms before any phase

function makeAPoem() {
  var nouns = ["cat", "crow", "snow", "home", "boy", "raven", "tree", "moon", "night", "day", "winter", "heart", "angel", "madam", "darkness", "chamber", "lady", "bird", "person", "eye", "darkness", "air"];
  var verbs = ["ran", "felt", "fell", "focused", "looked", "stared", "sat", "sighed", "blew", "whimpered", "embraced", "hugged"];
  var articles = ["a", "the"];
  var adjectives = ["shiny", "sad", "cold", "cheerfully", "sweet", "evil"];
  var pronouns = ["I", "we", "you", "they", "she", "it", "he"];

  function randNoun(){return nouns[Math.floor(Math.random() * nouns.length)]}
  function randVerb(){return verbs[Math.floor(Math.random() * verbs.length)]}
  function randArticle(){return articles[Math.floor(Math.random() * articles.length)]}
  function randAdjective(){return adjectives[Math.floor(Math.random() * adjectives.length)]}
  function randPronoun(){return pronouns[Math.floor(Math.random() * pronouns.length)]}

  var phrase1 = randPronoun() + " " + randVerb() + " " + randAdjective();
  var phrase2 = randArticle() + " " + randNoun() + " " + randVerb() + " " + randAdjective();
  var phrase3 = randPronoun() + " " + randVerb() + ". " + randArticle() + " " + randNoun() + " " +  randVerb() + " " + randAdjective();
  var phrase4 = randArticle() + " " + randNoun() + " " + randVerb() + " " + randAdjective();
  var phrase5 = randPronoun() + " " + randVerb();

  document.getElementsByClassName('poem')[0].innerHTML = phrase1;
  document.getElementsByClassName('poem')[1].innerHTML = phrase2;
  document.getElementsByClassName('poem')[2].innerHTML = phrase3;
  document.getElementsByClassName('poem')[3].innerHTML = phrase4;
  document.getElementsByClassName('poem')[4].innerHTML = phrase5;
}

<div id="poemBox">
<div id="edgar">
  <img src="https://cdn.britannica.com/52/76652-050-F4A6B093/Edgar-Allan-Poe.jpg" width="150px" alt="avatar">
  <p>Press the button below for a poem from Poe.</p>
  <button onclick="makeAPoem()">Go</button>
</div>
<div id="poetry">
  <p class="poem"></p>
  <p class="poem"></p>
  <p class="poem"></p>
  <p class="poem"></p>
  <p class="poem"></p>
</div>


问:
SQL Server 2008 dynamic  query doubt

Possible Duplicates:

  What is the purpose of system table table master..spt_values and what are the meanings of its values?

  Why (and how) to split column using master..spt_values?

I have some dynamic SQL, I have this lines that will be executed, whats the meaning of spt_values, and the type='P'

```<code>declare @Sql nvarchar(max)
select @Sql = ISNULL(@sql + ',', '') + QUOTENAME(RIGHT(number,10))
    from master..spt_values
    where type='P' and number between 1 and (select COUNT(*) From tableName)
</code>```

答:
spt_values is a table in the master database. As such, it's meant for internal SQL Server use only, and is undocumented to the public.

Basically the code you've got is a quick way to get your hands on a resultset of numbers.

Title: SQL Server 2008 dynamic  query doubt

Body:
Possible Duplicates:

  What is the purpose of system table table master..spt_values and what are the meanings of its values?

  Why (and how) to split column using master..spt_values?

I have some dynamic SQL, I have this lines that will be executed, whats the meaning of spt_values, and the type='P'

declare @Sql nvarchar(max)
select @Sql = ISNULL(@sql + ',', '') + QUOTENAME(RIGHT(number,10))
    from master..spt_values
    where type='P' and number between 1 and (select COUNT(*) From tableName)


问:
Thymealeaf text template not printing the current date
I am using spring boot 2.2.4 and using the thymealeaf text templates for the first time with spring boot.

Belowis the texttemplate I am trying to use and I am trying to print the current date and time but it is printing blank on screen.

```<code>CurrentDate:[#th:block th:utext="${#temporals.format(now, 'dd/MMM/yyyy HH:mm')}"/]
</code>```

I have added the Java8 date time dependency in pom.xml and also added the java8dialect in the template resolver bean.

```<code>pom.xml
--------
<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-java8time</artifactId>
    <version>3.0.4.RELEASE</version>
</dependency>

ThymeleafConfig.java
----------------------

@Configuration
public class ThymeleafConfig {

@Bean(name = "textTemplateEngine")
public TemplateEngine textTemplateEngine() {
   TemplateEngine templateEngine = new TemplateEngine();
   templateEngine.addTemplateResolver(textTemplateResolver());
   templateEngine.addDialect(new Java8TimeDialect());
   return templateEngine;
}

private ITemplateResolver textTemplateResolver() {
   ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
   templateResolver.setPrefix("/templates/text/");
   templateResolver.setSuffix(".txt");
   templateResolver.setTemplateMode(TemplateMode.TEXT /* https://github.com/thymeleaf/thymeleaf/issues/395 */);
   templateResolver.setCharacterEncoding("UTF8");
   templateResolver.setCheckExistence(true);
   templateResolver.setCacheable(false);
   return templateResolver;
 }
}
</code>```

Can anybody please tell me what am I doing wrong in thymealeaf text template that it is not printing the date?

答:
You can use a Thymeleaf utility method to print various date and time variants.

For example:

```<code><div th:text="${#dates.createNow()}"></div>
</code>```

I think that may answer your specific question.

However, I suspect your question is more about the wider topic of binding Java objects to Thymeleaf templates in Spring - and I have not used Spring with Thymeleaf.

Body:
I am using spring boot 2.2.4 and using the thymealeaf text templates for the first time with spring boot.

Belowis the texttemplate I am trying to use and I am trying to print the current date and time but it is printing blank on screen.

CurrentDate:[#th:block th:utext="${#temporals.format(now, 'dd/MMM/yyyy HH:mm')}"/]

I have added the Java8 date time dependency in pom.xml and also added the java8dialect in the template resolver bean.

pom.xml
--------
<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-java8time</artifactId>
    <version>3.0.4.RELEASE</version>
</dependency>

ThymeleafConfig.java
----------------------

@Configuration
public class ThymeleafConfig {

@Bean(name = "textTemplateEngine")
public TemplateEngine textTemplateEngine() {
   TemplateEngine templateEngine = new TemplateEngine();
   templateEngine.addTemplateResolver(textTemplateResolver());
   templateEngine.addDialect(new Java8TimeDialect());
   return templateEngine;
}

private ITemplateResolver textTemplateResolver() {
   ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
   templateResolver.setPrefix("/templates/text/");
   templateResolver.setSuffix(".txt");
   templateResolver.setTemplateMode(TemplateMode.TEXT /* https://github.com/thymeleaf/thymeleaf/issues/395 */);
   templateResolver.setCharacterEncoding("UTF8");
   templateResolver.setCheckExistence(true);
   templateResolver.setCacheable(false);
   return templateResolver;
 }
}

Can anybody please tell me what am I doing wrong in thymealeaf text template that it is not printing the date?

Body:
You can use a Thymeleaf utility method to print various date and time variants.

For example:

<div th:text="${#dates.createNow()}"></div>

I think that may answer your specific question.

However, I suspect your question is more about the wider topic of binding Java objects to Thymeleaf templates in Spring - and I have not used Spring with Thymeleaf.


问:
Can not assign observable data to local variable in angular
My Service

```<code>import { Injectable } from '@angular/core';
import {Observable} from 'rxjs';
import { HttpClient,HttpParams } from '@angular/common/http';

@Injectable()
export class UserService {

  constructor(private http: HttpClient) { }
  isAdmin;
  getLogIn(email:string,password:string):Observable<boolean>{
    let params = new HttpParams().set("userEmail",email).set("userPassword", password);
    return this.http.get<boolean>("http://localhost:8080/user/login",{params: params});
     }
}
</code>```

My Subscribe call

```<code> email:string="";
  password:string="";
  adminFlag:boolean=false;

  login(event: any) {
    console.log(this.adminFlag);
    this.userService.getLogIn(this.email,this.password).subscribe(data => this.adminFlag=(data));
    console.log(this.adminFlag);
    if(this.adminFlag){
      console.log("INSIDE IF")
        this.router.navigate("../../home");
    }
  }
</code>```

When i log in data var in console I am getting raw data as

```<code>true
</code>```

but i couldn't assign it to this boolean "adminFlag" it is changed to undefined

Anything I missed...???

the API is returning a boolean..I need that boolean to be assigned...

答:
When you are executing:

```<code>    this.userService.getLogIn(this.email,this.password).subscribe(data => this.adminFlag=(data));
</code>```

it means that you expect DATA to be a boolean. It's an observable boolean instead.
To get the real boolean, use the pipe function, eg:

```<code>getLogIn(email:string,password:string):boolean{
  let params = new HttpParams().set("userEmail",email).set("userPassword", password);
  return this.http
    .get<boolean>("http://localhost:8080/user/login",{params: params})
    .pipe(map(data => data);
}
</code>```

Body:
My Service

import { Injectable } from '@angular/core';
import {Observable} from 'rxjs';
import { HttpClient,HttpParams } from '@angular/common/http';

@Injectable()
export class UserService {

  constructor(private http: HttpClient) { }
  isAdmin;
  getLogIn(email:string,password:string):Observable<boolean>{
    let params = new HttpParams().set("userEmail",email).set("userPassword", password);
    return this.http.get<boolean>("http://localhost:8080/user/login",{params: params});
     }
}

My Subscribe call

 email:string="";
  password:string="";
  adminFlag:boolean=false;

  login(event: any) {
    console.log(this.adminFlag);
    this.userService.getLogIn(this.email,this.password).subscribe(data => this.adminFlag=(data));
    console.log(this.adminFlag);
    if(this.adminFlag){
      console.log("INSIDE IF")
        this.router.navigate("../../home");
    }
  }

When i log in data var in console I am getting raw data as

true

but i couldn't assign it to this boolean "adminFlag" it is changed to undefined

Anything I missed...???

the API is returning a boolean..I need that boolean to be assigned...

Body:
When you are executing:

    this.userService.getLogIn(this.email,this.password).subscribe(data => this.adminFlag=(data));

it means that you expect DATA to be a boolean. It's an observable boolean instead.
To get the real boolean, use the pipe function, eg:

getLogIn(email:string,password:string):boolean{
  let params = new HttpParams().set("userEmail",email).set("userPassword", password);
  return this.http
    .get<boolean>("http://localhost:8080/user/login",{params: params})
    .pipe(map(data => data);
}


问:
Combine or Simplify Web Service Queries in Power BI
I was wondering if there was a flexible way to setup multiple web services (API) queries in Power BI. The web service I am using is only capable of getting me one day of data for one location per query and I need daily data for 10 locations. Which means on a standard 31 day month I would need to setup 310 queries. The data I am interested in are the Final LMPs and the website I am pulling from is https://webservices.iso-ne.com/docs/v1.1/. An example of a working query in PowerBI that is grabbing Final LMP data for just 02/01/2020 for location 4152 is:

https://webservices.iso-ne.com/api/v1.1/hourlylmp/rt/final/day/20200201/location/4152.xml

答:
For such case I would setup the following items:

A data source (e.g. manually via 'Enter Data') with 10 individual locations

A data source with the required date range (e.g. something like that)

A data source that combines the the first two (cross join e.g. an example)

Add a column (to source 3) that calls a 'custom function' that for each combined record (in step 3) makes an API request to retrieve the data. The function should take two parameters (location and the day) as the input

Thanks,
Mau


问:
Why can't I declare a variable or function more than once with different types?
Okay I know "One Definition Rule", but when I try to declare a variable with different types subsequently in source code, I run into some mistake like following:

```<code>int fkc();
void fkc();
</code>```

enter image description here

I mean these two statements are just two declarations, not definitions. Alright, Does every declaration have to have only one unique definition?

答:
In C++, you can't overload functions based on return type.

Overload resolution takes into account the function name , cv-qualifiers , the number of parameters and their types.

You could do something like:

```<code>auto fck()
{
    if constexpr(...) return my_int;
    else /* do smth without return */
}
</code>```

but that's not function overloading of course.

Body:
Okay I know "One Definition Rule", but when I try to declare a variable with different types subsequently in source code, I run into some mistake like following:

int fkc();
void fkc();

enter image description here

I mean these two statements are just two declarations, not definitions. Alright, Does every declaration have to have only one unique definition?

Body:
In C++, you can't overload functions based on return type.

Overload resolution takes into account the function name , cv-qualifiers , the number of parameters and their types.

You could do something like:

auto fck()
{
    if constexpr(...) return my_int;
    else /* do smth without return */
}

but that's not function overloading of course.


问:
RSpec response.body is still empty even with config.render_views
In my spec_helper.rb file I have specifically set it to config.render_views but the response.body I get back is still empty. Here is my basic spec

```<code>describe  "#index" do
    it "should list all rooms" do
      get 'index'
      stub(Person).all
    end

    it "responds with 200 response code" do
      response.should be_ok
    end

    it "renders the index template" do
      pp response.body
      response.should render_template("people/index")
    end

  end
</code>```

Is there anything else that could have shorted this behavior? It's fine when I go through the browser. I am on Rspec 2.5.0

答:
Have you tried having render_views in your controller spec file? That works for me.

Another thing I noticed is that you only access the index page once in your test cases - the first one to be precise. The rest will return empty html content because there is no response.

This is how I will implement it. But if you already have config.render_views in the *spec_helper.rb* file and that works, you can do without the render_views in the controller spec.

```<code>describe MyController
    render_views

    before :each do
        get :index
    end

    describe  "#index" do
        it "should list all rooms" do
            stub(Person).all
        end

        it "responds with 200 response code" do
            response.should be_ok
        end

        it "renders the index template" do
            pp response.body
            response.should render_template("people/index")
        end
    end
end
</code>```

EDIT:
The subtle change here is the before blobk in which I call get :index for every it block.

Body:
In my spec_helper.rb file I have specifically set it to config.render_views but the response.body I get back is still empty. Here is my basic spec

describe  "#index" do
    it "should list all rooms" do
      get 'index'
      stub(Person).all
    end

    it "responds with 200 response code" do
      response.should be_ok
    end

    it "renders the index template" do
      pp response.body
      response.should render_template("people/index")
    end

  end

Is there anything else that could have shorted this behavior? It's fine when I go through the browser. I am on Rspec 2.5.0

Body:
Have you tried having render_views in your controller spec file? That works for me.

Another thing I noticed is that you only access the index page once in your test cases - the first one to be precise. The rest will return empty html content because there is no response.

This is how I will implement it. But if you already have config.render_views in the *spec_helper.rb* file and that works, you can do without the render_views in the controller spec.

describe MyController
    render_views

    before :each do
        get :index
    end

    describe  "#index" do
        it "should list all rooms" do
            stub(Person).all
        end

        it "responds with 200 response code" do
            response.should be_ok
        end

        it "renders the index template" do
            pp response.body
            response.should render_template("people/index")
        end
    end
end

EDIT:
The subtle change here is the before blobk in which I call get :index for every it block.