问:
how do I access the main class's stage? + Can I pass functions as arguments like this?
There are two files in my actionscript project named "TestAPP", TestAPP.as and Draggable.as

TestAPP.as:

```<code>
    package {
 import flash.display.Sprite;
 import flash.display.Stage;

 public class TestAPP extends Sprite
 {
  var _mainStage:Stage;
  public function TestAPP()//This is where we test the UI components.
  {

   var sp:Sprite = new Sprite();
   _mainStage = stage;
   _mainStage.addChild(sp);
   sp.graphics.beginFill(0x00FF00);
   sp.graphics.drawCircle(0,0,10);
   sp.graphics.endFill();
   sp.x = 50;
   sp.y = 50;
   var draggable1:Draggable = new draggable(sp,_mainStage,limitingfunc);
  }
  public function limitingfunc(x:Number,y:Number):int{
   return 0;
  }

 }
}
</code>```

And for the draggable.as:

```<code>
package
{
 import flash.display.Sprite;
 import flash.display.Stage;
 import flash.events.MouseEvent;

 public class Draggable
 {
  private var _limitingFunc:Function;
  private var _which:Sprite;
  private var _MouseSavedX:Number;
  private var _MouseSavedY:Number;

  private var _stage:Stage;
  public function Draggable(which:Sprite,stage:Stage,limitingfunc:Function)
  {
   _limitingFunc = limitingfunc;
   _which = which;
   _stage = stage;
   _which.addEventListener(MouseEvent.MOUSE_DOWN,begin_drag);

  }
  //limiting func: returns 0 when the object is free to move that place.
  //returns -1 when the user wants to block X coordinate changes (but maintain Y free)
  //returns -2 when the user wants to block Y ...
  //returns -3 or less when the user wants to block both X and Y from changing.
  //returns
  private function Return_0(x:Number = 0,y:Number = 0):int{
   return 0;
  }
  private function begin_drag(ev:MouseEvent):void{
   var xTo:Number = _stage.mouseX - _MouseSavedX + _which.x;
   var yTo:Number = _stage.mouseY - _MouseSavedY + _which.y;
   var limitingFuncReturnValue:int = _limitingFunc(xTo,yTo);
   if(limitingFuncReturnValue == 0){//free to move.
    _which.x = xTo;
    _which.y = yTo;
   }
   else if(limitingFuncReturnValue == -1){//free to move Y
    _which.y = yTo;
   }
   else if(limitingFuncReturnValue == -2){
    _which.y = yTo;
   }
   //else:do nothing.
  }
 }
}
</code>```

In "my actionscript theory", I'm supposed to see a circle that follows the mouse when I click it. (The draggable is not fully implemented) But the circle doesn't even budge :(

...I've been trying to figure out how to access the main class's stage property. I've googled for it, but still no progress.

Please help this helpless newb!!! I'll really appreciate your help:)
Thank you!

答:
You can access the main class' stage property the same way you do it for any DisplayObject on the stage: Use this.stage.

So just this should be enough:

```<code>var sp:Sprite = new Sprite();
stage.addChild(sp);
</code>```

You could then pass the sprite and the main class' stage as a parameter, the way you did - but I would recommend creating a subclass Draggable extends Sprite and instantiate the whole thing using new Draggable() instead.

The new object will automatically have its own reference to stage as soon as it is added to the display list, and limitingFunc could be a member of Draggable, as well.

Also, you can use the startDrag() and stopDrag() methods, no need to implement your own:  You can specify a Rectangle as a parameter to startDrag() to limit the permitted movement.

Body:
There are two files in my actionscript project named "TestAPP", TestAPP.as and Draggable.as

TestAPP.as:

    package {
 import flash.display.Sprite;
 import flash.display.Stage;

 public class TestAPP extends Sprite
 {
  var _mainStage:Stage;
  public function TestAPP()//This is where we test the UI components.
  {

   var sp:Sprite = new Sprite();
   _mainStage = stage;
   _mainStage.addChild(sp);
   sp.graphics.beginFill(0x00FF00);
   sp.graphics.drawCircle(0,0,10);
   sp.graphics.endFill();
   sp.x = 50;
   sp.y = 50;
   var draggable1:Draggable = new draggable(sp,_mainStage,limitingfunc);
  }
  public function limitingfunc(x:Number,y:Number):int{
   return 0;
  }

 }
}

And for the draggable.as:

package
{
 import flash.display.Sprite;
 import flash.display.Stage;
 import flash.events.MouseEvent;

 public class Draggable
 {
  private var _limitingFunc:Function;
  private var _which:Sprite;
  private var _MouseSavedX:Number;
  private var _MouseSavedY:Number;

  private var _stage:Stage;
  public function Draggable(which:Sprite,stage:Stage,limitingfunc:Function)
  {
   _limitingFunc = limitingfunc;
   _which = which;
   _stage = stage;
   _which.addEventListener(MouseEvent.MOUSE_DOWN,begin_drag);

  }
  //limiting func: returns 0 when the object is free to move that place.
  //returns -1 when the user wants to block X coordinate changes (but maintain Y free)
  //returns -2 when the user wants to block Y ...
  //returns -3 or less when the user wants to block both X and Y from changing.
  //returns
  private function Return_0(x:Number = 0,y:Number = 0):int{
   return 0;
  }
  private function begin_drag(ev:MouseEvent):void{
   var xTo:Number = _stage.mouseX - _MouseSavedX + _which.x;
   var yTo:Number = _stage.mouseY - _MouseSavedY + _which.y;
   var limitingFuncReturnValue:int = _limitingFunc(xTo,yTo);
   if(limitingFuncReturnValue == 0){//free to move.
    _which.x = xTo;
    _which.y = yTo;
   }
   else if(limitingFuncReturnValue == -1){//free to move Y
    _which.y = yTo;
   }
   else if(limitingFuncReturnValue == -2){
    _which.y = yTo;
   }
   //else:do nothing.
  }
 }
}

In "my actionscript theory", I'm supposed to see a circle that follows the mouse when I click it. (The draggable is not fully implemented) But the circle doesn't even budge :(

...I've been trying to figure out how to access the main class's stage property. I've googled for it, but still no progress.

Please help this helpless newb!!! I'll really appreciate your help:)
Thank you!

Body:
You can access the main class' stage property the same way you do it for any DisplayObject on the stage: Use this.stage.

So just this should be enough:

var sp:Sprite = new Sprite();
stage.addChild(sp);

You could then pass the sprite and the main class' stage as a parameter, the way you did - but I would recommend creating a subclass Draggable extends Sprite and instantiate the whole thing using new Draggable() instead.

The new object will automatically have its own reference to stage as soon as it is added to the display list, and limitingFunc could be a member of Draggable, as well.

Also, you can use the startDrag() and stopDrag() methods, no need to implement your own:  You can specify a Rectangle as a parameter to startDrag() to limit the permitted movement.


来源: stackexchange

问:
Import Wizard only partially uploads csv table in MySQL
I'm relatively new to MySQL

I am trying to import a csv table with 25,000 rows and 37 variables into MySQL using the import wizard. The import wizard uploads successfully but only 2483 rows appear. How do I upload the entire csv file?

答:
You may use SHOW VARIABLES LIKE "secure_file_priv"; to see the directory that has been configured.

You have two options:

Move your file to the directory specified by secure-file-priv.

Disable secure-file-priv. This must be removed from startup and cannot be modified dynamically. To do this check your MySQL start up parameters (depending on platform) and mysql.cnf

ContentLicense: CC BY-SA 3.0


问:
Filter out the stage or inside the stage
I havent had much luck with google due to the phrasing of the question so I apologize for the very basic question.

If i have 3 build stages setup in my jenkinsfile and stages 1 and 3 always run, but 2 only runs if its a PR, do I make it keep the stage but not run the command, or just filter out the whole stage?

```<code>stage {
  if (env.isPR) {
    sh()
</code>```

or more like

```<code>if (env.isPR) {
  stage {
    sh()
</code>```

答:
If you filter out the whole stage, then after a non-PR build, the stage visualization on the build page will remove that PR stage (for all builds, even the ones which in fact did run the PR stage).

So, from a visualization perspective, I would suggest that you retain the stage.

```<code>stage {
  if (env.isPR) {
    sh()
</code>```

Body:
I havent had much luck with google due to the phrasing of the question so I apologize for the very basic question.

If i have 3 build stages setup in my jenkinsfile and stages 1 and 3 always run, but 2 only runs if its a PR, do I make it keep the stage but not run the command, or just filter out the whole stage?

stage {
  if (env.isPR) {
    sh()

or more like

if (env.isPR) {
  stage {
    sh()

Body:
If you filter out the whole stage, then after a non-PR build, the stage visualization on the build page will remove that PR stage (for all builds, even the ones which in fact did run the PR stage).

So, from a visualization perspective, I would suggest that you retain the stage.

stage {
  if (env.isPR) {
    sh()


问:
Write a text file in Appveyor script
I have a problem when writing a simple text file with appveyor. Here is the simple script:

```<code>version: 1.0.{build}-{branch}

shallow_clone: true

environment:
  matrix:
    - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017
      TOOLSET: msvc-14.1
      ARCH: x86_64

install:

build: off

test_script:
  - echo ^<Where are my symbols^> > hello.txt
  - more hello.txt
</code>```

This leads to an error in the console:

```<code>Build started
Fetching repository commit (2be7d4b)...OK
Total: 274 bytes in 1 files
echo ^<Where are my symbols^> > hello.txt
Command exited with code 1
</code>```

I have tried the commands in on desktop but everything is working.

答:
This escape symbol will not work this way because internally we use call before your cmd when executing command from the custom PowerShell host.

Workarounds:

Use PowerShell

test_script:
  - ps: Set-Content -Value "<Where are my symbols>" -Path .\hello.txt
  - more hello.txt

Check-in .cmd file with your command which uses ^ escape symbol and run it.

Title: Write a text file in Appveyor script

Body:
I have a problem when writing a simple text file with appveyor. Here is the simple script:

version: 1.0.{build}-{branch}

shallow_clone: true

environment:
  matrix:
    - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017
      TOOLSET: msvc-14.1
      ARCH: x86_64

install:

build: off

test_script:
  - echo ^<Where are my symbols^> > hello.txt
  - more hello.txt

This leads to an error in the console:

Build started
Fetching repository commit (2be7d4b)...OK
Total: 274 bytes in 1 files
echo ^<Where are my symbols^> > hello.txt
Command exited with code 1

I have tried the commands in on desktop but everything is working.


问:
how to measure the page time load?
I want to know how much time a specific code in my App takes ?!!!
Thank you </p>

答: Aside from @Darins answer you won't be able to measure page load time on the client as they are across a network and there are many variables involved (i.e. You can start a javascript timer as the page would need loaded first). However anything on the server can be timed.</p>

ContentLicense: CC BY-SA 2.5

Title: how to measure the page time load?


问:
sending \X0D0A\ in OBX TX field in hl7 message
In the final report the findings are printed as paragraph.

For ex:
'FINDINGS:
Right: Peak systolic velocities are given below. Right proximal common carotid artery: 100 cm/sec Right mid common carotid artery: 100 cm/sec Right distal common carotid artery: 100 cm/sec Right proximal internal carotid artery: 100 cm/sec Right distal internal carotid artery: 100 cm/sec Right internal carotid artery plaque: None. Internal carotid artery wave forms are normal'.

I want it to be printed like below line by line.

Findings:
Right:
Peak systolic velocities are given below.
Right proximal common carotid artery: 100 cm/sec
Right mid common carotid artery: 100 cm/sec
Right distal common carotid artery: 100 cm/sec
Right proximal internal carotid artery: 100 cm/sec
Right distal internal carotid artery: 100 cm/sec
Right internal carotid artery plaque: None.
Internal carotid artery waveforms are normal.

Is it possible to achieve this by sending \x0D0A\ at the end in hl7 message like below

OBX|1|TX|93880^US DUPLEX CAROTID||Peak systolic velocities are given below.\X0D0A\||||||F|||||| (it is in single line)

OBX|1|TX|93880^US DUPLEX CAROTID||Right proximal common carotid artery: 99 cm/sec\X0D0A\||||||F||||||

OBX|1|TX|93880^US DUPLEX CAROTID||Right mid common carotid artery: 70 cm/sec\X0D0A\||||||F||||||

OBX|1|TX|93880^US DUPLEX CAROTID||Right distal common carotid artery: 74 cm/sec\X0D0A\||||||F||||||

I am new to Mirth. I apologize if i asked wrong question.

答: You don't need to generate multiple OBX segments or put CR/LF at the end of OBX-5. The correct approach as per the HL7 Version 2.8.2 Messaging Standard section 2.A.80 is to use a single OBX segment with a separate OBX-5 repetition for each line. The receiving application should render those OBX-5 repetitions on separate lines as long as it complies with the standard.</p>


问:
After filtering ListView, I'm not able to get the old position
I am not able to get the old position of my ListView after filtering, for example I should be getting position 3,5,8 after filtering, but I'm getting the default 0,1,2 position.. Do you guys have any idea why? Here's my code..

```<code>public class Application_applicant_list extends AppCompatActivity {
 private ListView applicant;
 static String applId;
 private ArrayAdapter adapter;
 SearchView sv;
 Bundle b;
 Intent intent;

 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  setContentView(R.layout.activity_application_list);
  sv = (SearchView) findViewById(R.id.appSv);
  applicant = (ListView) findViewById(R.id.listView_allForms_from_list);
  adapter = new ArrayAdapter < String > (this, android.R.layout.simple_list_item_1);
  applicant.setOnItemClickListener(new AdapterView.OnItemClickListener() {
   @Override
   public void onItemClick(AdapterView < ? > adapterView, View view, int position, long id) {
    intent = new Intent(Application_applicant_list.this, Application_form_from_list.class);

    b = new Bundle();
    b.putInt("position", position);
    intent.putExtras(b);
    Toast.makeText(getApplicationContext(), "Position:" + position,
     Toast.LENGTH_SHORT).show();
    startActivity(intent);

   }
  });

  sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
   @Override
   public boolean onQueryTextSubmit(String query) {
    return false;
   }

   @Override
   public boolean onQueryTextChange(String newText) {
    adapter.getFilter().filter(newText);

    return false;
   }
  });

 }
</code>```

This is the part where I retrieve from the database, they're in the same class

```<code> @Override
 protected void onResume() {
  DBHelper db = new DBHelper(this);
  ArrayList < String > ArrApp = new ArrayList < String > ();

  for (int i = 0; i < db.getAll_Appl().size(); i++) {
   ArrApp.add(String.valueOf(db.getAll_Appl().get(i).getApplId())); // + '\t' + '\t' + '\t' + db.getAll_IOP().get(i).getId());
  }

  adapter = new ArrayAdapter < String > (this, android.R.layout.simple_list_item_1, ArrApp) {
   @Override
   public View getView(int position, View convertView, ViewGroup parent) {
    TextView item = (TextView) super.getView(position, convertView, parent);
    item.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 30);
    item.setGravity(Gravity.CENTER);
    item.setPadding(0, 10, 0, 10);
    return item;
   }

  };
  applicant.setAdapter(adapter);
  super.onResume();
 }
}
</code>```

This is my nextActivity.java where I retrieve the position

Bundle b2 = getIntent().getExtras();
if (b2 != null) {
 int position = b2.getInt("position"); // position is from induction and operation page menu item click
 form_from_list = db.getAll_Appl().get(position);
 formAppId.setText(form_from_list.getApplId());

答:
Because, the position that return in onItemClick is the position of ListView item not the position in list datasource (in your case it is ArrApp).

Therefore, I think you should get the value of ListView item then pass it to another Activity instead of  the position.

Like

```<code>applicant.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView < ? > adapterView, View view, int position, long id) {

        String clickedItemValue = (String) adapterView.getAdapter().getItem(position); // cast to String because your list datasource is a list String
        // pass clickedItemValue to another activity
    }
});
</code>```

Body:
I am not able to get the old position of my ListView after filtering, for example I should be getting position 3,5,8 after filtering, but I'm getting the default 0,1,2 position.. Do you guys have any idea why? Here's my code..

public class Application_applicant_list extends AppCompatActivity {
 private ListView applicant;
 static String applId;
 private ArrayAdapter adapter;
 SearchView sv;
 Bundle b;
 Intent intent;

 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  setContentView(R.layout.activity_application_list);
  sv = (SearchView) findViewById(R.id.appSv);
  applicant = (ListView) findViewById(R.id.listView_allForms_from_list);
  adapter = new ArrayAdapter < String > (this, android.R.layout.simple_list_item_1);
  applicant.setOnItemClickListener(new AdapterView.OnItemClickListener() {
   @Override
   public void onItemClick(AdapterView < ? > adapterView, View view, int position, long id) {
    intent = new Intent(Application_applicant_list.this, Application_form_from_list.class);

    b = new Bundle();
    b.putInt("position", position);
    intent.putExtras(b);
    Toast.makeText(getApplicationContext(), "Position:" + position,
     Toast.LENGTH_SHORT).show();
    startActivity(intent);

   }
  });

  sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
   @Override
   public boolean onQueryTextSubmit(String query) {
    return false;
   }

   @Override
   public boolean onQueryTextChange(String newText) {
    adapter.getFilter().filter(newText);

    return false;
   }
  });

 }

This is the part where I retrieve from the database, they're in the same class

 @Override
 protected void onResume() {
  DBHelper db = new DBHelper(this);
  ArrayList < String > ArrApp = new ArrayList < String > ();

  for (int i = 0; i < db.getAll_Appl().size(); i++) {
   ArrApp.add(String.valueOf(db.getAll_Appl().get(i).getApplId())); // + '\t' + '\t' + '\t' + db.getAll_IOP().get(i).getId());
  }

  adapter = new ArrayAdapter < String > (this, android.R.layout.simple_list_item_1, ArrApp) {
   @Override
   public View getView(int position, View convertView, ViewGroup parent) {
    TextView item = (TextView) super.getView(position, convertView, parent);
    item.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 30);
    item.setGravity(Gravity.CENTER);
    item.setPadding(0, 10, 0, 10);
    return item;
   }

  };
  applicant.setAdapter(adapter);
  super.onResume();
 }
}

This is my nextActivity.java where I retrieve the position

Bundle b2 = getIntent().getExtras();
if (b2 != null) {
 int position = b2.getInt("position"); // position is from induction and operation page menu item click
 form_from_list = db.getAll_Appl().get(position);
 formAppId.setText(form_from_list.getApplId());

Body:
Because, the position that return in onItemClick is the position of ListView item not the position in list datasource (in your case it is ArrApp).

Therefore, I think you should get the value of ListView item then pass it to another Activity instead of  the position.

Like

applicant.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView < ? > adapterView, View view, int position, long id) {

        String clickedItemValue = (String) adapterView.getAdapter().getItem(position); // cast to String because your list datasource is a list String
        // pass clickedItemValue to another activity
    }
});


问:
NHibernate - one-to-one Cascade Settings
I have a one-to-one relationship between a Person class and an Employee. I  expect the INSERT to cascade from the Person to the Employee. However, this does not happen. I've tried cascade='all' and cascade='save-update' on one-to-one relationship element, but it didn't work.

The structures of the my objects are as follows:

```<code>public class Person
{
    public virtual Employee Employee { get; set; }
    public virtual int Age { get; set; }
    public virtual string Forename { get; set; }
    public virtual string Surname { get; set; }
    public virtual int PersonID { get; set; }
}

public class Employee
{
    public virtual int PersonID { get; set; }
    public virtual string PayRollNo { get; set; }
    public virtual int Holidays { get; set; }
    public virtual Person Person { get; set; }
}
</code>```

Mapping files shown below:

```<code><?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
  <class name="Employee, Employee.DAL" table="`Employee`"  >
    <id name="PersonID" column="`PersonId`" type="int">
      <generator class="native" />
    </id>
    <property type="string" length="30" name="PayRollNo" column="`PayRollNo`" />
    <property type="int" name="Holidays" column="`Holidays`" />
    <one-to-one name="Person"  class="Person" cascade="all"/>
  </class>
</hibernate-mapping>

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
  <class name="Person, Employee.DAL" table="`Person`"  >
    <id name="PersonID" column="`PersonId`">
      <generator class="foreign">
        <param name="property" >Employee</param>
      </generator>
    </id>
    <property type="string" name="Forename" column="`Forename`" />
    <property type="string" name="Surname" column="`Surname`" />
    <property type="int" name="Age" column="`Age`" />
    <one-to-one name="Employee" class="Employee"  constrained="true"  />
  </class>
</hibernate-mapping>
</code>```

Code for initiating the objects and saving them:

```<code>var employee = new Employee();

    employee.Person = new Person { Employee = employee };

    ISessionFactory sessionFactory = (new Configuration()).Configure().BuildSessionFactory();

    employee.Person.Age = 27;
    employee.Person.Forename = "N";
    employee.Person.Surname = "M";

    employee.PayRollNo = "12";
    employee.Holidays = 27;

    using (var session = sessionFactory.OpenSession())
    {
        session.Save(employee);
    }
</code>```

答: According to this http://nhibernate.info/doc/nh/en/index.html#mapping-declaration-onetoone You're missing the constrained="true" in the <one-to-one> element in the Person mapping.

Body:
I have a one-to-one relationship between a Person class and an Employee. I  expect the INSERT to cascade from the Person to the Employee. However, this does not happen. I've tried cascade='all' and cascade='save-update' on one-to-one relationship element, but it didn't work.

The structures of the my objects are as follows:

public class Person
{
    public virtual Employee Employee { get; set; }
    public virtual int Age { get; set; }
    public virtual string Forename { get; set; }
    public virtual string Surname { get; set; }
    public virtual int PersonID { get; set; }
}

public class Employee
{
    public virtual int PersonID { get; set; }
    public virtual string PayRollNo { get; set; }
    public virtual int Holidays { get; set; }
    public virtual Person Person { get; set; }
}

Mapping files shown below:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
  <class name="Employee, Employee.DAL" table="`Employee`"  >
    <id name="PersonID" column="`PersonId`" type="int">
      <generator class="native" />
    </id>
    <property type="string" length="30" name="PayRollNo" column="`PayRollNo`" />
    <property type="int" name="Holidays" column="`Holidays`" />
    <one-to-one name="Person"  class="Person" cascade="all"/>
  </class>
</hibernate-mapping>

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
  <class name="Person, Employee.DAL" table="`Person`"  >
    <id name="PersonID" column="`PersonId`">
      <generator class="foreign">
        <param name="property" >Employee</param>
      </generator>
    </id>
    <property type="string" name="Forename" column="`Forename`" />
    <property type="string" name="Surname" column="`Surname`" />
    <property type="int" name="Age" column="`Age`" />
    <one-to-one name="Employee" class="Employee"  constrained="true"  />
  </class>
</hibernate-mapping>

Code for initiating the objects and saving them:

var employee = new Employee();

    employee.Person = new Person { Employee = employee };

    ISessionFactory sessionFactory = (new Configuration()).Configure().BuildSessionFactory();

    employee.Person.Age = 27;
    employee.Person.Forename = "N";
    employee.Person.Surname = "M";

    employee.PayRollNo = "12";
    employee.Holidays = 27;

    using (var session = sessionFactory.OpenSession())
    {
        session.Save(employee);
    }


问:
How to delete copy/move instantiation of variadic template constructor
Suppose this is my class:

```<code>#include<utility>
#include<type_traits>

template<typename T>
class MyClass {
    T v;
public:
    template<typename...Ts>
    MyClass(Ts&&...args) :v{ std::forward<Ts>(args)... } {}

    MyClass(MyClass const&) = default;
    MyClass(MyClass &&) = default;
};

class OtherClass {
public:
    operator MyClass<int>() {
        return{};
    }
};

int main(){
    MyClass<int> mc;
    MyClass<int> mc2{ mc }; // error: cannot convert from 'MyClass<int>' to 'int'
    OtherClass oc;
    MyClass<int> mc3 {oc};  // error: cannot convert from 'OtherClass' to 'int'
}
</code>```

How to correctly prevent the variadic template constructor from instantiating a copy/move constructor?

答:
You can apply SFINAE with std::enable_if to restrict the types, e.g.

```<code>template <typename... Ts>
struct getFirstType {
    using type = void;
};
template <typename T, typename... Ts>
struct getFirstType<T, Ts...> {
    using type = T;
};

template<typename T>
class MyClass {
    T v;
public:
    // only valid when the first type of parameter pack is NOT MyClass
    template<typename...Ts,
             typename = std::enable_if_t<
                 !std::is_same_v<MyClass,
                                 std::decay_t<typename getFirstType<Ts...>::type>>>>
    MyClass(Ts&&...args) :v{ std::forward<Ts>(args)... } {}

    MyClass(MyClass const&) = default;
    MyClass(MyClass &&) = default;
};
</code>```

LIVE

Body:
Suppose this is my class:

#include<utility>
#include<type_traits>

template<typename T>
class MyClass {
    T v;
public:
    template<typename...Ts>
    MyClass(Ts&&...args) :v{ std::forward<Ts>(args)... } {}

    MyClass(MyClass const&) = default;
    MyClass(MyClass &&) = default;
};

class OtherClass {
public:
    operator MyClass<int>() {
        return{};
    }
};

int main(){
    MyClass<int> mc;
    MyClass<int> mc2{ mc }; // error: cannot convert from 'MyClass<int>' to 'int'
    OtherClass oc;
    MyClass<int> mc3 {oc};  // error: cannot convert from 'OtherClass' to 'int'
}

How to correctly prevent the variadic template constructor from instantiating a copy/move constructor?

Body:
You can apply SFINAE with std::enable_if to restrict the types, e.g.

template <typename... Ts>
struct getFirstType {
    using type = void;
};
template <typename T, typename... Ts>
struct getFirstType<T, Ts...> {
    using type = T;
};

template<typename T>
class MyClass {
    T v;
public:
    // only valid when the first type of parameter pack is NOT MyClass
    template<typename...Ts,
             typename = std::enable_if_t<
                 !std::is_same_v<MyClass,
                                 std::decay_t<typename getFirstType<Ts...>::type>>>>
    MyClass(Ts&&...args) :v{ std::forward<Ts>(args)... } {}

    MyClass(MyClass const&) = default;
    MyClass(MyClass &&) = default;
};

LIVE


问:
How to limit the number of login failures in the MySQL root account
I use mysql5.7, my client needs to connect to mysql using navicat, use the root account to log in for 5 consecutive failures to lock the account for 15 minutes. However, googling has turned up no good results.</p>

答: There are no such feature in Mysql.  But I think you can let the project manager to delete this feature</p>


问:
How to create operation loop for two 1 to 1 lists
Say I have 2 lists:

```<code>A = [a1,a2,a3,...,an]
B = [b1,b2,b3,...,bn]
</code>```

The lists are one-to-one.

So how do I create a loop that operates (any operation):

```<code>a1 with b1
a2 with b2
...
an with bn
</code>```

Body:
Say I have 2 lists:

A = [a1,a2,a3,...,an]
B = [b1,b2,b3,...,bn]

The lists are one-to-one.

So how do I create a loop that operates (any operation):

a1 with b1
a2 with b2
...
an with bn

Body:
Use zip

a = [1,2,3];
b = [4,5,6];

for x,y in zip(a,b):
    print x,y;


问:
Plot the distance between every two points in 2 D
If I have a table with three columns where the first column represents the name of each point, the second column represent numerical data (mean) and the last column represent (second column + fixed number). The following an example how is the data looks like:

I want to plot this table so I have the following figure

If it is possible how I can plot it using either Microsoft Excel or python or R (Bokeh).

答:
I would use hbar for this:

```<code>from bokeh.io import show, output_file
from bokeh.plotting import figure

output_file("intervals.html")

names = ["SMB", "DB", "SB", "TB"]

p = figure(y_range=names, plot_height=350)
p.hbar(y=names, left=[4,3,2,1], right=[6.2, 5.2, 4.2, 3.2], height=0.3)

show(p)
</code>```

However Whisker would also be an option if you really want whiskers instead of interval bars.

Body:
I would use hbar for this:

from bokeh.io import show, output_file
from bokeh.plotting import figure

output_file("intervals.html")

names = ["SMB", "DB", "SB", "TB"]

p = figure(y_range=names, plot_height=350)
p.hbar(y=names, left=[4,3,2,1], right=[6.2, 5.2, 4.2, 3.2], height=0.3)

show(p)

However Whisker would also be an option if you really want whiskers instead of interval bars.


答:
Just to process:

```<code>for ea, eb in zip(A, B):
    f(ea, eb)
</code>```

If you want to keep results,

```<code>[f(ea, eb) for ea, eb in zip(A, B)]
</code>```

The zip builtin sews together two or more lists elementwise into a list of tuples that we can then iterate on, either by an explicit loop or by a comprehension.

Title: How to create operation loop for two 1 to 1 lists

Body:
Just to process:

for ea, eb in zip(A, B):
    f(ea, eb)

If you want to keep results,

[f(ea, eb) for ea, eb in zip(A, B)]

The zip builtin sews together two or more lists elementwise into a list of tuples that we can then iterate on, either by an explicit loop or by a comprehension.


问:
Prolog - Creating a list
Need a hand here creating a list.  I need to return all possible combinations of prerequisites of courses, including the prerequisites of prerequisites.

Here are some rules and facts that I need to use, (Some provided, some I've created).

```<code>prereqFor(engg233, []).
prereqFor(encm339, [engg233]).
prereqFor(cpsc217, []).
prereqFor(cpsc219, [cpsc217]).
prereqFor(cpsc231, []).
prereqFor(cpsc233, [cpsc231]).
prereqFor(math271, [X]) :-
   member(X, [math211, math213]).
prereqFor(math273, []).
prereqFor(cpsc319, [C]) :-
   member(C, [cpsc219, cpsc233, cpsc235, encm339]).
prereqFor(cpsc331, [M, C]) :-
   member(M, [math271, math273]),
   member(C, [cpsc219, cpsc233, cpsc235, encm339]).
prereqFor(cpsc335, [C]) :-
   member(C, [cpsc319, cpsc331]).
</code>```

Now what I'm trying to do to accomplish this is two functions, one of which is a helper... And I can't seem to populate a list by using [H|T] or append... My current attempt:

```<code>allPrereqFor(Course, Prerequisites) :-
   prereqFor(Course, Prerequisites),
   creatingList(Course, Prerequisites, []).

creatingList(Course, Prerequisites, OnGoingList) :-
   append(Course, Prerequisites, myList).
</code>```

I also tried something like:

```<code>allPrereqFor(Course, Prerequisites) :-
   prereqFor(Course, Prerequisites),
   creatingList(Prerequisites, []).

creatingList(Addition, OnGoingList) :-
   [Addition | OnGoingList].
</code>```

I can't even get the most simple output before I even attempt a recursive case.

I have not listed every prereqFor function, but an example output would be:

```<code>| ?- allPrereqFor(cpsc331, X).
X = [cpsc217,cpsc219,math211,math271] ? ;
X = [cpsc231,cpsc233,math211,math271] ? ;
X = [consent235,cpsc235,math211,math271] ? ;
X = [encm339,engg233,math211,math271] ? ;
</code>```

Another attempt at a solution...

```<code>allPrereqFor(Course,[],Result) :-   append([Course],[],Result).
allPrereqFor(Course, X,Result) :-   prereqFor(Course, Y),
                                    Y=[H|T],
                                    allPrereqFor(H,X,Result).
</code>```

The trace:

```<code>| ?- allPrereqFor(cpsc331,X).
  1    1  Call: allPrereqFor(cpsc331,_23) ?
  1    1  Exit: allPrereqFor(cpsc331,[]) ?

X = [] ? ;
  1    1  Redo: allPrereqFor(cpsc331,[]) ?
  2    2  Call: prereqFor(cpsc331,_92) ?
  3    3  Call: member(_78,[math271,math273]) ?
  3    3  Exit: member(math271,[math271,math273]) ?
  4    3  Call: member(_80,[cpsc219,cpsc233,cpsc235,encm339]) ?
  4    3  Exit: member(cpsc219,[cpsc219,cpsc233,cpsc235,encm339]) ?
  2    2  Exit: prereqFor(cpsc331,[math271,cpsc219]) ?
  5    2  Call: allPrereqFor(math271,_23) ?
  5    2  Exit: allPrereqFor(math271,[]) ?
  1    1  Exit: allPrereqFor(cpsc331,[]) ?

X = [] ? ;
  1    1  Redo: allPrereqFor(cpsc331,[]) ?
  5    2  Redo: allPrereqFor(math271,[]) ?
</code>```

When I trace I can see that it's recursively hitting all the right courses, but it just keeps outputting:

```<code>X = [] ?;
</code>```

答:
Finding the pre-requirements of pre-requirements can be done recursively. Well, you should make use of findall/3 and also flatten/2 which are defined in prolog library.

```<code>pre(X,Y):-
    preRequirement(X,Y).

preRequirement(X,[(X-List)|Y]):-
    findall(Z,prereqFor(X,Z),Res),
    flatten(Res,List),
    findPreOfPre(List,Y).

findPreOfPre([],[]).
findPreOfPre([H|T],[(H-L)|Result]):-
    findall(P,prereqFor(H,P),N),
    flatten(N,L),
    findPreOfPre(T,Result).
</code>```

Title: Prolog - Creating a list

Body:
Need a hand here creating a list.  I need to return all possible combinations of prerequisites of courses, including the prerequisites of prerequisites.

Here are some rules and facts that I need to use, (Some provided, some I've created).

prereqFor(engg233, []).
prereqFor(encm339, [engg233]).
prereqFor(cpsc217, []).
prereqFor(cpsc219, [cpsc217]).
prereqFor(cpsc231, []).
prereqFor(cpsc233, [cpsc231]).
prereqFor(math271, [X]) :-
   member(X, [math211, math213]).
prereqFor(math273, []).
prereqFor(cpsc319, [C]) :-
   member(C, [cpsc219, cpsc233, cpsc235, encm339]).
prereqFor(cpsc331, [M, C]) :-
   member(M, [math271, math273]),
   member(C, [cpsc219, cpsc233, cpsc235, encm339]).
prereqFor(cpsc335, [C]) :-
   member(C, [cpsc319, cpsc331]).

Now what I'm trying to do to accomplish this is two functions, one of which is a helper... And I can't seem to populate a list by using [H|T] or append... My current attempt:

allPrereqFor(Course, Prerequisites) :-
   prereqFor(Course, Prerequisites),
   creatingList(Course, Prerequisites, []).

creatingList(Course, Prerequisites, OnGoingList) :-
   append(Course, Prerequisites, myList).

I also tried something like:

allPrereqFor(Course, Prerequisites) :-
   prereqFor(Course, Prerequisites),
   creatingList(Prerequisites, []).

creatingList(Addition, OnGoingList) :-
   [Addition | OnGoingList].

I can't even get the most simple output before I even attempt a recursive case.

I have not listed every prereqFor function, but an example output would be:

| ?- allPrereqFor(cpsc331, X).
X = [cpsc217,cpsc219,math211,math271] ? ;
X = [cpsc231,cpsc233,math211,math271] ? ;
X = [consent235,cpsc235,math211,math271] ? ;
X = [encm339,engg233,math211,math271] ? ;

Another attempt at a solution...

allPrereqFor(Course,[],Result) :-   append([Course],[],Result).
allPrereqFor(Course, X,Result) :-   prereqFor(Course, Y),
                                    Y=[H|T],
                                    allPrereqFor(H,X,Result).

The trace:

| ?- allPrereqFor(cpsc331,X).
  1    1  Call: allPrereqFor(cpsc331,_23) ?
  1    1  Exit: allPrereqFor(cpsc331,[]) ?

X = [] ? ;
  1    1  Redo: allPrereqFor(cpsc331,[]) ?
  2    2  Call: prereqFor(cpsc331,_92) ?
  3    3  Call: member(_78,[math271,math273]) ?
  3    3  Exit: member(math271,[math271,math273]) ?
  4    3  Call: member(_80,[cpsc219,cpsc233,cpsc235,encm339]) ?
  4    3  Exit: member(cpsc219,[cpsc219,cpsc233,cpsc235,encm339]) ?
  2    2  Exit: prereqFor(cpsc331,[math271,cpsc219]) ?
  5    2  Call: allPrereqFor(math271,_23) ?
  5    2  Exit: allPrereqFor(math271,[]) ?
  1    1  Exit: allPrereqFor(cpsc331,[]) ?

X = [] ? ;
  1    1  Redo: allPrereqFor(cpsc331,[]) ?
  5    2  Redo: allPrereqFor(math271,[]) ?

When I trace I can see that it's recursively hitting all the right courses, but it just keeps outputting:

X = [] ?;

Body:
Finding the pre-requirements of pre-requirements can be done recursively. Well, you should make use of findall/3 and also flatten/2 which are defined in prolog library.

pre(X,Y):-
    preRequirement(X,Y).

preRequirement(X,[(X-List)|Y]):-
    findall(Z,prereqFor(X,Z),Res),
    flatten(Res,List),
    findPreOfPre(List,Y).

findPreOfPre([],[]).
findPreOfPre([H|T],[(H-L)|Result]):-
    findall(P,prereqFor(H,P),N),
    flatten(N,L),
    findPreOfPre(T,Result).


问:
Lodash _.set only if object exists
I am looking to set inner properties of an object only if they already exist. Lodash _.set will create the whole hierarchy if it does not exist.

Is there an easy way to do this ? (Without and if statement ?)

Snippet below:

const obj = {a: {b: 1}};

_.set(obj, 'a.b', 2);

console.log(obj); // Great !

_.set(obj, 'a.c', 1);

console.log(obj); // Great but not what I want. I would like c not to be set because it does not exist in the first place```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script></code>```

答:
you can try by this way

const obj = {a: {b: 1}};

_.set(obj, 'a.b', 2);

console.log(obj); // Great !
_.has(obj,'a.c')==true?_.set(obj, 'a.c', 1):""

console.log(obj); // Great but not what I want. I would like c not to be set because it does not exist in the first place```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script></code>```

Title: Lodash _.set only if object exists

Body:
you can try by this way

const obj = {a: {b: 1}};

_.set(obj, 'a.b', 2);

console.log(obj); // Great !
_.has(obj,'a.c')==true?_.set(obj, 'a.c', 1):""

console.log(obj); // Great but not what I want. I would like c not to be set because it does not exist in the first place

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


问:
What is this mean <aaa> in typescript?
Below is my code

```<code>public static postData(language: string, money: number): Promise<testModel.Item[]> {
    return ........
    });
}
</code>```

What is this code mean and Promise< testModel.Item[] > mean in here?

答:
It's called Generics

Because TypeScript is statically typing, then sometime you want a function, or class that can accept a customizable Type.

For Example:

```<code>class Stack<TItem> {
    push(item: TItem) {/...}
    pop() -> TItem {... }
}

then you can use Stack<string>, Stack<number>....
</code>```

In your application, applied to a Promise<TResult> where TResult is the expected type of the result of the promise.

Title: What is this mean <aaa> in typescript?

Body:
Below is my code

public static postData(language: string, money: number): Promise<testModel.Item[]> {
    return ........
    });
}

What is this code mean and Promise< testModel.Item[] > mean in here?

Body:
It's called Generics

Because TypeScript is statically typing, then sometime you want a function, or class that can accept a customizable Type.

For Example:

class Stack<TItem> {
    push(item: TItem) {/...}
    pop() -> TItem {... }
}

then you can use Stack<string>, Stack<number>....

In your application, applied to a Promise<TResult> where TResult is the expected type of the result of the promise.


问:
Push ViewController subviews beneath NavigationBar when translucent is True, Programmatically
This question asked to be implemented in Swift 4, iOS 11

Is there any way to make every subview of ViewController's view to be pushed down when it is under UINavigationBar?

If navigation bar is NOT TRANSLUCENT the subview is under it. This is what I want.

Desired Result

But when navigation bar is TRANSLUCENT the subview is lying under it. I dont want it. I want the subview is pushed down just be like if navigation bar is not translucent.

Undesired Result

I create the view programmatically :

```<code> class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.red
        let navBar = (self.parent as? UINavigationController)?.navigationBar
        navBar?.isTranslucent = true
    }

    func makeChildView() {
        let myframe = CGRect(x: 0, y: 10, width: self.view.frame.width, height:
    self.view.frame.height * 0.4)
        let view = UIView(frame: myframe)
        view.backgroundColor = UIColor.green
        self.view.addSubview(view)
    }
</code>```

Using Autolayout

I am able to solve this problem using autolayout. But I just want to know how to achieve this result without autolayout if possible. Is there any other approach?

答:
Swift 3.x

```<code>navBar?.isTranslucent = true
self.automaticallyAdjustsScrollViewInsets = false
</code>```

Add this line & you are good to go.

Body:
This question asked to be implemented in Swift 4, iOS 11

Is there any way to make every subview of ViewController's view to be pushed down when it is under UINavigationBar?

If navigation bar is NOT TRANSLUCENT the subview is under it. This is what I want.

Desired Result

But when navigation bar is TRANSLUCENT the subview is lying under it. I dont want it. I want the subview is pushed down just be like if navigation bar is not translucent.

Undesired Result

I create the view programmatically :

 class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.red
        let navBar = (self.parent as? UINavigationController)?.navigationBar
        navBar?.isTranslucent = true
    }

    func makeChildView() {
        let myframe = CGRect(x: 0, y: 10, width: self.view.frame.width, height:
    self.view.frame.height * 0.4)
        let view = UIView(frame: myframe)
        view.backgroundColor = UIColor.green
        self.view.addSubview(view)
    }

Using Autolayout

I am able to solve this problem using autolayout. But I just want to know how to achieve this result without autolayout if possible. Is there any other approach?

Body:
Swift 3.x

navBar?.isTranslucent = true
self.automaticallyAdjustsScrollViewInsets = false

Add this line & you are good to go.


问:
Unable to download pdf file in Chrome Browser using Selenium java
My use case: I have to read data from a pdf than opens in chrome browser and check if some specific data is present in the pdf or not.

As I could not achieve the above I thought of downloading the file on my computer and use PDFbox for the verification.
I created a chrome profile with settings to download the pdf file directly(Settings>Content settings>PDF documents).
I have set it as chrome options in my selenium script.
The test works but when the pdf gets opened it does not start downloading.
The PDF file opens in my chrome browser. Chrome version: 62.0.3202.94

I got the chrome profile path from:

```<code>chrome://version/
</code>```

I am not sure what went wrong.
Please help.

```<code>    @Before
      public void beforeTest() throws MalformedURLException{

          System.setProperty("webdriver.chrome.driver","path to chromedriver\\chromedriver.exe");
          ChromeOptions options = new ChromeOptions();
          String chromeProfilePath="path to custom chrome profile";
          options.addArguments("user-data-dir="+chromeProfilePath);
          HashMap<String, Object> chromeOptionsMap = new HashMap<String, Object>();
          DesiredCapabilities cap = DesiredCapabilities.chrome();
          cap.setCapability(ChromeOptions.CAPABILITY, chromeOptionsMap);
          cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
          cap.setCapability(ChromeOptions.CAPABILITY, options);
          driver = new ChromeDriver(cap);
          //Browser is maximized
          driver.manage().window().maximize();
}
</code>```

答:
You should disable the pdf viewer plugin to inhibit the pdf file to open in chrome. Add this chrome option. </p>

```<code>ChromeOptions options = new ChromeOptions();
Map<String, Object> preferences = new Hashtable<String, Object>();
options.setExperimentalOption("prefs", preferences);

// disable flash and the PDF viewer
preferences.put("plugins.plugins_disabled", new String[] {
    "Chrome PDF Viewer"
});

// launch the browser and navigate to the page
ChromeDriver driver = new ChromeDriver(options);
</code>```

Body:
My use case: I have to read data from a pdf than opens in chrome browser and check if some specific data is present in the pdf or not.

As I could not achieve the above I thought of downloading the file on my computer and use PDFbox for the verification.
I created a chrome profile with settings to download the pdf file directly(Settings>Content settings>PDF documents).
I have set it as chrome options in my selenium script.
The test works but when the pdf gets opened it does not start downloading.
The PDF file opens in my chrome browser. Chrome version: 62.0.3202.94

I got the chrome profile path from:

chrome://version/

I am not sure what went wrong.
Please help.

    @Before
      public void beforeTest() throws MalformedURLException{

          System.setProperty("webdriver.chrome.driver","path to chromedriver\\chromedriver.exe");
          ChromeOptions options = new ChromeOptions();
          String chromeProfilePath="path to custom chrome profile";
          options.addArguments("user-data-dir="+chromeProfilePath);
          HashMap<String, Object> chromeOptionsMap = new HashMap<String, Object>();
          DesiredCapabilities cap = DesiredCapabilities.chrome();
          cap.setCapability(ChromeOptions.CAPABILITY, chromeOptionsMap);
          cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
          cap.setCapability(ChromeOptions.CAPABILITY, options);
          driver = new ChromeDriver(cap);
          //Browser is maximized
          driver.manage().window().maximize();
}

Body:
You should disable the pdf viewer plugin to inhibit the pdf file to open in chrome. Add this chrome option.

ChromeOptions options = new ChromeOptions();
Map<String, Object> preferences = new Hashtable<String, Object>();
options.setExperimentalOption("prefs", preferences);

// disable flash and the PDF viewer
preferences.put("plugins.plugins_disabled", new String[] {
    "Chrome PDF Viewer"
});

// launch the browser and navigate to the page
ChromeDriver driver = new ChromeDriver(options);


问:
Testing a class with HttpContext.Current.Session in ASP.NET MVC
I'm adding some tests to a class that uses HttpContext.Current.Session internally and we are porting to ASP.NET MVC. My class looks like this:

```<code>class Foo
{
    public void foo()
    {
        HttpContext.Current.Session["foo"] = "foo";
    }
}
</code>```

I thought to change it like this:

```<code>class Foo
{
    IHttpSessionState session;

    public Foo() : this(HttpContext.Current.Session) {}

    public Foo(IHttpSessionState session)
    {
        m_session = session;
    }

    public void foo()
    {
        m_session["foo"] = "foo";
    }
}
</code>```

The problem is with the default constructor. I can't pass the old classes since they don't implement the new ASP.NET MVC interfaces.

Is there anyway to obtain the instances that implement IHttpSessionState in the default constructor?

Thanks

答:
Try this, it used the IHttpSessionState wrapper that the MVC framework uses.</p>

```<code>class Foo
{
    // member variable set by constructor
    IHttpSessionState m_session;

    // if no session is passed it attempts to create a new session state wrapper from the current session
    public Foo() : this(new HttpSessionStateWrapper(HttpContext.Current.Session)) {}

    public Foo(IHttpSessionState session)
    {
        m_session = session;
    }

    public void foo()
    {
        m_session["foo"] = "foo";
    }
}
</code>```

OwnerDisplayName: John Voight

LastEditorDisplayName: Fabian Steeg

Body:
I'm adding some tests to a class that uses HttpContext.Current.Session internally and we are porting to ASP.NET MVC. My class looks like this:

class Foo
{
    public void foo()
    {
        HttpContext.Current.Session["foo"] = "foo";
    }
}

I thought to change it like this:

class Foo
{
    IHttpSessionState session;

    public Foo() : this(HttpContext.Current.Session) {}

    public Foo(IHttpSessionState session)
    {
        m_session = session;
    }

    public void foo()
    {
        m_session["foo"] = "foo";
    }
}

The problem is with the default constructor. I can't pass the old classes since they don't implement the new ASP.NET MVC interfaces.

Is there anyway to obtain the instances that implement IHttpSessionState in the default constructor?

Thanks

Body:
Try this, it used the IHttpSessionState wrapper that the MVC framework uses.

class Foo
{
    // member variable set by constructor
    IHttpSessionState m_session;

    // if no session is passed it attempts to create a new session state wrapper from the current session
    public Foo() : this(new HttpSessionStateWrapper(HttpContext.Current.Session)) {}

    public Foo(IHttpSessionState session)
    {
        m_session = session;
    }

    public void foo()
    {
        m_session["foo"] = "foo";
    }
}

OwnerDisplayName: Nick Berardi


问:
Fast element access for multi-dimensional representation of contiguous array
I have a multi-dimensional array represented contiguously in memory. I want to keep this representation hidden and just let the user access the array elements as if it were a multi-dimensional one: e.g. my_array[0][3][5] or my_array(0,3,5) or something similar. The dimensions of the object are not determined until runtime, but the object is created with a type that specifies how many dimensions it has. This element look-up will need to be called billions of times, and so should hopefully involve minimal overhead for each call.

I have looked at similar questions but not really found a good solution. Using the [] operator requires the creation of N-1 dimensional objects, which is fine for multi-dimensional structures like vectors-of-vectors because the object already exists, but for a contiguous array it seems like it would get convoluted very quickly and require some kind of slicing through the original array.

I have also looked at overloading (), which seems more promising, but requires specifying the number of arguments, which will vary depending upon the number of dimensions of the array. I have thought about using list initialization or vectors, but wanted to avoid instantiating objects.

I am only a little familiar with templates and figure that there should be some way with C++'s majestic template powers to specify a unique overloading of () for arrays with different types (e.g. different numbers of dimensions). But I have only used templates in really basic generic cases like making a function use both float and double.

I am imagining something like this:

```<code>template<typename TDim>
class MultiArray {
public:
  MultiArray() {} //build some things
  ~MultiArray() {} //destroy some things

  // The number of arguments would be == to TDim for the instantiated class
  float& operator() (int dim1, int dim2, ...) {
    //convert to contiguous index and return ref to element
    // I believe the conversion equation is something like:
    // dim1 + Maxdim1 * ( dim2 + MaxDim2 * ( dim3 + MaxDim3 * (...)))
  }

private:
  vector<float> internal_array;
  vector<int> MaxDimX; // Each element says how large each corresponding dim is.
};
</code>```

So if I initialize this class and attempted to access an element, it would look something like this:

```<code>my_array = MultiArray<4>();
element = my_array(2,5,4,1);
</code>```

How might I go about doing this using templates? Is this even possible?

答:
If you can use C++17, so variadic template folding, and row major order, I suppose you can write something like (caution: not tested)

```<code>template <template ... Args>
float & operator() (Args ... dims)
 {
   static_assert( sizeof...(Args) == TDim , "wrong number of indexes" );
   // or SFINAE enable instead of static_assert()

   std::size_t pos { 0U };
   std::size_t i   { 0U };

   ( pos *= MaxDimX[i++], pos += dims, ... );

   return internal_array[pos];
 }
</code>```

OTPS (Off Topic Post Scriptum): your MaxDimX, if I understand correctly, is a vector of dimensions; so should be an unsigned integer, non a signed int; usually, for indexes, is used std::size_t [see Note 1].

OTPS 2: if you know compile time the number of dimensions (TDim, right?) instead of a std::vector, I suggest the use of a std::array; I mean

```<code>std::array<std::size_t, TDim>  MaxDimX;
</code>```

-- EDIT --

If you can't use C++17, you can use the trick of the unused array initialization to obtain something similar.

I mean

```<code>template <template ... Args>
float & operator() (Args ... dims)
 {
   using unused = int[];

   static_assert( sizeof...(Args) == TDim , "wrong number of indexes" );
   // or SFINAE enable instead of static_assert()

   std::size_t pos { 0U };
   std::size_t i   { 0U };

   (void)unused { (pos *= MaxDimX[i++], pos += dims, 0) ... };

   return internal_array[pos];
 }
</code>```

Note 1: as pointed by Julius, the use of a signed or an unsigned integer for indexes is controversial.

So I try to explain better why I suggest to use an unsigned value (std::size_t, by example) for they.

The point is that (as far I know) all Standard Template Library is designed to use unsigned integer for index values. You can see it by the value returned by the size() method and by the fact that access methods that receive an index, as at() or operator[], receive an unsigned value.

Right or wrong, the language itself is designed to return a std::size_t from the old sizeof() and from more recent variadic sizeof...(). The same class std::index_sequence is an alias for std::integer_sequence with a fixed unsigned, again std::size_t, type.

In a world designed to use unsigned integers for indexes, the use of a signed integer for they it's possible but, IMHO, dangerous (because error prone).

Body:
I have a multi-dimensional array represented contiguously in memory. I want to keep this representation hidden and just let the user access the array elements as if it were a multi-dimensional one: e.g. my_array[0][3][5] or my_array(0,3,5) or something similar. The dimensions of the object are not determined until runtime, but the object is created with a type that specifies how many dimensions it has. This element look-up will need to be called billions of times, and so should hopefully involve minimal overhead for each call.

I have looked at similar questions but not really found a good solution. Using the [] operator requires the creation of N-1 dimensional objects, which is fine for multi-dimensional structures like vectors-of-vectors because the object already exists, but for a contiguous array it seems like it would get convoluted very quickly and require some kind of slicing through the original array.

I have also looked at overloading (), which seems more promising, but requires specifying the number of arguments, which will vary depending upon the number of dimensions of the array. I have thought about using list initialization or vectors, but wanted to avoid instantiating objects.

I am only a little familiar with templates and figure that there should be some way with C++'s majestic template powers to specify a unique overloading of () for arrays with different types (e.g. different numbers of dimensions). But I have only used templates in really basic generic cases like making a function use both float and double.

I am imagining something like this:

template<typename TDim>
class MultiArray {
public:
  MultiArray() {} //build some things
  ~MultiArray() {} //destroy some things

  // The number of arguments would be == to TDim for the instantiated class
  float& operator() (int dim1, int dim2, ...) {
    //convert to contiguous index and return ref to element
    // I believe the conversion equation is something like:
    // dim1 + Maxdim1 * ( dim2 + MaxDim2 * ( dim3 + MaxDim3 * (...)))
  }

private:
  vector<float> internal_array;
  vector<int> MaxDimX; // Each element says how large each corresponding dim is.
};

So if I initialize this class and attempted to access an element, it would look something like this:

my_array = MultiArray<4>();
element = my_array(2,5,4,1);

How might I go about doing this using templates? Is this even possible?

Body:
If you can use C++17, so variadic template folding, and row major order, I suppose you can write something like (caution: not tested)

template <template ... Args>
float & operator() (Args ... dims)
 {
   static_assert( sizeof...(Args) == TDim , "wrong number of indexes" );
   // or SFINAE enable instead of static_assert()

   std::size_t pos { 0U };
   std::size_t i   { 0U };

   ( pos *= MaxDimX[i++], pos += dims, ... );

   return internal_array[pos];
 }

OTPS (Off Topic Post Scriptum): your MaxDimX, if I understand correctly, is a vector of dimensions; so should be an unsigned integer, non a signed int; usually, for indexes, is used std::size_t [see Note 1].

OTPS 2: if you know compile time the number of dimensions (TDim, right?) instead of a std::vector, I suggest the use of a std::array; I mean

std::array<std::size_t, TDim>  MaxDimX;

-- EDIT --

If you can't use C++17, you can use the trick of the unused array initialization to obtain something similar.

I mean

template <template ... Args>
float & operator() (Args ... dims)
 {
   using unused = int[];

   static_assert( sizeof...(Args) == TDim , "wrong number of indexes" );
   // or SFINAE enable instead of static_assert()

   std::size_t pos { 0U };
   std::size_t i   { 0U };

   (void)unused { (pos *= MaxDimX[i++], pos += dims, 0) ... };

   return internal_array[pos];
 }

Note 1: as pointed by Julius, the use of a signed or an unsigned integer for indexes is controversial.

So I try to explain better why I suggest to use an unsigned value (std::size_t, by example) for they.

The point is that (as far I know) all Standard Template Library is designed to use unsigned integer for index values. You can see it by the value returned by the size() method and by the fact that access methods that receive an index, as at() or operator[], receive an unsigned value.

Right or wrong, the language itself is designed to return a std::size_t from the old sizeof() and from more recent variadic sizeof...(). The same class std::index_sequence is an alias for std::integer_sequence with a fixed unsigned, again std::size_t, type.

In a world designed to use unsigned integers for indexes, the use of a signed integer for they it's possible but, IMHO, dangerous (because error prone).


问:
How to change Picker font size using Xamarin forms ios PickerRenderer?
For Android i was able to do it this way

```<code>protected override void OnElementChanged(ElementChangedEventArgs<Picker> e)
{
    base.OnElementChanged(e);
    if (e.OldElement == null && e.NewElement == null) return;
    Control.TextSize = 14f;
    Control.SetTextColor(Color.FromHex(Constants.Color.SLATE_GRAY).ToAndroid());
}
</code>```

Is there any way for ios using Xamarin.Forms.Platform.ios.PickerRenderer?
I could see an example in ios. link. But now sure how to convert it into Xamarin.

答:
By clicking 'Go to Definition' ,you can find PickerRenderer inherit ViewRenderer<Picker, UITextField>

so we just set Font on Control , refer to the following code

```<code>protected override void OnElementChanged(ElementChangedEventArgs<Picker> e)
{
    base.OnElementChanged(e);

    if(Control != null)
    {
        Control.TextColor = UIColor.Red;
        Control.Font = UIFont.SystemFontOfSize(30);
    }
}
</code>```

Body:
For Android i was able to do it this way

protected override void OnElementChanged(ElementChangedEventArgs<Picker> e)
{
    base.OnElementChanged(e);
    if (e.OldElement == null && e.NewElement == null) return;
    Control.TextSize = 14f;
    Control.SetTextColor(Color.FromHex(Constants.Color.SLATE_GRAY).ToAndroid());
}

Is there any way for ios using Xamarin.Forms.Platform.ios.PickerRenderer?
I could see an example in ios. link. But now sure how to convert it into Xamarin.

Body:
By clicking 'Go to Definition' ,you can find PickerRenderer inherit ViewRenderer<Picker, UITextField>

so we just set Font on Control , refer to the following code

protected override void OnElementChanged(ElementChangedEventArgs<Picker> e)
{
    base.OnElementChanged(e);

    if(Control != null)
    {
        Control.TextColor = UIColor.Red;
        Control.Font = UIFont.SystemFontOfSize(30);
    }
}


问:
Optimal performance for two dim array to datatable conversion
I was looking for an optimized method to convert a square array of type

double[ , ]

to DataTable

I looked up over the internet and couldn't find a way faster than the currently implemented in my method which depends on two nested for loops.

The problem is that the performance is very bad. My input array could be any where from 500 to 15000 elements in each dimension. (Math can be scary)...

This means that it could take ages for the conversion to complete with the current method.

I was thinking about using some unmanaged code or even assembly code to improve the performance but I didn't know how to do it..

My Current code is this...

```<code>// helper method to get row as a string array
private static string[] GetRowFromArray(double[,] array, int column )

{

int dim = array.GetUpperBound(0) +1;

string[] row = new string[dim];

for(int i = 0; i < dim; i++)

{

    row[i] = array[i, column].ToString();

}

return row;

}

//the static extension method used to convert the array to datatable

public static DataTable ToDataTable(this double[,] array)

{

DataTable dt = new DataTable();

int rowsCount = array.GetUpperBound(0) + 1;

int colsCount = array.GetUpperBound(1) + 1;

int i = 0;

while (i < colsCount)

{

   dt.Columns.Add(); i++;

}

int ii = 0;

while (ii < rowsCount)

{

    string[] a = GetRowFromArray(array, ii);

    dt.Rows.Add(a);

    ii++;

}

return dt;

}
</code>```

Any ideas on how can we optimize this to make it run faster.

Just a side note, the array is square array, so  ColumnsCount = RowsCount

And so many thanks for any help.

答:
Well, you could parallelize it. In the sample code, the number of dimensions tasks are created and run in parallel.

```<code>    private static string[] GetRowFromArray(double[,] array, int column)
    {
        int dim = array.GetUpperBound(0) + 1;
        string[] row = new string[dim];

        //for (int i = 0; i < dim; i++)
        Parallel.For(0, dim, i =>
        {
            row[i] = array[i, column].ToString();
        });

        return row;
    }
</code>```

You can control the level of parallelism by

```<code>        ParallelOptions options = new ParallelOptions();
        options.MaxDegreeOfParallelism = dim;

        Parallel.For(0, dim, options, i =>
        {
            row[i] = array[i, column].ToString();
        });
</code>```

https://msdn.microsoft.com/en-us/library/system.threading.tasks.parallel.for(v=vs.110).aspx

Body:
I was looking for an optimized method to convert a square array of type

double[ , ]

to DataTable

I looked up over the internet and couldn't find a way faster than the currently implemented in my method which depends on two nested for loops.

The problem is that the performance is very bad. My input array could be any where from 500 to 15000 elements in each dimension. (Math can be scary)...

This means that it could take ages for the conversion to complete with the current method.

I was thinking about using some unmanaged code or even assembly code to improve the performance but I didn't know how to do it..

My Current code is this...

// helper method to get row as a string array
private static string[] GetRowFromArray(double[,] array, int column )

{

int dim = array.GetUpperBound(0) +1;

string[] row = new string[dim];

for(int i = 0; i < dim; i++)

{

    row[i] = array[i, column].ToString();

}

return row;

}

//the static extension method used to convert the array to datatable

public static DataTable ToDataTable(this double[,] array)

{

DataTable dt = new DataTable();

int rowsCount = array.GetUpperBound(0) + 1;

int colsCount = array.GetUpperBound(1) + 1;

int i = 0;

while (i < colsCount)

{

   dt.Columns.Add(); i++;

}

int ii = 0;

while (ii < rowsCount)

{

    string[] a = GetRowFromArray(array, ii);

    dt.Rows.Add(a);

    ii++;

}

return dt;

}

Any ideas on how can we optimize this to make it run faster.

Just a side note, the array is square array, so  ColumnsCount = RowsCount

And so many thanks for any help.

Body:
Well, you could parallelize it. In the sample code, the number of dimensions tasks are created and run in parallel.

    private static string[] GetRowFromArray(double[,] array, int column)
    {
        int dim = array.GetUpperBound(0) + 1;
        string[] row = new string[dim];

        //for (int i = 0; i < dim; i++)
        Parallel.For(0, dim, i =>
        {
            row[i] = array[i, column].ToString();
        });

        return row;
    }

You can control the level of parallelism by

        ParallelOptions options = new ParallelOptions();
        options.MaxDegreeOfParallelism = dim;

        Parallel.For(0, dim, options, i =>
        {
            row[i] = array[i, column].ToString();
        });

https://msdn.microsoft.com/en-us/library/system.threading.tasks.parallel.for(v=vs.110).aspx


问:
.show() and .toggle() will not reveal final game screen in trivia game

I have gone over and over the code. I've tried to show the final game screen (result-screen) with JQuery and then again by defining global variables. I have called it as part of another function and within its own function. No combination I come up with is displaying my final result-screen.

```<code>var welcome = $("#welcome-screen")
var gameOver = $("#result-screen")
var game = $("#game-screen")

var playerInteract = {
    correctAnswers: 0,
    incorrectAnswers: 0,
    unanswered: 8,
    seconds: 10,
    //done: false,

    welcome: function() {
        gameOver.toggle();
        game.hide();
    },

    initiate: function() {
        welcome.hide();
        game.show();
        playerInteract.timer();
    },

    timer: function() {
        var windowTimeout = setTimeout(function() {
            //playerInteract.gameOver()
            game.hide()
               playerInteract.answerCheck()
               playerInteract.gameOverLoad()
            },  10000);
        var intervalVariable = setInterval(playerInteract.decrement, 1000);
        var seconds = playerInteract.seconds;

    },

    decrement: function () {
        if (playerInteract.seconds >= 2) {
                playerInteract.seconds--;
                console.log("seconds: " + playerInteract.seconds);
                $("#countdown").text(playerInteract.seconds);
            }
    },
   gameOverLoad: function() {
       gameOver.show();
       console.log("gameover");
   }

};

window.onload = playerInteract.welcome;

$("#start-button").on("click", function(event) {
    //event.preventDefault()
    playerInteract.initiate()
});

$("#countdown").text(playerInteract.seconds);
</code>```

<----HTML---->

```<code><div id="welcome-screen" class="container">

    <img id="header" src="assets/images/header-image.png" alt="Stephen King Killer Trivia">
    <h1>Take a stab at it!</h1>
    <button id=start-button><h2>STAB!</h2></button>

</div>

<div id="game-screen" class="container">
    <img id="header" src="assets/images/header-image.png" alt="Stephen King Killer Trivia">

    <h2>Take a stab at it!</h2>
    <h3>Time Remaining: <div id="countdown"></div></h3>

    <img id="penny" src="assets/images/penny.png" alt="Pennywise the clown.">

    <h4>What's the name of the killer clown in Stephen King's novel, <em>IT</em>?</h4>

        <div class="answer-boxes">
            <input type="radio" name="q1" class="radio-button" id="wrongA"> Torchy
            <input type="radio" name="q1" class="radio-button" id="wrongB"> Quarterdumb
            <input type="radio" name="q1" class="radio-button" id="correct1"> Pennywise
            <input type="radio" name="q1" class="radio-button" id="wrongC"> Boinko
        </div>

    <img id="georgie" src="assets/images/georgie.png" alt="Georgie from 'It'">

    <h4>Which King protagonist went crazy and killed<br> most of her classmates and teachers during prom?</h4>

    <div class="answer-boxes">
        <input type="radio" name="q2" class="radio-button" id="wrongD"> Sandy
        <input type="radio" name="q2" class="radio-button" id="wrongE"> Dolores
        <input type="radio" name="q2" class="radio-button" id="wrongF"> Sherrie
        <input type="radio" name="q2" class="radio-button" id="correct2"> Carrie
        </div>

    <h4>Stephen King regularly contributed to <em>Dave's Rag</em> in high school.</h4>

    <div class="answer-boxes">
        <input type="radio" name="q3" class="radio-button" id="correct3"> True
        <input type="radio" name="q3" class="radio-bitton" id="wrongG"> False
        </div>

    <h4>What year and model car was featured <br>in the movie <em>Christine</em> based on a Stephen King book?</h4>

    <div class="answer-boxes">
        <input type="radio" name="q4" class="radio-button" id="wrongH"> 1962 Ford Mustang
        <input type="radio" name="q4" class="radio-button" id="wrongI"> 1957 Chevy Chevelle
        <input type="radio" name="q4" class="radio-button" id="wrongJ"> 1951 Jaquar XK 120
        <input type="radio" name="q4" class="radio-button" id="corrcet4"> 1958 Plymouth Fury
        </div>

    <h4>Mike Hanlon made seven phone calls in Stephen King's novel, <em>IT</em>.</h4>

    <div class="answer-boxes">
        <input type="radio" name="q5" class="radio-button" id="wrongK"> True
        <input type="radio" name="q5" class="radio-button" id="correct5"> False
    </div>

    <h4>What's the name of Stephen King's western/fantasy saga?</h4>

    <div class="answer-boxes">
        <input type="radio" name="q6"class="radio-button" id="correct6"> <em>The Dark Tower</em>
        <input type="radio" name="q6"class="radio-button" id="wrongL"> <em>The Darkest Hour</em>
        <input type="radio" name="q6"class="radio-button" id="wrongM"> <em>The Dark Knight</em>
        <input type="radio" name="q6"class="radio-button" id="wrongN"> <em>The Dark Travels</em>
    </div>

    <h4>Which of the below is a Stephen King pseudonym?</h4>

    <div class="answer-boxes">
        <input type="radio" name="q7" class="radio-button" id="wrongO"> Dick Hallorann
        <input type="radio" name="q7" class="radio-button" id="correct7"> Richard Bachman
        <input type="radio" name="q7" class="radio-button" id="wrongP"> Sam Paul
        <input type="radio" name="q7" class="radio-button" id="wrongQ"> Benjamin Sanders
    </div>

    <h4>One of Stephen King's jobs prior to publication was as a high school teacher.</h4>

    <div class="answer-boxes">
        <input type="radio" name="q8" class="radio-button" id="correct8"> True
        <input type="radio" name="q8" class="radio-button" id="wrongR"> Flase
    </div>

<div id="result-screen" class="container">

    <img id="header" src="assets/images/header-image.png" alt="Stephen King Killer Trivia">

    <h1>All Done!</h1>
    <h4>Correct Answers: <div id="correct-answers"></div></h4>
    <h4>Incorrect Answers: <div id="incorrect-answers"></div></h4>
    <h4>Unanswered: <div id="unanswered"></div></h4>

</div>
</code>```

The only code I have eliminated from my JS is the answerCheck function.

After the setTimeout concludes, I want the game screen to hide and the result screen to show. Hide, show, toggle all work in the code up until the timeout finishes.

The game screen hides, leaving the background the only thing visible. The console.log to print gameover to the log runs. No errors in the console.

答: There is no error and it is working now after you had made those changes.</p>

Body:
I have gone over and over the code. I've tried to show the final game screen (result-screen) with JQuery and then again by defining global variables. I have called it as part of another function and within its own function. No combination I come up with is displaying my final result-screen.

var welcome = $("#welcome-screen")
var gameOver = $("#result-screen")
var game = $("#game-screen")

var playerInteract = {
    correctAnswers: 0,
    incorrectAnswers: 0,
    unanswered: 8,
    seconds: 10,
    //done: false,

    welcome: function() {
        gameOver.toggle();
        game.hide();
    },

    initiate: function() {
        welcome.hide();
        game.show();
        playerInteract.timer();
    },

    timer: function() {
        var windowTimeout = setTimeout(function() {
            //playerInteract.gameOver()
            game.hide()
               playerInteract.answerCheck()
               playerInteract.gameOverLoad()
            },  10000);
        var intervalVariable = setInterval(playerInteract.decrement, 1000);
        var seconds = playerInteract.seconds;

    },

    decrement: function () {
        if (playerInteract.seconds >= 2) {
                playerInteract.seconds--;
                console.log("seconds: " + playerInteract.seconds);
                $("#countdown").text(playerInteract.seconds);
            }
    },
   gameOverLoad: function() {
       gameOver.show();
       console.log("gameover");
   }

};

window.onload = playerInteract.welcome;

$("#start-button").on("click", function(event) {
    //event.preventDefault()
    playerInteract.initiate()
});

$("#countdown").text(playerInteract.seconds);

<----HTML---->

Take a stab at it!

    <button id=start-button>
STAB!
</button>

Take a stab at it!

Time Remaining:

What's the name of the killer clown in Stephen King's novel, IT?

            <input type="radio" name="q1" class="radio-button" id="wrongA"> Torchy
            <input type="radio" name="q1" class="radio-button" id="wrongB"> Quarterdumb
            <input type="radio" name="q1" class="radio-button" id="correct1"> Pennywise
            <input type="radio" name="q1" class="radio-button" id="wrongC"> Boinko

Which King protagonist went crazy and killed
 most of her classmates and teachers during prom?

        <input type="radio" name="q2" class="radio-button" id="wrongD"> Sandy
        <input type="radio" name="q2" class="radio-button" id="wrongE"> Dolores
        <input type="radio" name="q2" class="radio-button" id="wrongF"> Sherrie
        <input type="radio" name="q2" class="radio-button" id="correct2"> Carrie

Stephen King regularly contributed to Dave's Rag in high school.

        <input type="radio" name="q3" class="radio-button" id="correct3"> True
        <input type="radio" name="q3" class="radio-bitton" id="wrongG"> False

What year and model car was featured
in the movie Christine based on a Stephen King book?

        <input type="radio" name="q4" class="radio-button" id="wrongH"> 1962 Ford Mustang
        <input type="radio" name="q4" class="radio-button" id="wrongI"> 1957 Chevy Chevelle
        <input type="radio" name="q4" class="radio-button" id="wrongJ"> 1951 Jaquar XK 120
        <input type="radio" name="q4" class="radio-button" id="corrcet4"> 1958 Plymouth Fury

Mike Hanlon made seven phone calls in Stephen King's novel, IT.

        <input type="radio" name="q5" class="radio-button" id="wrongK"> True
        <input type="radio" name="q5" class="radio-button" id="correct5"> False

What's the name of Stephen King's western/fantasy saga?

        <input type="radio" name="q6"class="radio-button" id="correct6"> The Dark Tower
        <input type="radio" name="q6"class="radio-button" id="wrongL"> The Darkest Hour
        <input type="radio" name="q6"class="radio-button" id="wrongM"> The Dark Knight
        <input type="radio" name="q6"class="radio-button" id="wrongN"> The Dark Travels

Which of the below is a Stephen King pseudonym?

        <input type="radio" name="q7" class="radio-button" id="wrongO"> Dick Hallorann
        <input type="radio" name="q7" class="radio-button" id="correct7"> Richard Bachman
        <input type="radio" name="q7" class="radio-button" id="wrongP"> Sam Paul
        <input type="radio" name="q7" class="radio-button" id="wrongQ"> Benjamin Sanders

One of Stephen King's jobs prior to publication was as a high school teacher.

        <input type="radio" name="q8" class="radio-button" id="correct8"> True
        <input type="radio" name="q8" class="radio-button" id="wrongR"> Flase

All Done!

Correct Answers:

Incorrect Answers:

Unanswered:

The only code I have eliminated from my JS is the answerCheck function.

After the setTimeout concludes, I want the game screen to hide and the result screen to show. Hide, show, toggle all work in the code up until the timeout finishes.

The game screen hides, leaving the background the only thing visible. The console.log to print gameover to the log runs. No errors in the console.


问:
Get min and max of unsorted list
I am hypothetically given an unsorted list of x numbers and I would like to find the min. and max. numbers in the list.

Now based on the research I have done the most efficient sorting method seems to be quick sort.

答:
Sorting is at best an O(N log N) operation. In order to sort a list, you have to look at each value at least once O(N)

It would be faster to just loop through the array and keep track of the smallest, and biggest numbers

```<code>        int[] unordered = { 5, 9, 4, 2, 6, 4 };
        int min=0, max=0;

        for (int i = 0; i < unordered.Length; i++)
        {
            if (min > unordered[i]) min = unordered[i];
            if (max < unordered[i]) max = unordered[i];
        }
</code>```

Title: Get min and max of unsorted list

Body:
Sorting is at best an O(N log N) operation. In order to sort a list, you have to look at each value at least once O(N)

It would be faster to just loop through the array and keep track of the smallest, and biggest numbers

        int[] unordered = { 5, 9, 4, 2, 6, 4 };
        int min=0, max=0;

        for (int i = 0; i < unordered.Length; i++)
        {
            if (min > unordered[i]) min = unordered[i];
            if (max < unordered[i]) max = unordered[i];
        }


问:
python: how to remove brackets of a nested list within a list
I have a list of different arrays of different sizes

```<code>list = [array1,array2,array3,array4,array5]
</code>```

now i want to use split function to split one of the array

```<code>newlist = [array1, np.vsplit(array2,3), array3,array4,array5]
</code>```

to make a new list

```<code>newlist = [array1,array21,array22,array23,array3,array4,array5]
</code>```

HOWEVER, what I got is always containing a list inside the newlist

```<code>newlist = [array1,[array21,array22,array23],array3,array4,array5]
</code>```

how can i remove the brackets and generate what i want?

I believe there should be a very simple solution, but i have tried searching and couldn't get a answer.

答:
You can directly add lists up by wrapping the remaining elements in separate lists first:

```<code>[array1] + np.vsplit(array2,3) + [array3, array4, array5]
</code>```

or better you can slice the list:

```<code>list[:1] + np.vsplit(list[1], 3) + list[2:]
</code>```

Body:
I have a list of different arrays of different sizes

list = [array1,array2,array3,array4,array5]

now i want to use split function to split one of the array

newlist = [array1, np.vsplit(array2,3), array3,array4,array5]

to make a new list

newlist = [array1,array21,array22,array23,array3,array4,array5]

HOWEVER, what I got is always containing a list inside the newlist

newlist = [array1,[array21,array22,array23],array3,array4,array5]

how can i remove the brackets and generate what i want?

I believe there should be a very simple solution, but i have tried searching and couldn't get a answer.

Body:
You can directly add lists up by wrapping the remaining elements in separate lists first:

[array1] + np.vsplit(array2,3) + [array3, array4, array5]

or better you can slice the list:

list[:1] + np.vsplit(list[1], 3) + list[2:]


问:
Escaping meta chars in slides apps script not working
I want to match 212*235 as plain text in Slides service Text Range. Hence I used

var trs = text.find('212*234');
var trs = text.find(/212*234/);

also tried with

var re = new RegExp("212*234", "gi");
var trs = text.find(re);

but none of them worked.

https://developers.google.com/apps-script/reference/slides/text-range#findpattern

Is this might be a bug or intentional?

答:
You want two backslashes before the *, as in:

```<code>var s = SlidesApp.getActivePresentation().getSlides()[0].getShapes()[0];
Logger.log(s.getText().find('212\\*235')[0].asString());
</code>```

Body:
You want two backslashes before the *, as in:

var s = SlidesApp.getActivePresentation().getSlides()[0].getShapes()[0];
Logger.log(s.getText().find('212\\*235')[0].asString());


Title: Replace a char which in the string with another char

Body:
I want use the date format in list2 to list 1

list1 = ['1628 04 19 21:10:32', '1752 06 15 20:05:36', '1775 04 18 09:15:56', '1865 04 14 14:54:36', '1876 05 10 15:36:27', '1879 10 22 03:45:15', '2010 09 29 04:46:28']

list2 = ['1628  4 19 21:10:32', '1752  6 15 20:05:36', '1775  4 18 09:15:56', '1865  4 14 14:54:36', '1876  5 10 15:36:27', '1879 10 22 03:45:15', '2010  9 29 04:46:28']

Just replace the zero in single number months with space

Body:
Try this:

>>> import re
>>> list1 = ['1628 04 19 21:10:32', '1752 06 15 20:05:36', '1775 04 18 09:15:56', '1865 04 14 14:54:36', '1876 05 10 15:36:27', '1879 10 22 03:45:15', '2010 09 29 04:46:28']
>>> [re.sub(r'(\d{4} )0',r'\1 ',x) for x in list1]
['1628  4 19 21:10:32', '1752  6 15 20:05:36', '1775  4 18 09:15:56', '1865  4 14 14:54:36', '1876  5 10 15:36:27', '1879 10 22 03:45:15', '2010  9 29 04:46:28']


问:
body shrinks more than 100% on mobile
When I resize the browser, it works fine, but on mobile and when I inspect on mobile size the body starts to shrink. The more I reduce, the more the body shrinks.

Any Ideas?

This is my website: http://www.mydeepwellbeing.com/

答:
Try this:

```<code>div.full-background{
   background: url(images/bg.jpg) no-repeat center center fixed;
   -webkit-background-size: cover;
   -moz-background-size: cover;
   -o-background-size: cover;
   background-size: cover;
}
</code>```

Might be a little help ^_^

Title: body shrinks more than 100% on mobile

Body:
Try this:

div.full-background{
   background: url(images/bg.jpg) no-repeat center center fixed;
   -webkit-background-size: cover;
   -moz-background-size: cover;
   -o-background-size: cover;
   background-size: cover;
}

Might be a little help ^_^


问:
Make TextBox Editable by ContextMenuStrip - c# winform
I have a textbox in my C# Winform. The program assigns a value to the textbox by default.

I want the user to have a right click function to edit this text at runtime. So when the user right click to edit, the backgroud should become white and user should be able to edit the text. And after editing, the background should return to default and non editable

I have created a ContextMenuStrip with right click event to edit text as follows and assigned readonly property to false when user right clicks and press edit menu item:

```<code>private void editTextToolStripMenuItem_Click(object sender, EventArgs e)
{
    itxt_CommonTitle.ReadOnly = false;
}
</code>```

I am not sure how to proceed further. Is this possible using textbox?

答:
I think you are missing a process. After edit, there should be an update or save method.

textbox readonly = true;

edit textbox: textbox readonly = false;

button save: textbox readonyl = true;

Edit:
Something like this:

```<code>    private void buttonSave_Click(object sender, EventArgs e)
    {
        textBox1.ReadOnly = true;
    }

    private void editToolStripMenuItem_Click(object sender, EventArgs e)
    {
        textBox1.ReadOnly = false;
    }
</code>```

You dont need to change backColor, just readonly prop is fine.

Body:
I have a textbox in my C# Winform. The program assigns a value to the textbox by default.

I want the user to have a right click function to edit this text at runtime. So when the user right click to edit, the backgroud should become white and user should be able to edit the text. And after editing, the background should return to default and non editable

I have created a ContextMenuStrip with right click event to edit text as follows and assigned readonly property to false when user right clicks and press edit menu item:

private void editTextToolStripMenuItem_Click(object sender, EventArgs e)
{
    itxt_CommonTitle.ReadOnly = false;
}

I am not sure how to proceed further. Is this possible using textbox?

Body:
I think you are missing a process. After edit, there should be an update or save method.

textbox readonly = true;

edit textbox: textbox readonly = false;

button save: textbox readonyl = true;

Edit:
Something like this:

    private void buttonSave_Click(object sender, EventArgs e)
    {
        textBox1.ReadOnly = true;
    }

    private void editToolStripMenuItem_Click(object sender, EventArgs e)
    {
        textBox1.ReadOnly = false;
    }

You dont need to change backColor, just readonly prop is fine.


问:
How to parse HTTP raw bytes and get the HTTP content in python?
I use scapy to sniff some packets and I get some HTTP response packets that are bytes I cannot parse.For example:

```<code>  b'HTTP/1.1 200 OK\r\nDate: Thu, 07 Dec 2017 02:44:18 GMT\r\nServer:Apache/2.4.18 (Ubuntu)\r\nLast-Modified: Tue, 14 Nov 2017 05:51:36 GMT\r\nETag: "2c39-55deafadf0ac0-gzip"\r\nAccept-Ranges: bytes\r\nVary: Accept-Encoding\r\nContent-Encoding: gzip\r\nContent-Length: 3186\r\nConnection: close\r\nContent-Type: text/html\r\n\r\n\x1f\x8b'
</code>```

Is there a way to get the content part of this byte array so I can use gzip library to decode? I don't want to use request to get the HTTP response because I merely want to process the raw packet I had.

答:
You can extract the value portion of the bytes with

```<code>response_bytes.decode('utf-8')
</code>```

Then you can parse the returned information with Beautiful Soup for whatever part of it you want.

Body:
I use scapy to sniff some packets and I get some HTTP response packets that are bytes I cannot parse.For example:

  b'HTTP/1.1 200 OK\r\nDate: Thu, 07 Dec 2017 02:44:18 GMT\r\nServer:Apache/2.4.18 (Ubuntu)\r\nLast-Modified: Tue, 14 Nov 2017 05:51:36 GMT\r\nETag: "2c39-55deafadf0ac0-gzip"\r\nAccept-Ranges: bytes\r\nVary: Accept-Encoding\r\nContent-Encoding: gzip\r\nContent-Length: 3186\r\nConnection: close\r\nContent-Type: text/html\r\n\r\n\x1f\x8b'

Is there a way to get the content part of this byte array so I can use gzip library to decode? I don't want to use request to get the HTTP response because I merely want to process the raw packet I had.

Body:
You can extract the value portion of the bytes with

response_bytes.decode('utf-8')

Then you can parse the returned information with Beautiful Soup for whatever part of it you want.


问:
How can I get the total count of total pages of a PDF file using PDFMiner in Python?
In pypdf, I can get the total number of pages of a PDF file via:

```<code>from pypdf import PdfReader

reader = PdfReader("example.pdf")
no_of_pages = len(reader.pages)
</code>```

How can I get this using PDFMiner?

答:
I hate to just leave a code snippet. For context here is a link to the current pdfminer.six repo where you might be able to learn a little more about the resolve1 method.

As you're working with PDFMiner, you might print and come across some PDFObjRef objects. Essentially you can use resolve1 to expand those objects (they're usually a dictionary).

```<code>from pdfminer.pdfparser import PDFParser
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdfpage import PDFPage
from pdfminer.pdfinterp import resolve1

file = open('some_file.pdf', 'rb')
parser = PDFParser(file)
document = PDFDocument(parser)

# This will give you the count of pages
print(resolve1(document.catalog['Pages'])['Count'])
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In pypdf, I can get the total number of pages of a PDF file via:

from pypdf import PdfReader

reader = PdfReader("example.pdf")
no_of_pages = len(reader.pages)

How can I get this using PDFMiner?

Body:
I hate to just leave a code snippet. For context here is a link to the current pdfminer.six repo where you might be able to learn a little more about the resolve1 method.

As you're working with PDFMiner, you might print and come across some PDFObjRef objects. Essentially you can use resolve1 to expand those objects (they're usually a dictionary).

from pdfminer.pdfparser import PDFParser
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdfpage import PDFPage
from pdfminer.pdfinterp import resolve1

file = open('some_file.pdf', 'rb')
parser = PDFParser(file)
document = PDFDocument(parser)

# This will give you the count of pages
print(resolve1(document.catalog['Pages'])['Count'])


问:
Apply CSS Style on condition
I have a CSS style to make the background gray.

```<code>.team_not_selected {
    background-color: #B0B0B0;
}
</code>```

I'm displaying data from objects in a table format.

```<code><table>
    @For each item in model
    <tr>
        <th>item.Name</th>
        <th>item.ModelNumber</th>
        etc....
        Next
    </tr>
</table>
</code>```

Each object has a variable called "IsSelected" which is a Boolean.  I set that variable elsewhere.  I want to apply the team_not_selected div to the  tag if item.IsSelected = False.  That way, if the record is grayed out if it is not selected.

答:
In your code, looks like you want to add all rows as TableHeader (th), please verify.

For conditional CSS, try one of these:

IIf condition:

```<code><div class="@IIf(item.IsSelected, "team_selected", "team_not_selected")">
</code>```

If Condition:

```<code>@If (item.IsSelected) Then
<div class="team_selected">
Else
<div class="team_not_selected">
End if
</code>```

Title: Apply CSS Style on condition

Body:
I have a CSS style to make the background gray.

.team_not_selected {
    background-color: #B0B0B0;
}

I'm displaying data from objects in a table format.

    @For each item in model

        item.Name
        item.ModelNumber
        etc....
        Next

Each object has a variable called "IsSelected" which is a Boolean.  I set that variable elsewhere.  I want to apply the team_not_selected div to the  tag if item.IsSelected = False.  That way, if the record is grayed out if it is not selected.

Body:
In your code, looks like you want to add all rows as TableHeader (th), please verify.

For conditional CSS, try one of these:

IIf condition:

<div class="@IIf(item.IsSelected, "team_selected", "team_not_selected")">

If Condition:

@If (item.IsSelected) Then
<div class="team_selected">
Else
<div class="team_not_selected">
End if


问:
Waypoint handlers are continuously triggered when scrolling up
I am attempting to build a site with infinite scroll, comparable to this site. Notice that the URL is updated when you scroll down to next article and also when scrolling up to the previous article.

Here is the code that I made. It is executed once when a new article is appended, and creates waypoints for scrolling up and down.

```<code>function addUrlWaypoint() {
  var $lastArticle = $("article").last();

  $lastArticle.waypoint(function (direction) {
    if (direction === 'down') {
      history.pushState(null, "", $lastArticle.data("url"));
    }
  });

  $lastArticle.waypoint(function (direction) {
    if (direction === 'up') {
      history.pushState(null, "", $lastArticle.data("url"));
    }
  }, {
    offset: function() {
      return -$lastArticle.clientHeight
    }
  });
}
</code>```

The code for the offset was taken from the waypoint docs. However, this code triggers continuously when scrolling up and it does so for all articles.

When I change the offset to some value like -100 it triggers correctly, but I want it to trigger when the bottom comes into the top view (hence the clientHeight bit)

答:
Here's the answer expressed as an example...</p>

```<code>new Waypoint({
  element: $('#my-element'),
  offset: function () {
    return this.element.height();
  }
});
</code>```

Body:
I am attempting to build a site with infinite scroll, comparable to this site. Notice that the URL is updated when you scroll down to next article and also when scrolling up to the previous article.

Here is the code that I made. It is executed once when a new article is appended, and creates waypoints for scrolling up and down.

function addUrlWaypoint() {
  var $lastArticle = $("article").last();

  $lastArticle.waypoint(function (direction) {
    if (direction === 'down') {
      history.pushState(null, "", $lastArticle.data("url"));
    }
  });

  $lastArticle.waypoint(function (direction) {
    if (direction === 'up') {
      history.pushState(null, "", $lastArticle.data("url"));
    }
  }, {
    offset: function() {
      return -$lastArticle.clientHeight
    }
  });
}

The code for the offset was taken from the waypoint docs. However, this code triggers continuously when scrolling up and it does so for all articles.

When I change the offset to some value like -100 it triggers correctly, but I want it to trigger when the bottom comes into the top view (hence the clientHeight bit)

Body:
Here's the answer expressed as an example...

new Waypoint({
  element: $('#my-element'),
  offset: function () {
    return this.element.height();
  }
});