问:
Config parsing Robotframework
I have a project that has been implemented using a mix of python and Robotframework scripts. I have have a bunch of configuration items stored inside my projects  Config.ini file which looks like this:

```<code>[Environment]
Username: username@mail.com
Password: testpassword

[WebUI]
login_url:        http://testsite.net/
</code>```

Python is able to interpret the above variables alright using the ConfigManager object like this:

```<code>class MyConfigManager(ConfigManager):
    """
    Class to hold all config values in form of variables.
    """

def __init__(self):
    super().__init__("dispatch/config.ini")
    self._android = Android(self._config)

@property
def username(self):
    return self._config.get(_env_section, "Username")

@property
def password(self):
    return self._config.get(_env_section, "Password")

config = MyConfigManager()
</code>```

Is it possible to import config.ini in Robotframework as a variables file and use these values? I am trying not to have another variables file for my Robot scripts.

EDIT:

I am attempting to do something like this with my robot file:

```<code>*** Settings ***
Documentation   WebUI Login Tests
Library         SeleniumLibrary
Resource        common_keywords.robot
Variables       config.ini
# ^ will this work?
Default Tags    Smoke
Suite Setup     Set Selenium Timeout        15seconds
Suite Teardown  Close Browser

*** Variables ***

${login_button}     class:auth0-lock-submit

*** Test Cases ***
TC001_Login_Test
    [Documentation]     Open login page, login with credentials in arguments.
    Open Browser Confirm Login Page     chrome      ${login_url}
    Provide Input Text          name:email          ${username}
    Provide Input Text          name:password       ${password}
    Find Element And Click      ${login_button}
# the three vars ${login_url},  ${username}, ${password} would be from
# config.ini but this isnt working. What am I doing wrong? or is not
# possible to do this?
</code>```

答:
Robot framework variable files can be python code, and because they are python, you can create variables any way you want.

You just need to create a python function that returns a dictionary of key/value pairs. Each key will become a robot variable.

For example, for the data in your question, if you want to create variables like ${CONFIG.Environment.username}, you could do it like this:

```<code>import ConfigParser
def get_variables(varname, filename):
    config = ConfigParser.ConfigParser()
    config.read(filename)

    variables = {}
    for section in config.sections():
        for key, value in config.items(section):
            var = "%s.%s.%s" % (varname, section, key)
            variables[var] = value
    return variables
</code>```

Save it to a file named "ConfigVariables.py", and put it where your test can find it. You can then use it like this:

```<code>*** Settings ***
Variables  ConfigVariables.py  CONFIG  /tmp/Config.ini

*** Test cases ***
Example
    should be equal  ${CONFIG.Environment.username}  username@mail.com
    should be equal  ${CONFIG.Environment.password}  testpassword
    should be equal  ${CONFIG.WebUI.login_url}       http://testsite.net/
</code>```

Using functions to define variables is described in the robot framework user guide, in the section titled Variable Files

Title: Config parsing Robotframework

Body:
I have a project that has been implemented using a mix of python and Robotframework scripts. I have have a bunch of configuration items stored inside my projects  Config.ini file which looks like this:

[Environment]
Username: username@mail.com
Password: testpassword

[WebUI]
login_url:        http://testsite.net/

Python is able to interpret the above variables alright using the ConfigManager object like this:

class MyConfigManager(ConfigManager):
    """
    Class to hold all config values in form of variables.
    """

def __init__(self):
    super().__init__("dispatch/config.ini")
    self._android = Android(self._config)

@property
def username(self):
    return self._config.get(_env_section, "Username")

@property
def password(self):
    return self._config.get(_env_section, "Password")

config = MyConfigManager()

Is it possible to import config.ini in Robotframework as a variables file and use these values? I am trying not to have another variables file for my Robot scripts.

EDIT:

I am attempting to do something like this with my robot file:

*** Settings ***
Documentation   WebUI Login Tests
Library         SeleniumLibrary
Resource        common_keywords.robot
Variables       config.ini
# ^ will this work?
Default Tags    Smoke
Suite Setup     Set Selenium Timeout        15seconds
Suite Teardown  Close Browser

*** Variables ***

${login_button}     class:auth0-lock-submit

*** Test Cases ***
TC001_Login_Test
    [Documentation]     Open login page, login with credentials in arguments.
    Open Browser Confirm Login Page     chrome      ${login_url}
    Provide Input Text          name:email          ${username}
    Provide Input Text          name:password       ${password}
    Find Element And Click      ${login_button}
# the three vars ${login_url},  ${username}, ${password} would be from
# config.ini but this isnt working. What am I doing wrong? or is not
# possible to do this?

Body:
Robot framework variable files can be python code, and because they are python, you can create variables any way you want.

You just need to create a python function that returns a dictionary of key/value pairs. Each key will become a robot variable.

For example, for the data in your question, if you want to create variables like ${CONFIG.Environment.username}, you could do it like this:

import ConfigParser
def get_variables(varname, filename):
    config = ConfigParser.ConfigParser()
    config.read(filename)

    variables = {}
    for section in config.sections():
        for key, value in config.items(section):
            var = "%s.%s.%s" % (varname, section, key)
            variables[var] = value
    return variables

Save it to a file named "ConfigVariables.py", and put it where your test can find it. You can then use it like this:

*** Settings ***
Variables  ConfigVariables.py  CONFIG  /tmp/Config.ini

*** Test cases ***
Example
    should be equal  ${CONFIG.Environment.username}  username@mail.com
    should be equal  ${CONFIG.Environment.password}  testpassword
    should be equal  ${CONFIG.WebUI.login_url}       http://testsite.net/

Using functions to define variables is described in the robot framework user guide, in the section titled Variable Files


来源: stackexchange

问:
Executing sequence of MS sql queries with temp tables in python
Currently trying to use pyodbc and pandas to read sequence of sql queries (from MS sql server) and examine as dataframe, getting the following error on the very first query in the sequence:

```<code>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-95-5eec1638614b> in <module>()
    285 for count, q in enumerate(sql_in):
    286     print count
--> 287     frame_in = pd.read_sql(q, cnxn)
    288 print frame_in.head(n=10)
    289

/home/mapr/anaconda2/lib/python2.7/site-packages/pandas/io/sql.pyc in read_sql(sql, con, index_col, coerce_float, params, parse_dates, columns, chunksize)
    497             sql, index_col=index_col, params=params,
    498             coerce_float=coerce_float, parse_dates=parse_dates,
--> 499             chunksize=chunksize)
    500
    501     try:

/home/mapr/anaconda2/lib/python2.7/site-packages/pandas/io/sql.pyc in read_query(self, sql, index_col, coerce_float, params, parse_dates, chunksize)
   1598         args = _convert_params(sql, params)
   1599         cursor = self.execute(*args)
-> 1600         columns = [col_desc[0] for col_desc in cursor.description]
   1601
   1602         if chunksize is not None:

TypeError: 'NoneType' object is not iterable
</code>```

The relevant code snippet looks like:

```<code>sql_in = """
SET NOCOUNT ON;
select <stuff> from <table1> into #<temptable1>
----SPLIT
SET NOCOUNT ON;
select <stuff> from <table2> into #<temptable2>
----SPLIT
SET NOCOUNT ON;
select <stuff> from <table3> into #<temptable3>
----SPLIT
SET NOCOUNT ON;
select <stuff> from <table4> <joined with temptables1-3> into #<temptable4>
""".split('----SPLIT')

for count, q in enumerate(sql_in):
    print count
    frame_in = pd.read_sql(q, cnxn)
</code>```

Done this way because only interested in the final temp table (using split because of the advice posted here).

Can confirm that pyodbc is configured right by running:

```<code>cnxn = pyodbc.connect(cnxn_str)
cursor = cnxn.cursor()

#Sample select query
print 'Testing db connection...'
cursor.execute("SELECT @@version;")
row = cursor.fetchone()
while row:
    print row[0]
    row = cursor.fetchone()
</code>```

And actually getting the server version.

Any ideas why this could be happening and how to fix? Thanks.

答: I believe it is because the first several queries don't return any data. Pandas read_sql expects data to come back. You should just use the pyodbc execute function to run those queries. </p>

ContentLicense: CC BY-SA 3.0

Body:
Currently trying to use pyodbc and pandas to read sequence of sql queries (from MS sql server) and examine as dataframe, getting the following error on the very first query in the sequence:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-95-5eec1638614b> in <module>()
    285 for count, q in enumerate(sql_in):
    286     print count
--> 287     frame_in = pd.read_sql(q, cnxn)
    288 print frame_in.head(n=10)
    289

/home/mapr/anaconda2/lib/python2.7/site-packages/pandas/io/sql.pyc in read_sql(sql, con, index_col, coerce_float, params, parse_dates, columns, chunksize)
    497             sql, index_col=index_col, params=params,
    498             coerce_float=coerce_float, parse_dates=parse_dates,
--> 499             chunksize=chunksize)
    500
    501     try:

/home/mapr/anaconda2/lib/python2.7/site-packages/pandas/io/sql.pyc in read_query(self, sql, index_col, coerce_float, params, parse_dates, chunksize)
   1598         args = _convert_params(sql, params)
   1599         cursor = self.execute(*args)
-> 1600         columns = [col_desc[0] for col_desc in cursor.description]
   1601
   1602         if chunksize is not None:

TypeError: 'NoneType' object is not iterable

The relevant code snippet looks like:

sql_in = """
SET NOCOUNT ON;
select <stuff> from <table1> into #<temptable1>
----SPLIT
SET NOCOUNT ON;
select <stuff> from <table2> into #<temptable2>
----SPLIT
SET NOCOUNT ON;
select <stuff> from <table3> into #<temptable3>
----SPLIT
SET NOCOUNT ON;
select <stuff> from <table4> <joined with temptables1-3> into #<temptable4>
""".split('----SPLIT')

for count, q in enumerate(sql_in):
    print count
    frame_in = pd.read_sql(q, cnxn)

Done this way because only interested in the final temp table (using split because of the advice posted here).

Can confirm that pyodbc is configured right by running:

cnxn = pyodbc.connect(cnxn_str)
cursor = cnxn.cursor()

#Sample select query
print 'Testing db connection...'
cursor.execute("SELECT @@version;")
row = cursor.fetchone()
while row:
    print row[0]
    row = cursor.fetchone()

And actually getting the server version.

Any ideas why this could be happening and how to fix? Thanks.


问:
Is there a UIView resize event?
I have a view that has rows and columns of imageviews in it.

If this view is resized, I need to rearrange the imageviews positions.

This view is a subview of another view that gets resized.

Is there a way to detect when this view is being resized?

答:
Swift 4 keypath KVO -- This is how I detect autorotate and moving to iPad side panel. Should work work any view. Had to observe the UIView's layer. </p>

```<code>private var observer: NSKeyValueObservation?

override func viewDidLoad() {
    super.viewDidLoad()
    observer = view.layer.observe(\.bounds) { object, _ in
        print(object.bounds)
    }
    // ...
}
override func viewWillDisappear(_ animated: Bool) {
    observer?.invalidate()
    //...
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Is there a UIView resize event?

Body:
Swift 4 keypath KVO -- This is how I detect autorotate and moving to iPad side panel. Should work work any view. Had to observe the UIView's layer.

private var observer: NSKeyValueObservation?

override func viewDidLoad() {
    super.viewDidLoad()
    observer = view.layer.observe(\.bounds) { object, _ in
        print(object.bounds)
    }
    // ...
}
override func viewWillDisappear(_ animated: Bool) {
    observer?.invalidate()
    //...
}


问:
Multi-module MultiDex project won't run tests after update to android gradle plugin 2.3
I have project with multiple modules, all of which are configured to build with multiDexEnabled true. All of these modules have instrumentation test packages that are configured to run JUnit4 tests with MultiDex enabled per this SO answer: https://stackoverflow.com/a/35214158/736963 EXCEPT for one of the modules. One of the modules is configured to use testInstrumentationRunner "com.android.test.runner.MultiDexTestRunner" (and hence has no JUnit4 tests) because it depends on a DLL that just will not load with the JUnit4 test runner. (If anyone knows the solution to that one, that's great! But that's not the problem I'm reporting here...)

This configuration has been working fine until I just attempted to update to android gradle plugin 2.3.0. Now when I run tests for the module using the JUnit3 MultiDexTestRunner, I see this:

```<code>Started running tests
Test running failed: Instrumentation run failed due to 'java.lang.ClassNotFoundException'
Empty test suite.
</code>```

And in the console this (truncated to the useful bit):

```<code>java.lang.RuntimeException: Unable to instantiate instrumentation ComponentInfo{com.redacted.test/com.android.test.runner.MultiDexTestRunner}: java.lang.ClassNotFoundException: Didn't find class "com.android.test.runner.MultiDexTestRunner" on path: DexPathList[[zip file "/system/framework/android.test.runner.jar", zip file "/data/app/com.redacted.test-1/base.apk", zip file "/data/app/com.redacted.test-1/base.apk"],nativeLibraryDirectories=[/data/app/com.redacted.test-1/lib/arm, /data/app/com.redacted.test-1/lib/arm, /data/app/com.redacted.test-1/base.apk!/lib/armeabi-v7a, /data/app/com.redacted.test-1/base.apk!/lib/armeabi-v7a, /vendor/lib, /system/lib]]
...
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.android.test.runner.MultiDexTestRunner" on path: DexPathList[[zip file "/system/framework/android.test.runner.jar", zip file "/data/app/com.intuit.paymentshub.test-1/base.apk", zip file "/data/app/com.intuit.paymentshub.test-1/base.apk"],nativeLibraryDirectories=[/data/app/com.intuit.paymentshub.test-1/lib/arm, /data/app/com.intuit.paymentshub.test-1/lib/arm, /data/app/com.intuit.paymentshub.test-1/base.apk!/lib/armeabi-v7a, /data/app/com.intuit.paymentshub.test-1/base.apk!/lib/armeabi-v7a, /vendor/lib, /system/lib]]
</code>```

So I'm stuck on the earlier Android Gradle Plugin until I can resolve this (or the DLL problem, though I'm less hopeful on that one since it has never worked.)

答: It seems like this problem went away after updating the tooling. Currently running android for gradle 2.3.3 with buildTools 26 and this problem is gone.</p>

Body:
I have project with multiple modules, all of which are configured to build with multiDexEnabled true. All of these modules have instrumentation test packages that are configured to run JUnit4 tests with MultiDex enabled per this SO answer: https://stackoverflow.com/a/35214158/736963 EXCEPT for one of the modules. One of the modules is configured to use testInstrumentationRunner "com.android.test.runner.MultiDexTestRunner" (and hence has no JUnit4 tests) because it depends on a DLL that just will not load with the JUnit4 test runner. (If anyone knows the solution to that one, that's great! But that's not the problem I'm reporting here...)

This configuration has been working fine until I just attempted to update to android gradle plugin 2.3.0. Now when I run tests for the module using the JUnit3 MultiDexTestRunner, I see this:

Started running tests
Test running failed: Instrumentation run failed due to 'java.lang.ClassNotFoundException'
Empty test suite.

And in the console this (truncated to the useful bit):

java.lang.RuntimeException: Unable to instantiate instrumentation ComponentInfo{com.redacted.test/com.android.test.runner.MultiDexTestRunner}: java.lang.ClassNotFoundException: Didn't find class "com.android.test.runner.MultiDexTestRunner" on path: DexPathList[[zip file "/system/framework/android.test.runner.jar", zip file "/data/app/com.redacted.test-1/base.apk", zip file "/data/app/com.redacted.test-1/base.apk"],nativeLibraryDirectories=[/data/app/com.redacted.test-1/lib/arm, /data/app/com.redacted.test-1/lib/arm, /data/app/com.redacted.test-1/base.apk!/lib/armeabi-v7a, /data/app/com.redacted.test-1/base.apk!/lib/armeabi-v7a, /vendor/lib, /system/lib]]
...
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.android.test.runner.MultiDexTestRunner" on path: DexPathList[[zip file "/system/framework/android.test.runner.jar", zip file "/data/app/com.intuit.paymentshub.test-1/base.apk", zip file "/data/app/com.intuit.paymentshub.test-1/base.apk"],nativeLibraryDirectories=[/data/app/com.intuit.paymentshub.test-1/lib/arm, /data/app/com.intuit.paymentshub.test-1/lib/arm, /data/app/com.intuit.paymentshub.test-1/base.apk!/lib/armeabi-v7a, /data/app/com.intuit.paymentshub.test-1/base.apk!/lib/armeabi-v7a, /vendor/lib, /system/lib]]

So I'm stuck on the earlier Android Gradle Plugin until I can resolve this (or the DLL problem, though I'm less hopeful on that one since it has never worked.)


问:
Can hibernate map a Java collection of different object types?
I have a Java HashMap object that contians a User object and a Room object. Can Hibernate cope with mapping this to a database, or can hibernate only deal with mapping collections that contain objects of the same type?

Many thanks,

Dave.

答: You may want to create a common supertype for these objects. If you find that the two types do not have common foundation then maybe they do not belong in the same Map. As far as I know, mapping to two distinct types as you describe is not possible.</p>


问:
Use Lambda Edge(with Cloudfront trigger) to resize images on fly
I've just done this, makes images stored on s3 being resized on request and it works as charm: https://aws.amazon.com/tw/blogs/compute/resize-images-on-the-fly-with-amazon-s3-aws-lambda-and-amazon-api-gateway/

And I've just started reading articles of Lambda Edge: http://docs.aws.amazon.com/lambda/latest/dg/lambda-edge.html

But I'm still not sure what I should do with events: Viewer Request, Origin Request, Origin Response and Viewer Response.

The lambda function with gateway trigger I use for now is https://github.com/awslabs/serverless-image-resizing

答:
As of December 2017, AWS Lambda Limits are memory allocation maximum of 3008 MB and maximum execution duration per request of 300 seconds. In fact Step 2.1: Create a Deployment Package even uses the example of image resizing.

AWS Lambda@Edge has the best description of the events including a diagram.  I think you want to use the Origin Request event, so your response can be cached.  Also, watch AWS re:invent 2017: Building Serverless Websites with Lambda@Edge (CTD309) - YouTube  for a full explanation.


问:
Show div when  element is hovered
Easy to explain. I want to make something like dropdown menu. When I hover on element (for example ) -  appears div block, which disappears on leaving  element or div block.

```<code><a>Element to hover</a>
<div>I'm not gonna disappear until u leave me or my <a> bro</div>
</code>```

I hope it would be easy for you guys to help me. Thanks in advance!

What have I tried?
I went by the simplest way, but this doesn't work as I wanted. I did it in css, smth like

```<code> a:hover div {
display: block;
}
</code>```

But when I leave div, it disappears. So I need the other solution? How can I do this?

答:
Here's what a simple CSS solution would look like using the sibling selector.

.nav
{
  border: 1px solid black;
  padding: 1px;
}

.nav:hover + .menu, .menu:hover
{
  display: block;
}

.menu {
  display:none;
  border: 1px solid black;
  padding: 1px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Element to hover
<div class="menu">I'm not gonna disappear until u leave me or my a bro</div></code>```

Title: Show div when <a> element is hovered

Body:
Easy to explain. I want to make something like dropdown menu. When I hover on element (for example ) -  appears div block, which disappears on leaving  element or div block.

Element to hover

I'm not gonna disappear until u leave me or my  bro

I hope it would be easy for you guys to help me. Thanks in advance!

What have I tried?
I went by the simplest way, but this doesn't work as I wanted. I did it in css, smth like

 a:hover div {
display: block;
}

But when I leave div, it disappears. So I need the other solution? How can I do this?

Body:
Here's what a simple CSS solution would look like using the sibling selector.

.nav
{
  border: 1px solid black;
  padding: 1px;
}

.nav:hover + .menu, .menu:hover
{
  display: block;
}

.menu {
  display:none;
  border: 1px solid black;
  padding: 1px;
}

<a class="nav">Element to hover</a>
<div class="menu">I'm not gonna disappear until u leave me or my a bro</div>


问:
How can I retrieve the input values of dynamically created textfields?
Here is my code so far where I have a numericupdown item named numericUpDown and button. Once the user selects a number when they press the button it dynamically created the fields.

```<code>private void createPerson_Click(object sender, EventArgs e)
{
    Label[] person_Name = new Label[(int)this.numericUpDown.Value];
    TextBox[] person_txtinput = new TextBox[(int)this.numericUpDown.Value];

    for (int i = 0; i < this.numericUpDown.Value; i++)
    {
        //create person name label
        Person_Name[i] = new Label();
        Person_Name[i].Location = new System.Drawing.Point(20, 114 + i * 25);
        Person_Name[i].Size = new System.Drawing.Size(120, 15);
        Person_Name[i].Text = (i + 1).ToString() + @")" + "Person Name:";
        this.Controls.Add(Person_Name[i]);

        //create person name textbox
        PersonNameTxtInput[i] = new TextBox();
        PersonNameTxtInput[i].Location = new System.Drawing.Point(140, 114 + i * 25);
        PersonNameTxtInput[i].Size = new System.Drawing.Size(125, 20);
        this.Controls.Add(PersonNameTxtInput[i]);
    }
}

 private void save_Click(object sender, EventArgs e)
{
    for (int i = 0; j < this.numericUpDown.Value; i++)
    {
        MessageBox.Show("" + PersonNameTxtInput[i].Text);
    }
}
</code>```

My question is, how can I get all the values from the textboxes depending on how many fields are created by the user when the save button is pressed?

I have tried using the code within the save button listener however how can i make Label[] person_Name = new Label[(int)this.numericUpDown.Value]; a global variable so i can access it within the save button for loop.

答:
Well, I don't know exactly why you are doing this in this particular way and I must admit it doesn't seem very effective, but you could just do what Ryan_L suggested and iterate through this.Controls like this

```<code>for(int i = 0; i < this.Controls.Count; i++)
{
    if(this.Controls[i] is TextBox) //skip buttons and labels
    {
        MessageBox.Show("" + this.Controls[i].Text);
    }
}
</code>```

Now, regarding your question how to define a global variable so you can access it within the save button for loop...just define the two arrays outside of the createPerson_Click event like this:

```<code>Label[] person_Name;
TextBox[] person_txtinput;

private void button1_Click(object sender, EventArgs e)
{
    person_Name = new Label[(int)this.numericUpDown.Value];
    person_txtinput = new TextBox[(int)this.numericUpDown.Value];
    //the rest of the code
}
</code>```

Hope this helps. However, you might want to reconsider your entire approach.

Body:
Here is my code so far where I have a numericupdown item named numericUpDown and button. Once the user selects a number when they press the button it dynamically created the fields.

private void createPerson_Click(object sender, EventArgs e)
{
    Label[] person_Name = new Label[(int)this.numericUpDown.Value];
    TextBox[] person_txtinput = new TextBox[(int)this.numericUpDown.Value];

    for (int i = 0; i < this.numericUpDown.Value; i++)
    {
        //create person name label
        Person_Name[i] = new Label();
        Person_Name[i].Location = new System.Drawing.Point(20, 114 + i * 25);
        Person_Name[i].Size = new System.Drawing.Size(120, 15);
        Person_Name[i].Text = (i + 1).ToString() + @")" + "Person Name:";
        this.Controls.Add(Person_Name[i]);

        //create person name textbox
        PersonNameTxtInput[i] = new TextBox();
        PersonNameTxtInput[i].Location = new System.Drawing.Point(140, 114 + i * 25);
        PersonNameTxtInput[i].Size = new System.Drawing.Size(125, 20);
        this.Controls.Add(PersonNameTxtInput[i]);
    }
}

 private void save_Click(object sender, EventArgs e)
{
    for (int i = 0; j < this.numericUpDown.Value; i++)
    {
        MessageBox.Show("" + PersonNameTxtInput[i].Text);
    }
}

My question is, how can I get all the values from the textboxes depending on how many fields are created by the user when the save button is pressed?

I have tried using the code within the save button listener however how can i make Label[] person_Name = new Label[(int)this.numericUpDown.Value]; a global variable so i can access it within the save button for loop.

Body:
Well, I don't know exactly why you are doing this in this particular way and I must admit it doesn't seem very effective, but you could just do what Ryan_L suggested and iterate through this.Controls like this

for(int i = 0; i < this.Controls.Count; i++)
{
    if(this.Controls[i] is TextBox) //skip buttons and labels
    {
        MessageBox.Show("" + this.Controls[i].Text);
    }
}

Now, regarding your question how to define a global variable so you can access it within the save button for loop...just define the two arrays outside of the createPerson_Click event like this:

Label[] person_Name;
TextBox[] person_txtinput;

private void button1_Click(object sender, EventArgs e)
{
    person_Name = new Label[(int)this.numericUpDown.Value];
    person_txtinput = new TextBox[(int)this.numericUpDown.Value];
    //the rest of the code
}

Hope this helps. However, you might want to reconsider your entire approach.


问:
Trouble with nginx and django configuration?
I use NGINX+GUNICORN+DJANGO and my gunicorn status is active.
I want to set up nginx with django.
I create a new file named 'mysite'in /etc/nginx/sites-available

```<code>server {
        listen 8000 default_server;
        listen [::]:8000 default_server;
        server_name my_ip;
        location = /favicon.ico { access_log off; log_not_found off; }
        location /static/ {
            root /home/split/mysite;
        }
        location / {
            include proxy_params;
            proxy_pass http://unix:/home/split/mysite/mysite.sock;
        }
}
</code>```

saved it and create symbolyc link to /etc/nginx/sites-enabled
After that I did sudo service nginx restart and got this:

```<code>Job for nginx.service failed because the control process exited with error code. See "systemctl status nginx.service" and "journalctl -xe" for details.
</code>```

I went to journalctl -xe

```<code>--
-- Unit nginx.service has finished shutting down.
Dec 07 01:05:17 ubuntu systemd[1]: Starting A high performance web server and a reverse proxy server...
-- Subject: Unit nginx.service has begun start-up
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit nginx.service has begun starting up.
Dec 07 01:05:17 ubuntu nginx[49646]: nginx: [crit] pread() "/etc/nginx/sites-enabled/sites-available" failed (21: Is a directory)
Dec 07 01:05:17 ubuntu nginx[49646]: nginx: configuration file /etc/nginx/nginx.conf test failed
Dec 07 01:05:17 ubuntu systemd[1]: nginx.service: Control process exited, code=exited status=1
Dec 07 01:05:17 ubuntu sudo[49639]: pam_unix(sudo:session): session closed for user root
Dec 07 01:05:17 ubuntu systemd[1]: FAILED TO START A HIGH PERFORMANCE WEB SERVER AND A REVERSE PROXY SERVER.
-- Subject: Unit nginx.service has failed
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit nginx.service has failed.
--
-- The result is failed.
Dec 07 01:05:17 ubuntu systemd[1]: nginx.service: Unit entered failed state.
Dec 07 01:05:17 ubuntu systemd[1]: nginx.service: Failed with result 'exit-code'.
Dec 07 01:05:42 ubuntu kernel: [UFW BLOCK] IN=eth0 OUT= MAC=02:1e:6d:00:e4:9f:00:01:e8:11:73:69:08:00 SRC=193.124.0.226 DST=194.87.95.46 LEN=48 TOS=0
Dec 07 01:05:57 ubuntu kernel: [UFW BLOCK] IN=eth0 OUT= MAC=02:1e:6d:00:e4:9f:00:01:e8:11:73:69:08:00 SRC=193.124.0.226 DST=194.87.95.46 LEN=52 TOS=0
Dec 07 01:06:16 ubuntu kernel: [UFW BLOCK] IN=eth0 OUT= MAC=01:00:5e:00:00:01:00:21:d7:56:a5:80:08:00 SRC=93.95.100.9 DST=224.0.0.1 LEN=32 TOS=0x00 P
Dec 07 01:06:21 ubuntu sudo[49655]:    split : TTY=pts/0 ; PWD=/etc/nginx ; USER=root ; COMMAND=/bin/journalctl -xe
Dec 07 01:06:21 ubuntu sudo[49655]: pam_unix(sudo:session): session opened for user root by split(uid=0)
Dec 07 01:06:39 ubuntu kernel: [UFW BLOCK] IN=eth0 OUT= MAC=02:1e:6d:00:e4:9f:00:01:e8:11:73:69:08:00 SRC=193.124.0.226 DST=194.87.95.46 LEN=52 TOS=0
Dec 07 01:07:16 ubuntu kernel: [UFW BLOCK] IN=eth0 OUT= MAC=01:00:5e:00:00:01:00:21:d7:56:a5:80:08:00 SRC=93.95.100.9 DST=224.0.0.1 LEN=32 TOS=0x00 P
Dec 07 01:07:17 ubuntu kernel: [UFW BLOCK] IN=eth0 OUT= MAC=02:1e:6d:00:e4:9f:00:01:e8:11:73:69:08:00 SRC=185.207.206.224 DST=194.87.95.46 LEN=40 TOS
Dec 07 01:07:46 ubuntu kernel: [UFW BLOCK] IN=eth0 OUT= MAC=02:1e:6d:00:e4:9f:00:01:e8:11:73:69:08:00 SRC=212.16.70.23 DST=194.87.95.46 LEN=40 TOS=0x
Dec 07 01:08:03 ubuntu sudo[49662]:    split : TTY=pts/0 ; PWD=/etc/nginx ; USER=root ; COMMAND=/bin/su
Dec 07 01:08:03 ubuntu sudo[49662]: pam_unix(sudo:session): session opened for user root by split(uid=0)
Dec 07 01:08:03 ubuntu su[49663]: Successful su for root by root
Dec 07 01:08:03 ubuntu su[49663]: + /dev/pts/0 root:root
Dec 07 01:08:03 ubuntu su[49663]: pam_unix(su:session): session opened for user root by split(uid=0)
</code>```

答:
this is a draft of my project used with uwsgi worked well for me . just change the address
one more thing change socket permission to 664 </p>

```<code># mysite_nginx.conf

# the upstream component nginx needs to connect to
upstream django {
    server unix:///tmp/uwsgi.sock;
    #server 127.0.0.1:8001; # for a web port socket (we'll use this first)
}

# configuration of the server
server {
    # the port your site will be served on
    listen      8080;
    # the domain name it will serve for
    server_name 127.0.0.1; # substitute your machine's IP address or FQDN
    charset     utf-8;

    # max upload size
    client_max_body_size 75M;   # adjust to taste

    # Django media
    location /media  {
        alias /home/naqib/FINAL_WEB_03/NLLAYVM/media;  # your Django project's media files
    }

    location /static {
        alias /home/naqib/FINAL_WEB_03/NLLAYVM/app/static; # your Django project's static files
    }

    # Finally, send all non-media requests to the Django server.
    location / {
        uwsgi_pass  django;
        include     /home/naqib/FINAL_WEB_03/NLLAYVM/uwsgi_params; # the uwsgi_params file you installed
    }
}
</code>```

Body:
I use NGINX+GUNICORN+DJANGO and my gunicorn status is active.
I want to set up nginx with django.
I create a new file named 'mysite'in /etc/nginx/sites-available

server {
        listen 8000 default_server;
        listen [::]:8000 default_server;
        server_name my_ip;
        location = /favicon.ico { access_log off; log_not_found off; }
        location /static/ {
            root /home/split/mysite;
        }
        location / {
            include proxy_params;
            proxy_pass http://unix:/home/split/mysite/mysite.sock;
        }
}

saved it and create symbolyc link to /etc/nginx/sites-enabled
After that I did sudo service nginx restart and got this:

Job for nginx.service failed because the control process exited with error code. See "systemctl status nginx.service" and "journalctl -xe" for details.

I went to journalctl -xe

--
-- Unit nginx.service has finished shutting down.
Dec 07 01:05:17 ubuntu systemd[1]: Starting A high performance web server and a reverse proxy server...
-- Subject: Unit nginx.service has begun start-up
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit nginx.service has begun starting up.
Dec 07 01:05:17 ubuntu nginx[49646]: nginx: [crit] pread() "/etc/nginx/sites-enabled/sites-available" failed (21: Is a directory)
Dec 07 01:05:17 ubuntu nginx[49646]: nginx: configuration file /etc/nginx/nginx.conf test failed
Dec 07 01:05:17 ubuntu systemd[1]: nginx.service: Control process exited, code=exited status=1
Dec 07 01:05:17 ubuntu sudo[49639]: pam_unix(sudo:session): session closed for user root
Dec 07 01:05:17 ubuntu systemd[1]: FAILED TO START A HIGH PERFORMANCE WEB SERVER AND A REVERSE PROXY SERVER.
-- Subject: Unit nginx.service has failed
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit nginx.service has failed.
--
-- The result is failed.
Dec 07 01:05:17 ubuntu systemd[1]: nginx.service: Unit entered failed state.
Dec 07 01:05:17 ubuntu systemd[1]: nginx.service: Failed with result 'exit-code'.
Dec 07 01:05:42 ubuntu kernel: [UFW BLOCK] IN=eth0 OUT= MAC=02:1e:6d:00:e4:9f:00:01:e8:11:73:69:08:00 SRC=193.124.0.226 DST=194.87.95.46 LEN=48 TOS=0
Dec 07 01:05:57 ubuntu kernel: [UFW BLOCK] IN=eth0 OUT= MAC=02:1e:6d:00:e4:9f:00:01:e8:11:73:69:08:00 SRC=193.124.0.226 DST=194.87.95.46 LEN=52 TOS=0
Dec 07 01:06:16 ubuntu kernel: [UFW BLOCK] IN=eth0 OUT= MAC=01:00:5e:00:00:01:00:21:d7:56:a5:80:08:00 SRC=93.95.100.9 DST=224.0.0.1 LEN=32 TOS=0x00 P
Dec 07 01:06:21 ubuntu sudo[49655]:    split : TTY=pts/0 ; PWD=/etc/nginx ; USER=root ; COMMAND=/bin/journalctl -xe
Dec 07 01:06:21 ubuntu sudo[49655]: pam_unix(sudo:session): session opened for user root by split(uid=0)
Dec 07 01:06:39 ubuntu kernel: [UFW BLOCK] IN=eth0 OUT= MAC=02:1e:6d:00:e4:9f:00:01:e8:11:73:69:08:00 SRC=193.124.0.226 DST=194.87.95.46 LEN=52 TOS=0
Dec 07 01:07:16 ubuntu kernel: [UFW BLOCK] IN=eth0 OUT= MAC=01:00:5e:00:00:01:00:21:d7:56:a5:80:08:00 SRC=93.95.100.9 DST=224.0.0.1 LEN=32 TOS=0x00 P
Dec 07 01:07:17 ubuntu kernel: [UFW BLOCK] IN=eth0 OUT= MAC=02:1e:6d:00:e4:9f:00:01:e8:11:73:69:08:00 SRC=185.207.206.224 DST=194.87.95.46 LEN=40 TOS
Dec 07 01:07:46 ubuntu kernel: [UFW BLOCK] IN=eth0 OUT= MAC=02:1e:6d:00:e4:9f:00:01:e8:11:73:69:08:00 SRC=212.16.70.23 DST=194.87.95.46 LEN=40 TOS=0x
Dec 07 01:08:03 ubuntu sudo[49662]:    split : TTY=pts/0 ; PWD=/etc/nginx ; USER=root ; COMMAND=/bin/su
Dec 07 01:08:03 ubuntu sudo[49662]: pam_unix(sudo:session): session opened for user root by split(uid=0)
Dec 07 01:08:03 ubuntu su[49663]: Successful su for root by root
Dec 07 01:08:03 ubuntu su[49663]: + /dev/pts/0 root:root
Dec 07 01:08:03 ubuntu su[49663]: pam_unix(su:session): session opened for user root by split(uid=0)

Body:
this is a draft of my project used with uwsgi worked well for me . just change the address
one more thing change socket permission to 664

# mysite_nginx.conf

# the upstream component nginx needs to connect to
upstream django {
    server unix:///tmp/uwsgi.sock;
    #server 127.0.0.1:8001; # for a web port socket (we'll use this first)
}

# configuration of the server
server {
    # the port your site will be served on
    listen      8080;
    # the domain name it will serve for
    server_name 127.0.0.1; # substitute your machine's IP address or FQDN
    charset     utf-8;

    # max upload size
    client_max_body_size 75M;   # adjust to taste

    # Django media
    location /media  {
        alias /home/naqib/FINAL_WEB_03/NLLAYVM/media;  # your Django project's media files
    }

    location /static {
        alias /home/naqib/FINAL_WEB_03/NLLAYVM/app/static; # your Django project's static files
    }

    # Finally, send all non-media requests to the Django server.
    location / {
        uwsgi_pass  django;
        include     /home/naqib/FINAL_WEB_03/NLLAYVM/uwsgi_params; # the uwsgi_params file you installed
    }
}


问:
Python: Number of the Week in a Month
When specifying a date:

```<code>datetime.datetime(2011, 8, 15)
</code>```

How can i get to know that this is the third week of the month?

What if I want this dates?

```<code>datetime.datetime(2011, 2, 28) //should return 4
datetime.datetime(2011, 8, 29) //should return 5
</code>```

I understand that only February has 4 weeks if the given date is in a leap year (bissextile)

答:
To take into account the comment of @Usagi:

```<code>datetime.datetime(2011, 8, 15) // should return 3
datetime.datetime(2011, 2, 28) // should return 5
datetime.datetime(2011, 8, 29) // should return 5
</code>```

The following equation manage that the first day of a month is not necessary a monday:

```<code>(d.day-d.weekday() -2)//7+2
</code>```

The -2 and +2 allow to get a week number between 1 and 6

Title: Python: Number of the Week in a Month

Body:
When specifying a date:

datetime.datetime(2011, 8, 15)

How can i get to know that this is the third week of the month?

What if I want this dates?

datetime.datetime(2011, 2, 28) //should return 4
datetime.datetime(2011, 8, 29) //should return 5

I understand that only February has 4 weeks if the given date is in a leap year (bissextile)

Body:
To take into account the comment of @Usagi:

datetime.datetime(2011, 8, 15) // should return 3
datetime.datetime(2011, 2, 28) // should return 5
datetime.datetime(2011, 8, 29) // should return 5

The following equation manage that the first day of a month is not necessary a monday:

(d.day-d.weekday() -2)//7+2

The -2 and +2 allow to get a week number between 1 and 6


问:
C programming : dereferencing pointers
I have these three files. using structures, functions and pointers.

Trying to do this:

void getName(Name *) - Receives a pointer to a Name and performs the actions

contacts.h

```<code>struct Name {
char firstName[31];
char middleInitial[7];
char lastName[36];
};
struct Contacts {
struct Name name;
struct Address address;
struct Numbers numbers;
};
void getName(struct Name*name);
</code>```

contacts.c

```<code>#include <stdio.h>
#include "contacts.h"

void getName(struct Name*name)
{
    char yorn;
        printf("Please enter the contact's first name: ");
scanf("%s", name->firstName);

printf("Do you want to enter a middle initial(s)? (y or n): ");
scanf("%s", &yorn);

if (yorn == 'y'){
    printf("Please enter the contact's middle initial(s): ");
    scanf("%s", name->middleInitial);
}

printf("Please enter the contact's last name: ");
scanf("%s", name->lastName);
}
</code>```

a1ms4.c

```<code>#include <stdio.h>
#include "contacts.h"
#include "contacts.c"

struct Name name;
getName(&contact.name);
</code>```

I'm getting the following error in contacts.c:

error: dereferencing pointer to incomplete type struct Name

scanf("%s", name->firstName);

```<code>                 ^~
</code>```

[EDIT:
I minimized the code to this:

```<code>#include <stdio.h>

struct Name {
char firstName[31];
};

struct Contacts {

struct Name name;
};

void getName(Name*name);

int main(void)
{

struct Contacts contact;
getName(&contact.name);
return 0;
}

void getName(Name*name)
{
char yorn;
printf("Please enter the contact's first name: ");
scanf("%c", name->firstName);

printf("First name: %c\n", name.firstName);

return;
}
</code>```

and getting these error:

1). error: unknown type name âNameâ

void getName(Name*name);

2). In function âmainâ:

warning: implicit declaration of function âgetNameâ; did you mean âgetlineâ? [-Wimplicit-function-declaration]

getName(&contact.name);

3). At top level:

error: unknown type name âNameâ

void getName(Name*name)

答: There are quite a few things wrong but I think your main error is that you have declared Name as struct Name so you need to use struct Name instead of just Name.

Title: C programming : dereferencing pointers

Body:
I have these three files. using structures, functions and pointers.

Trying to do this:

void getName(Name *) - Receives a pointer to a Name and performs the actions

contacts.h

struct Name {
char firstName[31];
char middleInitial[7];
char lastName[36];
};
struct Contacts {
struct Name name;
struct Address address;
struct Numbers numbers;
};
void getName(struct Name*name);

contacts.c

#include <stdio.h>
#include "contacts.h"

void getName(struct Name*name)
{
    char yorn;
        printf("Please enter the contact's first name: ");
scanf("%s", name->firstName);

printf("Do you want to enter a middle initial(s)? (y or n): ");
scanf("%s", &yorn);

if (yorn == 'y'){
    printf("Please enter the contact's middle initial(s): ");
    scanf("%s", name->middleInitial);
}

printf("Please enter the contact's last name: ");
scanf("%s", name->lastName);
}

a1ms4.c

#include <stdio.h>
#include "contacts.h"
#include "contacts.c"

struct Name name;
getName(&contact.name);

I'm getting the following error in contacts.c:

error: dereferencing pointer to incomplete type struct Name

scanf("%s", name->firstName);

                 ^~

[EDIT:
I minimized the code to this:

#include <stdio.h>

struct Name {
char firstName[31];
};

struct Contacts {

struct Name name;
};

void getName(Name*name);

int main(void)
{

struct Contacts contact;
getName(&contact.name);
return 0;
}

void getName(Name*name)
{
char yorn;
printf("Please enter the contact's first name: ");
scanf("%c", name->firstName);

printf("First name: %c\n", name.firstName);

return;
}

and getting these error:

1). error: unknown type name âNameâ

void getName(Name*name);

2). In function âmainâ:

warning: implicit declaration of function âgetNameâ; did you mean âgetlineâ? [-Wimplicit-function-declaration]

getName(&contact.name);

3). At top level:

error: unknown type name âNameâ

void getName(Name*name)


答:
When you say struct Foo {...}; in C, you are not defining a type with the name Foo. Instead, you are defining a struct by the name Foo **which is referenced as struct Foo.

Thus, when you say void getName(Name*name);, your compiler rightly complains that there is no type called Name. Since it could not parse this function declaration, it subsequently complains about not knowing about that function when you call it. Ignore that second error, it's not your problem. Fix the prototype.

There are two methods of fixing your program:

Call your structs struct. At each and every instance where you have Name in your code, ensure that you are actually saying struct Name instead.

Write a typedef that defines the type Name. Declare your struct like this:

```<code>struct Foo { ... };
typedef struct Foo Foo;
</code>```

Since C programmers are lazy gits, they will usually merge these two statements into the following declaration:

```<code>typedef struct Foo { ... } Foo;
</code>```

This declares both the struct Foo and its alias Foo in a single statement. You'll see this a lot in real code.

The form of the typedef deserves some explanation. I find it easiest to think of it as a variable declaration with typedef prepended to turn the variable name into a type name. I.e. if you can declare an array of strings with

```<code>char* array[10];
</code>```

then you can give a name to its type with

```<code>typedef char* ArrayType[10];
</code>```

After that, you can declare the above array with a simple

```<code>ArrayType array;
</code>```

So, when you say

```<code>typedef struct Foo Foo;
</code>```

the second Foo is the name that is being declared, and the type it aliases is the rest of the declaration without the typedef: struct Foo.

Title: C programming : dereferencing pointers

Body:
When you say struct Foo {...}; in C, you are not defining a type with the name Foo. Instead, you are defining a struct by the name Foo **which is referenced as struct Foo.

Thus, when you say void getName(Name*name);, your compiler rightly complains that there is no type called Name. Since it could not parse this function declaration, it subsequently complains about not knowing about that function when you call it. Ignore that second error, it's not your problem. Fix the prototype.

There are two methods of fixing your program:

Call your structs struct. At each and every instance where you have Name in your code, ensure that you are actually saying struct Name instead.

Write a typedef that defines the type Name. Declare your struct like this:

struct Foo { ... };
typedef struct Foo Foo;

Since C programmers are lazy gits, they will usually merge these two statements into the following declaration:

typedef struct Foo { ... } Foo;

This declares both the struct Foo and its alias Foo in a single statement. You'll see this a lot in real code.

The form of the typedef deserves some explanation. I find it easiest to think of it as a variable declaration with typedef prepended to turn the variable name into a type name. I.e. if you can declare an array of strings with

char* array[10];

then you can give a name to its type with

typedef char* ArrayType[10];

After that, you can declare the above array with a simple

ArrayType array;

So, when you say

typedef struct Foo Foo;

the second Foo is the name that is being declared, and the type it aliases is the rest of the declaration without the typedef: struct Foo.


问:
ModuleNotFoundError: No module named 'pyperclip'
Similar issues like this have been posted on StackOverflow but I did not find adequate answers to resolve this issue.

I'm running Python 3.6.3 on a Windows 7 machine.  From IDLE I type the following import stmt and get the subsequent error:

```<code>>>> import pyperclip
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    import pyperclip
ModuleNotFoundError: No module named 'pyperclip'
</code>```

I tried hitting Win-R (to pup up the RUN window) and typed the following:

```<code>pip3 install pyperclip
pip install pyperclip
</code>```

But it gives me an error saying "Could not fetch the URL: https://pypi.python.org/simple/pyperclip/
Could not find a version that satisfies the requirement pyperclip... No Matching distribution found"

If I visit the URL mentioned (https://pypi.python.org/simple/pyperclip/) I see a bunch of pyperclip ZIP files all dif versions.  But if I select a version I'm not sure where to place them/extract them or if extracting them is even the right thing to do.

Any advice?

答:
For manual Installation,

I went to the link you provided in your question.

Since all of them are pyperclip 1.5, I wouldn't mind downloading any one of them.

However, the person who designed the site must want you to click on the topmost link, instead of scrolling all the way down.

So I downloaded the 1.5.11 version, which was on the top.

And on downloading (I am using my phone) I quickly extracted the zip and saw a nice setup.py file there.

Btw, I wouldn't worry where to unzip or run the setup.py file.

Go ahead and run the setup.py and let it take its time.

Once done, still not working in IDLE? I suggest use CMD(windows) or Terminal(Linux) and check if it is working there, and then come back to me.

Edit: On having problems installing the setup.py, open CMD as administrator by right clicking and selecting it from the start menu.

Navigate to the directory where setup.py is located and run it inside the CMD, by typing 'setup.py' and press Enter.

Body:
Similar issues like this have been posted on StackOverflow but I did not find adequate answers to resolve this issue.

I'm running Python 3.6.3 on a Windows 7 machine.  From IDLE I type the following import stmt and get the subsequent error:

>>> import pyperclip
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    import pyperclip
ModuleNotFoundError: No module named 'pyperclip'

I tried hitting Win-R (to pup up the RUN window) and typed the following:

pip3 install pyperclip
pip install pyperclip

But it gives me an error saying "Could not fetch the URL: https://pypi.python.org/simple/pyperclip/
Could not find a version that satisfies the requirement pyperclip... No Matching distribution found"

If I visit the URL mentioned (https://pypi.python.org/simple/pyperclip/) I see a bunch of pyperclip ZIP files all dif versions.  But if I select a version I'm not sure where to place them/extract them or if extracting them is even the right thing to do.

Any advice?


问:
Delete multiple Core Data objects: Issue with NSFetchedResultsController
I have found a fix for this, but I'm not really liking the fix. My issue goes like this. I am using a NSFetchedResultsController to populate a UICollectionView-- which displays a collection of images. Each image is described by a Core Data object (e.g., its file name is in the Core Data object).

I have UI controls that allow a user to delete multiple images at the same time, and was having a problem when the user would delete more than one object. The code to do the deletion was:

```<code>    for image in images {
       CoreData.sessionNamed(CoreDataExtras.sessionName).remove(image)
    }

    CoreData.sessionNamed(CoreDataExtras.sessionName).saveContext()
</code>```

(Some of this is my library code).
With the deletion of two objects, I get a crash and the following log message:

CoreData: error: Serious application error. Exception was caught
  during Core Data change processing. This is usually a bug within an
  observer of NSManagedObjectContextObjectsDidChangeNotification.
  Invalid update: invalid number of items in section 0. The number of
  items contained in an existing section after the update (99) must be
  equal to the number of items contained in that section before the
  update (101), plus or minus the number of items inserted or deleted
  from that section (0 inserted, 1 deleted) and plus or minus the number
  of items moved into or out of that section (0 moved in, 0 moved out).
  with userInfo (null)

What fixes the problem is if I change the deletion code to:

```<code>    for image in images {
        CoreData.sessionNamed(CoreDataExtras.sessionName).remove(image)
        CoreData.sessionNamed(CoreDataExtras.sessionName).saveContext()
    }
</code>```

I guess the problem is that in the delegate callback method:

```<code>- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
       atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
      newIndexPath:(NSIndexPath *)newIndexPath {
</code>```

I do:

```<code>collectionView.deleteItems(at: [indexPath])
</code>```

Apparently, you can either do a reloadItems in the didChangeObject method, or you can do a saveContext after each object deletion.

答:
If you delete several images, and then save the context, the FRC processes all the deletions - so its sections, fetchedObjects, etc, reflect all those changes.  But it then calls the didChangeObject: delegate method separately for each change.  In that method, you call the collectionView update methods (eg. deleteItems); the collectionView then calls its dataSource methods and does a quick tally up: there were X items, Y items were deleted, there are now Z items and throws an error because Z != X-Y.

When a FRC is used with a tableView, this problem is overcome by using the tableView beginUpdates and endUpdates calls in the FRC controllerWillChangeContent: and controllerDidChangeContent: delegate methods.  This causes the tableView to defer doing the tally up until ALL the individual changes have been processed - at which point the numbers do add up.

Your solution - to call saveContext after each deletion - causes the FRC to process each deletion in turn: updating its sections, fetchedObjects, etc, to reflect only one deletion at a time.  This keeps the FRC's data in sync with the collectionView.  One possible refinement would be to call processPendingChanges on the context after each deletion, instead of saving the context.  This avoids saving data when you might not want to, but nonetheless causes each deletion to be processed separately.

The alternative is to mimic the tableView's beginUpdates/endUpdates mechanism for holding all the collectionView updates until all the FRC updates have been processed.  This works broadly as follows:

Create arrays to keep track of the changes (inserts, deletes).

Each time didChangeObject: is called, add the corresponding indexPath to the relevant array.

When controllerDidChangeContent: is called, iterate through the arrays (deletions first, when inserts) calling the corresponding collectionView update methods. (Then empty the arrays ready for the next batch of updates).

Some good explanations and potential implementations are included in this question and its answers.

Body:
I have found a fix for this, but I'm not really liking the fix. My issue goes like this. I am using a NSFetchedResultsController to populate a UICollectionView-- which displays a collection of images. Each image is described by a Core Data object (e.g., its file name is in the Core Data object).

I have UI controls that allow a user to delete multiple images at the same time, and was having a problem when the user would delete more than one object. The code to do the deletion was:

    for image in images {
       CoreData.sessionNamed(CoreDataExtras.sessionName).remove(image)
    }

    CoreData.sessionNamed(CoreDataExtras.sessionName).saveContext()

(Some of this is my library code).
With the deletion of two objects, I get a crash and the following log message:

CoreData: error: Serious application error. Exception was caught
  during Core Data change processing. This is usually a bug within an
  observer of NSManagedObjectContextObjectsDidChangeNotification.
  Invalid update: invalid number of items in section 0. The number of
  items contained in an existing section after the update (99) must be
  equal to the number of items contained in that section before the
  update (101), plus or minus the number of items inserted or deleted
  from that section (0 inserted, 1 deleted) and plus or minus the number
  of items moved into or out of that section (0 moved in, 0 moved out).
  with userInfo (null)

What fixes the problem is if I change the deletion code to:

    for image in images {
        CoreData.sessionNamed(CoreDataExtras.sessionName).remove(image)
        CoreData.sessionNamed(CoreDataExtras.sessionName).saveContext()
    }

I guess the problem is that in the delegate callback method:

- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
       atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
      newIndexPath:(NSIndexPath *)newIndexPath {

I do:

collectionView.deleteItems(at: [indexPath])

Apparently, you can either do a reloadItems in the didChangeObject method, or you can do a saveContext after each object deletion.


问:
Prevent onbeforeunload dialog from interfering with tests
I am looking to disable the dialog that spawns from onbeforeunload in the instance of Chrome spun up by Capybara. I have a very large test suite and it would be impractical to modify every visit/refresh to include code to click the ‘Leave’ confirmation.

I have tried adding page.execute_script ‘window.onbeforeunload = undefined;’ before visits and refreshes, and while this works, it shares the problem of having to modify all my visit and refresh calls.

I also checked to see if there are any Chrome CLI options I could add to disable this functionality, but I didn’t find anything relevant. I checked here: https://peter.sh/experiments/chromium-command-line-switches/ but after searching for unload, alert, and dialog, nothing that matched seemed relevant.

I am on Chromedriver v2.33, Chrome 62, Capybara 2.5 and Selenium-webdriver 2.53.4. Will update this post with more info if needed.

Is this possible?

答:
To make Capybaras visit and refresh methods always call your execute_script first the easiest solution would be something like

```<code>module BeforeUnloadDisabler
  def visit(*args)
    execute_script 'window.onbeforeunload = undefined;'
    super
  end

  def refresh(*args)
    execute_script 'window.onbeforeunload = undefined;'
    super
  end
end

::Capybara::Session.prepend(BeforeUnloadDisabler)
</code>```

Although, if your app is registering beforeunload alerts that much you might want to reconsider your design choices -- that can be really annoying for users.

Body:
To make Capybaras visit and refresh methods always call your execute_script first the easiest solution would be something like

module BeforeUnloadDisabler
  def visit(*args)
    execute_script 'window.onbeforeunload = undefined;'
    super
  end

  def refresh(*args)
    execute_script 'window.onbeforeunload = undefined;'
    super
  end
end

::Capybara::Session.prepend(BeforeUnloadDisabler)

Although, if your app is registering beforeunload alerts that much you might want to reconsider your design choices -- that can be really annoying for users.


问:
PHP variable containing conditional statement
I'm using jQuery's Query Builder from here http://querybuilder.js.org/demo.html and my main page is written in PHP. I've used the query builder to basically specify conditions that I would like to use in my conditional statements.

I'm not too far from converting the input into the format (((A == B) && (C != A)) || (D == E)) as an example. For this I've used most of this solution. https://stackoverflow.com/a/26607204/1724376

Now I'm stuck thinking I may have gone down the wrong path as I could append "$" to the variables and potentially use eval() but that's something I really don't want to do even though this will be an internal site.

There are 36 variables so I can't think of any other solution to build the conditional statement either since there could be multiple permutations of what the user wants to (and should be able to) use as the conditions.

I'm afraid the answer will be that eval() is the only choice but as a last ditch effort before I toss out hours of work, I figured I'd ask folks a lot smarter than me.

Guidance will be appreciated.

Edit: My end goal is to allow a jQuery query builder-ish UI to allow the user to specify the exact conditions under which one specific function will be executed. That function will not change, but the conditions may. The user should not need to modify code.

答:
After much research, I've only been able to find eval() as a viable approach. I'm sanitizing the input by limiting the size of the variable, comparing it against what I know to be valid options from the select statements, and also verifying that the input doesn't contain anything besides letters and numbers.

I wish there was a better option but this approach seems to work for now.


问:
whitespace on top of shiny dashboard
I'm trying to create a shiny dashboard page and whenever I put text into dashboard body part, there is a huge chunk of whitespace that I would like to remove. Here is a picture of the dashboard:

There's the spacing between the testing and the top bar. I'm wondering how I can remove that spacing? Of course I don't want it to be all crammed/close together, but I don't want a huge block of whitespace at the top. Here is my coding for the dashboard:

```<code>dashboardHeader(title = "Title"),

dashboardSidebar(width = 270,
  sidebarMenu(
    menuItem("Home", tabName = "home", icon = icon("home"))
  ),

dashboardBody(
    tabItem(tabName = "home",
            h4("testing")
    )
)
</code>```

I've tried to do a css file and do padding-top and margin, it didn't work out and turned out messy. Anyone know how to fix this?

答:
h1, h2, h3, h4 generally come with a margin-top.

try css-

```<code>h4 {
    margin-top: 0;
}
</code>```

Title: whitespace on top of shiny dashboard

Body:
I'm trying to create a shiny dashboard page and whenever I put text into dashboard body part, there is a huge chunk of whitespace that I would like to remove. Here is a picture of the dashboard:

There's the spacing between the testing and the top bar. I'm wondering how I can remove that spacing? Of course I don't want it to be all crammed/close together, but I don't want a huge block of whitespace at the top. Here is my coding for the dashboard:

dashboardHeader(title = "Title"),

dashboardSidebar(width = 270,
  sidebarMenu(
    menuItem("Home", tabName = "home", icon = icon("home"))
  ),

dashboardBody(
    tabItem(tabName = "home",
            h4("testing")
    )
)

I've tried to do a css file and do padding-top and margin, it didn't work out and turned out messy. Anyone know how to fix this?

Body:
h1, h2, h3, h4 generally come with a margin-top.

try css-

h4 {
    margin-top: 0;
}


问:
Iterate through Json Object with nested Array Javascript
I need to iterate this json and push the values into an other array

```<code>[
{
    "id": 1,
    "nombre": "Samson",
    "marcaModelo": [
        {
            "id": 6,
            "nombre": "API 6D "
        }
    ]
}
{
    "id": 6,
    "nombre": "Endress + Hauser",
    "marcaModelo": [
        {
            "id": 10,
            "nombre": "Proline t-mass 65F50-AK2AH1RCBBCA"
        },
        {
            "id": 8,
            "nombre": "Cerabar M"
        }
    ]
}
]
</code>```

I made out with this

```<code>Object.entries(res).forEach((value, key) => {
      console.log(key, value)
      this.marcas.push({
        'marcaId': res[key].id,
        'marcaNombre': res[key].nombre,
        'modeloId': res[key].marcaModelo[0].id,
        'modeloNombre': res[key].marcaModelo[0].nombre
      })
      console.log(this.marcas)
    })
</code>```

but only push one marcaModelo object into marcas array, if I replace marcaModelo[0] for marcaModelo[key] I get an undefined.

I need something like this

```<code>{
marcaId:6
marcaNombre:"Endress + Hauser"
modeloId:[10, 8]
modeloNombre:[Proline t-mass 65F50-AK2AH1RCBBCA, Cerabar M]
}
</code>```

答:
or</p>

```<code>res.map(({ id, nombre, marcaModelo }) => ({
    marcaId: id,
    marcaNombre: nombre,
    modeloId: marcaModelo.map(m => m.id),
    modeloNombre: marcaModelo.map(m => m.nombre),
}));
</code>```

Body:
I need to iterate this json and push the values into an other array

[
{
    "id": 1,
    "nombre": "Samson",
    "marcaModelo": [
        {
            "id": 6,
            "nombre": "API 6D "
        }
    ]
}
{
    "id": 6,
    "nombre": "Endress + Hauser",
    "marcaModelo": [
        {
            "id": 10,
            "nombre": "Proline t-mass 65F50-AK2AH1RCBBCA"
        },
        {
            "id": 8,
            "nombre": "Cerabar M"
        }
    ]
}
]

I made out with this

Object.entries(res).forEach((value, key) => {
      console.log(key, value)
      this.marcas.push({
        'marcaId': res[key].id,
        'marcaNombre': res[key].nombre,
        'modeloId': res[key].marcaModelo[0].id,
        'modeloNombre': res[key].marcaModelo[0].nombre
      })
      console.log(this.marcas)
    })

but only push one marcaModelo object into marcas array, if I replace marcaModelo[0] for marcaModelo[key] I get an undefined.

I need something like this

{
marcaId:6
marcaNombre:"Endress + Hauser"
modeloId:[10, 8]
modeloNombre:[Proline t-mass 65F50-AK2AH1RCBBCA, Cerabar M]
}

Body:
or

res.map(({ id, nombre, marcaModelo }) => ({
    marcaId: id,
    marcaNombre: nombre,
    modeloId: marcaModelo.map(m => m.id),
    modeloNombre: marcaModelo.map(m => m.nombre),
}));


问:
ClassNotFoundException when reading object from ObjectInputStream
I am pretty new to Spring MVC and webapps in general. I have been trying to make a project that reads an object through a socket's output stream. When I try the socket connection and my object in a separate project with just a simple main class, inputStream.readObject() works out and reads out the TradeRecord. But when I combine it in my test Springmvc project, I get a ClassNotFoundException for my TradeRecord.

Part of my controller.java class:

```<code>public void readRecord(){
    try {
        Socket socket = connectServer();
        ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());
        while (true) {
            TradeRecord rec = (TradeRecord) inputStream.readObject();
            System.out.println(inputStream.readObject());
        }
    } catch (SocketException se) {
        se.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e){
        e.printStackTrace();
    }
}
</code>```

TradeRecord class which is copied directly from the person sending the object:

```<code>package models;
import java.io.Serializable;

public class TradeRecord implements Serializable
{
    public static final int STATUS = 0;
    ...
    public String TradeID;
    public char OrdStatus;
    public char TimeInForce;
    ...

    public int timeOnList = 0;
    public String venueID = "";
    public String sourceID = "";
    public String errMsg = "";
}
</code>```

dispatcher:

```<code><mvc:annotation-driven />
<context:component-scan base-package="controllers"/>
<mvc:resources mapping="/bootstrap/**" location="/bootstrap/" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</code>```

web.xml:

```<code><context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
</code>```

and the error:

```<code>java.lang.ClassNotFoundException: TradeRecord
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1702)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1547)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at java.io.ObjectInputStream.resolveClass(ObjectInputStream.java:626)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1613)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1518)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1774)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1351)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:371)
</code>```

I have tried to make the TradeRecord into a jar and manually adding it to my external libraries, under the lib of my WEB-INF, and under the lib in Tomcat (in separate occasions). I also tried to put the POJO under the base controllers package just to see if it can be found there but none of it worked. Any help would be greatly appreciated. Thanks!

edit* I am currently using Intellij IDEA 2017.1.1 and building with maven.

答: Tomcat can't find the TradeRecord class because it isn't there. The only 'configuration' required is to put it into the same package at source and destination and include the class in the WAR or one of its dependent JARs in its lib directory.

Body:
I am pretty new to Spring MVC and webapps in general. I have been trying to make a project that reads an object through a socket's output stream. When I try the socket connection and my object in a separate project with just a simple main class, inputStream.readObject() works out and reads out the TradeRecord. But when I combine it in my test Springmvc project, I get a ClassNotFoundException for my TradeRecord.

Part of my controller.java class:

public void readRecord(){
    try {
        Socket socket = connectServer();
        ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());
        while (true) {
            TradeRecord rec = (TradeRecord) inputStream.readObject();
            System.out.println(inputStream.readObject());
        }
    } catch (SocketException se) {
        se.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e){
        e.printStackTrace();
    }
}

TradeRecord class which is copied directly from the person sending the object:

package models;
import java.io.Serializable;

public class TradeRecord implements Serializable
{
    public static final int STATUS = 0;
    ...
    public String TradeID;
    public char OrdStatus;
    public char TimeInForce;
    ...

    public int timeOnList = 0;
    public String venueID = "";
    public String sourceID = "";
    public String errMsg = "";
}

dispatcher:

<mvc:annotation-driven />
<context:component-scan base-package="controllers"/>
<mvc:resources mapping="/bootstrap/**" location="/bootstrap/" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>

web.xml:

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

and the error:

java.lang.ClassNotFoundException: TradeRecord
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1702)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1547)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at java.io.ObjectInputStream.resolveClass(ObjectInputStream.java:626)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1613)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1518)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1774)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1351)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:371)

I have tried to make the TradeRecord into a jar and manually adding it to my external libraries, under the lib of my WEB-INF, and under the lib in Tomcat (in separate occasions). I also tried to put the POJO under the base controllers package just to see if it can be found there but none of it worked. Any help would be greatly appreciated. Thanks!

edit* I am currently using Intellij IDEA 2017.1.1 and building with maven.


问:
What is the difference between OCI and THIN driver connection with data source connection between java and oracle XE?
I'm writing the below codes for connection between the java and Oracle 10g XE using 3 way(OCI, THIN and data source), the code is running successfully but don't know difference between the THIN and OCI with data source connection.

1-

```<code>public static void main (String args[]) throws SQLException
 {
  OracleDataSource ods = new OracleDataSource();
  ods.setURL("jdbc:oracle:thin:hr/hr@localhost:1521/XE");
  Connection con = ods.getConnection();
  System.out.println("Connected");
  con.close();
 }
</code>```

2-

```<code>public static void main(String args[])
     {
      try
      {
       // load oracle driver
      Class.forName("oracle.jdbc.driver.OracleDriver");
      // connect using Thin driver
      Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","hr","hr");
      System.out.println("Connected Successfully To Oracle");
      con.close();
      }
      catch(Exception ex)
      {
        ex.printStackTrace();
      }
 }
</code>```

3-

```<code>public static void main(String args[])
     {
      try
      {
       // load oracle driver
      Class.forName("oracle.jdbc.driver.OracleDriver");
      // connect using Native-API (OCI) driver
      Connection con = DriverManager.getConnection("jdbc:oracle:oci:@","hr","hr" );
      System.out.println("Connected Successfully To Oracle using OCI driver");
      con.close();
      }
      catch(Exception ex)
      {
        ex.printStackTrace();
      }
 }
</code>```

答: Both the JDBC thin driver and the JDBC OCI driver speak the same network protocol. From the server standpoint there is no difference between the two. The JDBC thin driver is 100% Java and comes in a single standalone jar (some extra jars will be needed for advanced features). The JDBC OCI driver makes JNI calls to the OCI C client library and hence depends on the Oracle full client to be installed (OCI is also what sqlplus uses). Oracle recommends to use the JDBC thin driver which is what most customers use. It's the fastest driver and the most robust one.</p>

Body:
I'm writing the below codes for connection between the java and Oracle 10g XE using 3 way(OCI, THIN and data source), the code is running successfully but don't know difference between the THIN and OCI with data source connection.

1-

public static void main (String args[]) throws SQLException
 {
  OracleDataSource ods = new OracleDataSource();
  ods.setURL("jdbc:oracle:thin:hr/hr@localhost:1521/XE");
  Connection con = ods.getConnection();
  System.out.println("Connected");
  con.close();
 }

2-

public static void main(String args[])
     {
      try
      {
       // load oracle driver
      Class.forName("oracle.jdbc.driver.OracleDriver");
      // connect using Thin driver
      Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","hr","hr");
      System.out.println("Connected Successfully To Oracle");
      con.close();
      }
      catch(Exception ex)
      {
        ex.printStackTrace();
      }
 }

3-

public static void main(String args[])
     {
      try
      {
       // load oracle driver
      Class.forName("oracle.jdbc.driver.OracleDriver");
      // connect using Native-API (OCI) driver
      Connection con = DriverManager.getConnection("jdbc:oracle:oci:@","hr","hr" );
      System.out.println("Connected Successfully To Oracle using OCI driver");
      con.close();
      }
      catch(Exception ex)
      {
        ex.printStackTrace();
      }
 }

ContentLicense: CC BY-SA 4.0


问:
In angular-cli, how does the "lazy" attribute work to load global libraries?
By adding them to the scripts property of .angular-cli file, one can load global scripts into your app. This example comes from the documentation:

```<code>"scripts": [
  "global-script.js",
  { "input": "lazy-script.js", "lazy": true },
  { "input": "pre-rename-script.js", "output": "renamed-script" },
]
</code>```

I am however a bit confused by the "lazy" attribute. When building your app, the to-be-lazy-loaded script is no longer packaged in the scripts.bundle.js file.

But how will the library then be loaded after all? What do I have to do to load the file when necessary?

答:
As an alternative to manipulating the DOM in step #2 of Will Huang's accepted answer, it's now also possible to use the dynamic import functionality of esnext with TypeScript, as outlined in this post.

Using this approach, one could then add the following to a lazy-loaded NgModule:

```<code>import('jquery')
    .then((module: Function) => {
        window['$'] = module;
    });
</code>```

Body:
By adding them to the scripts property of .angular-cli file, one can load global scripts into your app. This example comes from the documentation:

"scripts": [
  "global-script.js",
  { "input": "lazy-script.js", "lazy": true },
  { "input": "pre-rename-script.js", "output": "renamed-script" },
]

I am however a bit confused by the "lazy" attribute. When building your app, the to-be-lazy-loaded script is no longer packaged in the scripts.bundle.js file.

But how will the library then be loaded after all? What do I have to do to load the file when necessary?

Body:
As an alternative to manipulating the DOM in step #2 of Will Huang's accepted answer, it's now also possible to use the dynamic import functionality of esnext with TypeScript, as outlined in this post.

Using this approach, one could then add the following to a lazy-loaded NgModule:

import('jquery')
    .then((module: Function) => {
        window['$'] = module;
    });


问:
Merge cells with pandas
I want to remove duplicated cells with merge them all because they point out subelements.
For example I have a df like this:

```<code>|   | Customer ID | Category      | VALUE   |
| -:|:----------- |:------------- | -------:|
| 0 | HETO90      | Baby Sets     |  1000.0 |
| 1 | HETO90      | Girls Dresses |  5356.0 |
| 2 | HETO90      | Girls Jumpers |  2822.0 |
| 3 | HETO90      | Girls Top     | 13398.0 |
| 4 | HETO90      | Shorts        |  7590.0 |
</code>```

I just want to merge HET090 to the one. Like this:

```<code>|   | Customer ID | Category      | VALUE   |
| -:|:----------- |:------------- | -------:|
| 0 |             | Baby Sets     |  1000.0 |
| 1 |             | Girls Dresses |  5356.0 |
| 2 | HETO90      | Girls Jumpers |  2822.0 |
| 3 |             | Girls Top     | 13398.0 |
| 4 |             | Shorts        |  7590.0 |
</code>```

答:
In pandas the inner most index must label each row.

```<code>df = df.set_index('Customer ID', append=True).swaplevel(0,1)
</code>```

Output:

```<code>                    Category    VALUE
Customer ID
HETO90      0      Baby Sets   1000.0
            1  Girls Dresses   5356.0
            2  Girls Jumpers   2822.0
            3      Girls Top  13398.0
            4         Shorts   7590.0
</code>```

Title: Merge cells with pandas

Body:
I want to remove duplicated cells with merge them all because they point out subelements.
For example I have a df like this:

|   | Customer ID | Category      | VALUE   |
| -:|:----------- |:------------- | -------:|
| 0 | HETO90      | Baby Sets     |  1000.0 |
| 1 | HETO90      | Girls Dresses |  5356.0 |
| 2 | HETO90      | Girls Jumpers |  2822.0 |
| 3 | HETO90      | Girls Top     | 13398.0 |
| 4 | HETO90      | Shorts        |  7590.0 |

I just want to merge HET090 to the one. Like this:

|   | Customer ID | Category      | VALUE   |
| -:|:----------- |:------------- | -------:|
| 0 |             | Baby Sets     |  1000.0 |
| 1 |             | Girls Dresses |  5356.0 |
| 2 | HETO90      | Girls Jumpers |  2822.0 |
| 3 |             | Girls Top     | 13398.0 |
| 4 |             | Shorts        |  7590.0 |

Body:
In pandas the inner most index must label each row.

df = df.set_index('Customer ID', append=True).swaplevel(0,1)

Output:

                    Category    VALUE
Customer ID
HETO90      0      Baby Sets   1000.0
            1  Girls Dresses   5356.0
            2  Girls Jumpers   2822.0
            3      Girls Top  13398.0
            4         Shorts   7590.0


问:
Routing Failover
I'm new at mikrotik, just configured wan1 as ether1 and wan2 as lte, If I unplug cable from ether1 it automatically connects to wan2 (lte1), but how to do that automatically change route to wan2 (lte) if no internet connection. (I've checked tutorial wiki of Advanced Routing Failover without Scripting) but cannot understand what to replace with GW1, GW2, Host1, Host2, ISP1, ISP2, Host1A, Host1B, Host2A, Host2B...? see screenshot:

答:
```<code>/ip route
add dst-address=8.8.8.8 gateway=192.168.0.1 scope=10 target-scope=10
add dst-address=0.0.0.0/0 gateway=8.8.8.8 distance=1 check-gateway=ping
add dst-address=0.0.0.0/0 gateway=192.168.1.1 distance=5
</code>```

It will ping 8.8.8.8 via wan1. If 2 ping fails its switch to lte. Then if lte is up and 8.8.8.8 ping again, its switch def route to lte.

Title: Routing Failover

Body:
/ip route
add dst-address=8.8.8.8 gateway=192.168.0.1 scope=10 target-scope=10
add dst-address=0.0.0.0/0 gateway=8.8.8.8 distance=1 check-gateway=ping
add dst-address=0.0.0.0/0 gateway=192.168.1.1 distance=5

It will ping 8.8.8.8 via wan1. If 2 ping fails its switch to lte. Then if lte is up and 8.8.8.8 ping again, its switch def route to lte.


问:
Creating Step Builder with ByteBuddy
I'm trying to get ByteBuddy to implement a step builder, given an interface for that builder. I'm stuck on 2 places.

How to create a setter that returns the current instance for method chaining?

I started with:

```<code>.method(ElementMatchers.isSetter())
.intercept(FieldAccessor.ofBeanProperty());
</code>```

only I'd like to return the current builder instance so we can chain calls like:

```<code>final Object obj = ...builder().id(100).name("test").build();
</code>```

so instead I created an interceptor like this, which seems like a hack and I'd like to avoid reflection where possible:

```<code>@RuntimeType
public Object intercept(@RuntimeType Object arg, @This Object source, @Origin Method method)
{
  try
  {
    // Field name is same as method name.
    final Field field = source.getClass().getDeclaredField(method.getName());
    field.setAccessible(true);
    field.set(source, arg);
  }
  catch (Throwable ex)
  {
    throw new Error(ex);
  }

  // Return current builder instance.
  return source;
}
</code>```

Is there an easy way to access defined fields on a class I'm defining without reflection?

Currently I add fields to the builder class in a loop and my build method on the builder is intercepted like this:

```<code>private static final class InterBuilder
{
  private final Collection<String> fields;
  private final Constructor<?> constructor;

  InterBuilder(final Constructor<?> constructor, final Collection<String> fields)
  {
    this.constructor = constructor;
    this.fields = fields;
  }

  @RuntimeType
  public Object intercept(@This Object source, @Origin Method method)
  {
    try
    {
      final Object[] args = Arrays.stream(source.getClass().getDeclaredFields())
        .filter(f -> this.fields.contains(f.getName()))
        .map(f ->  { try {
          f.setAccessible(true);
          return f.get(source); }
          catch (Throwable ex) { throw new Error(ex); } })
        .toArray();

      // Invoke a constructor passing in the private field values from the builder...
      return this.constructor.newInstance(args);
    }
    catch (Throwable ex)
    {
      throw new Error(ex);
    }
  }
}
</code>```

I saw the @FieldValue annoation. I don't suppose there is something that will give me all fields without knowing their names up front?

The code is a proof of concept at this point. Are there better ways to do what I'm doing here?

Thank you!

答:
Rafael gave me the information I needed to come up with a solution, so the answer credit goes to him, but I wanted to include my solution for anyone else to discover in the future.</p>

```<code>DynamicType.Builder<?> builder = new ByteBuddy()
  .subclass(Object.class)
  .implement(interfaces)
  .name(builderClassName);

// Find all of the setters on the builder...
// Here I'm assuming all field names match setter names like:
//   MyClass x = theBuilder.name("hi").id(1000).isValid(true).build();
final List<Method> setters = ...

for (final Method setter : setters)
{
  // This will define a field and a setter that will set the value and return the current instance.
  builder = builder
    .defineField(setter.getName(), setter.getParameterTypes()[0], Visibility.PRIVATE)
    .define(setter)
    .intercept(FieldAccessor.ofField(setter.getName()).setsArgumentAt(0).andThen(FixedValue.self()));
}

// Find the "build" method on the builder.
final Method buildMethod = ...

// Get a constructor that you want the builder to call and return the new instance.
final Constructor<?> constructor = ...

// Get the field names from the setters.
final List<String> fieldNames = setters.stream()
  .map(Method::getName)
  .collect(Collectors.toList());

// This will define a "build" method that will invoke the constructor of some object and
// pass in the fields (in order) of the builder to that constructor.
builder = builder
  .define(buildMethod)
  .intercept(MethodCall.construct(constructor)
    .withField(fieldNames.toArray(new String[fieldNames.size()])));
</code>```

Title: Creating Step Builder with ByteBuddy

Body:
I'm trying to get ByteBuddy to implement a step builder, given an interface for that builder. I'm stuck on 2 places.

How to create a setter that returns the current instance for method chaining?

I started with:

.method(ElementMatchers.isSetter())
.intercept(FieldAccessor.ofBeanProperty());

only I'd like to return the current builder instance so we can chain calls like:

final Object obj = ...builder().id(100).name("test").build();

so instead I created an interceptor like this, which seems like a hack and I'd like to avoid reflection where possible:

@RuntimeType
public Object intercept(@RuntimeType Object arg, @This Object source, @Origin Method method)
{
  try
  {
    // Field name is same as method name.
    final Field field = source.getClass().getDeclaredField(method.getName());
    field.setAccessible(true);
    field.set(source, arg);
  }
  catch (Throwable ex)
  {
    throw new Error(ex);
  }

  // Return current builder instance.
  return source;
}

Is there an easy way to access defined fields on a class I'm defining without reflection?

Currently I add fields to the builder class in a loop and my build method on the builder is intercepted like this:

private static final class InterBuilder
{
  private final Collection<String> fields;
  private final Constructor<?> constructor;

  InterBuilder(final Constructor<?> constructor, final Collection<String> fields)
  {
    this.constructor = constructor;
    this.fields = fields;
  }

  @RuntimeType
  public Object intercept(@This Object source, @Origin Method method)
  {
    try
    {
      final Object[] args = Arrays.stream(source.getClass().getDeclaredFields())
        .filter(f -> this.fields.contains(f.getName()))
        .map(f ->  { try {
          f.setAccessible(true);
          return f.get(source); }
          catch (Throwable ex) { throw new Error(ex); } })
        .toArray();

      // Invoke a constructor passing in the private field values from the builder...
      return this.constructor.newInstance(args);
    }
    catch (Throwable ex)
    {
      throw new Error(ex);
    }
  }
}

I saw the @FieldValue annoation. I don't suppose there is something that will give me all fields without knowing their names up front?

The code is a proof of concept at this point. Are there better ways to do what I'm doing here?

Thank you!

Body:
Rafael gave me the information I needed to come up with a solution, so the answer credit goes to him, but I wanted to include my solution for anyone else to discover in the future.

DynamicType.Builder<?> builder = new ByteBuddy()
  .subclass(Object.class)
  .implement(interfaces)
  .name(builderClassName);

// Find all of the setters on the builder...
// Here I'm assuming all field names match setter names like:
//   MyClass x = theBuilder.name("hi").id(1000).isValid(true).build();
final List<Method> setters = ...

for (final Method setter : setters)
{
  // This will define a field and a setter that will set the value and return the current instance.
  builder = builder
    .defineField(setter.getName(), setter.getParameterTypes()[0], Visibility.PRIVATE)
    .define(setter)
    .intercept(FieldAccessor.ofField(setter.getName()).setsArgumentAt(0).andThen(FixedValue.self()));
}

// Find the "build" method on the builder.
final Method buildMethod = ...

// Get a constructor that you want the builder to call and return the new instance.
final Constructor<?> constructor = ...

// Get the field names from the setters.
final List<String> fieldNames = setters.stream()
  .map(Method::getName)
  .collect(Collectors.toList());

// This will define a "build" method that will invoke the constructor of some object and
// pass in the fields (in order) of the builder to that constructor.
builder = builder
  .define(buildMethod)
  .intercept(MethodCall.construct(constructor)
    .withField(fieldNames.toArray(new String[fieldNames.size()])));


问:
CSS div sizing relative to viewport borders?
I have a div containing some text and a YouTube video. I used CSS to give it a grey background. I also set the position to 4.4 em from the top, 1% from the left, and made it 98% wide. I want the bottom of the div to be 4.4 em from the bottom, no matter the size or zoom of the browser. How can I do this? Can I use CSS, or is Javascript required? If you give an answer containing Javascript code, please don’t use jQuery.

div {
  position: absolute;
  left: 1%;
  width: 98%;
  top: 4.4em;
  background: grey;
}

body {
  width: 100%;
  color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>EDIT: Here is my HTML:

<div>
  <h1>A Heading</h1>
  YOUTUBE VIDEO HERE
</div></code>```

答:
You could either use a border that is transparent to simluate the 4.4em gap at the bottom, or you could use the "calc()" css function https://www.w3schools.com/cssref/func_calc.asp

Example:

```<code>height: calc(100vh - 4.4em);
</code>```

Body:
I have a div containing some text and a YouTube video. I used CSS to give it a grey background. I also set the position to 4.4 em from the top, 1% from the left, and made it 98% wide. I want the bottom of the div to be 4.4 em from the bottom, no matter the size or zoom of the browser. How can I do this? Can I use CSS, or is Javascript required? If you give an answer containing Javascript code, please don’t use jQuery.

div {
  position: absolute;
  left: 1%;
  width: 98%;
  top: 4.4em;
  background: grey;
}

body {
  width: 100%;
  color: white;
}

EDIT: Here is my HTML:

A Heading

  YOUTUBE VIDEO HERE

Body:
You could either use a border that is transparent to simluate the 4.4em gap at the bottom, or you could use the "calc()" css function https://www.w3schools.com/cssref/func_calc.asp

Example:

height: calc(100vh - 4.4em);


问:
How to code for optional command line parameters in C
My program has to accept optional command line parameters where there will be either 1 or 3 parameters (executable, number of rows, number of columns). If argc is anything other than 3, we have to create a board that is 10x10 (I've already made a function to create the board).

I'm not sure how to account for this. One restriction on main.c is that we're only allowed to declare/assign variables and call functions, so I'm stuck on how I'm supposed to make this work. My initial idea was to write a function correctNumOfArgs to check if argc is 3, and then return true or false. I would then use that result in a different function to determine how to create the board, but that would still require me to pass argv[1] and argv[2] as parameters in the function and they might not even exist. How do I get around this? Note: I looked at other questions regarding optional command line parameters and they suggested solutions more advanced than what we have learned. Is there a more basic solution to this?

答:
You can pass both argc and argv to a function and have it return rows and cols.

```<code>int main(int argc, char **argv) {
    int rows = 10, cols = 10;
    check_args(argc, argv, &rows, &cols);
    return 0;
}

void check_args(int argc, char **argv, int *rows, int *cols) {
    if (argc == 3) {
        *rows = atoi(argv[1]);
        *cols = atoi(argv[2]);
    }
}
</code>```

Body:
You can pass both argc and argv to a function and have it return rows and cols.

int main(int argc, char **argv) {
    int rows = 10, cols = 10;
    check_args(argc, argv, &rows, &cols);
    return 0;
}

void check_args(int argc, char **argv, int *rows, int *cols) {
    if (argc == 3) {
        *rows = atoi(argv[1]);
        *cols = atoi(argv[2]);
    }
}


问:
Sort null values last with DataTables in R
I am currently using a datatable in an rmarkdown document to create a flexdashboard. I have a numeric column with NA's in it.  When I click to sort the column in descending order it puts the largest value first and the NA/null values last.  When I sort in ascending order it puts the NA/null values first and then the numeric values.  Is there a way to sort the null value last when sorting in ascending order?  It looks like DataTables might have a plugin for this very issue but I see it is not supported by the R DataTables version. I'm looking to be able to sort the numeric columns the same way RStudio does with a table when you view it.

Here is a reproducible example of the functionality I am looking for:

```<code>library(DT)
library(tidyverse)

Table.with.null <- tibble(Category=c("A","B","C","D"),
                          Numeric=seq(1,4),
                          Numeric.null=c(1,2,3,NA))

datatable(Table.with.null,rownames=FALSE)
</code>```

When I sort the Numeric.null column in ascending order the table should look like this:

```<code>Category  Numeric  Numeric.null
A         1        1
B         2        2
C         3        3
D         4        NA
</code>```

Which it does.  When I sort Numeric.null column in descending order the table should look like this:

```<code>Category  Numeric  Numeric.null
C         3        3
B         2        2
A         1        1
D         4        NA
</code>```

答:
The trick is to provide sorting function using callback argument. The js function from the example doesn't work for me (I guess value argument should be supplied - it needs a bit of work), but here is example with my own sorting function.

Important note is that sorting column type should be changed to character just before calling datatable function. Also keep in mind that while rownames DT argument is set to FALSE columns have numbers 0,1,2,...

```<code>library(DT)
library(dplyr)

temp <-mtcars
temp[1, "wt"] <- NA
temp[2, "wt"] <- NA

#OUTPUT - dtdata
DT::datatable({
  temp %>% mutate(wt = as.character(wt))
},
callback = JS("
  $.fn.dataTableExt.oSort['NumericOrBlank-asc'] = function(x,y) {
    var retVal;
        if( x === '' || $.isEmptyObject(x)) x = 1000;
    if( y === '' || $.isEmptyObject(y)) y = 1000;
    x = (x = parseFloat($.trim(x).replace(/,/g,''))) ? x : 0;
    y = (y = parseFloat($.trim(y).replace(/,/g,''))) ? y : 0;
    if (x==y) retVal= 0;
    else retVal = (x>y) ? 1 : -1;
    return retVal;
  };
  $.fn.dataTableExt.oSort['NumericOrBlank-desc'] = function(y,x) {
  var retVal;
  x = (x = parseFloat($.trim(x).replace(/,/g,''))) ? x : 0;
  y = (y = parseFloat($.trim(y).replace(/,/g,''))) ? y : 0;
  if (x==y) retVal= 0;
  else retVal = (x>y) ? 1 : -1;
  return retVal;
  };
  "),
options = list(
  autoWidth = TRUE,
  aoColumnDefs = list(list(width = '100px', bSortable = TRUE, sType =
'NumericOrBlank', targets = c(5)))
), rownames = FALSE)
</code>```

Body:
I am currently using a datatable in an rmarkdown document to create a flexdashboard. I have a numeric column with NA's in it.  When I click to sort the column in descending order it puts the largest value first and the NA/null values last.  When I sort in ascending order it puts the NA/null values first and then the numeric values.  Is there a way to sort the null value last when sorting in ascending order?  It looks like DataTables might have a plugin for this very issue but I see it is not supported by the R DataTables version. I'm looking to be able to sort the numeric columns the same way RStudio does with a table when you view it.

Here is a reproducible example of the functionality I am looking for:

library(DT)
library(tidyverse)

Table.with.null <- tibble(Category=c("A","B","C","D"),
                          Numeric=seq(1,4),
                          Numeric.null=c(1,2,3,NA))

datatable(Table.with.null,rownames=FALSE)

When I sort the Numeric.null column in ascending order the table should look like this:

Category  Numeric  Numeric.null
A         1        1
B         2        2
C         3        3
D         4        NA

Which it does.  When I sort Numeric.null column in descending order the table should look like this:

Category  Numeric  Numeric.null
C         3        3
B         2        2
A         1        1
D         4        NA

Body:
The trick is to provide sorting function using callback argument. The js function from the example doesn't work for me (I guess value argument should be supplied - it needs a bit of work), but here is example with my own sorting function.

Important note is that sorting column type should be changed to character just before calling datatable function. Also keep in mind that while rownames DT argument is set to FALSE columns have numbers 0,1,2,...

library(DT)
library(dplyr)

temp <-mtcars
temp[1, "wt"] <- NA
temp[2, "wt"] <- NA

#OUTPUT - dtdata
DT::datatable({
  temp %>% mutate(wt = as.character(wt))
},
callback = JS("
  $.fn.dataTableExt.oSort['NumericOrBlank-asc'] = function(x,y) {
    var retVal;
        if( x === '' || $.isEmptyObject(x)) x = 1000;
    if( y === '' || $.isEmptyObject(y)) y = 1000;
    x = (x = parseFloat($.trim(x).replace(/,/g,''))) ? x : 0;
    y = (y = parseFloat($.trim(y).replace(/,/g,''))) ? y : 0;
    if (x==y) retVal= 0;
    else retVal = (x>y) ? 1 : -1;
    return retVal;
  };
  $.fn.dataTableExt.oSort['NumericOrBlank-desc'] = function(y,x) {
  var retVal;
  x = (x = parseFloat($.trim(x).replace(/,/g,''))) ? x : 0;
  y = (y = parseFloat($.trim(y).replace(/,/g,''))) ? y : 0;
  if (x==y) retVal= 0;
  else retVal = (x>y) ? 1 : -1;
  return retVal;
  };
  "),
options = list(
  autoWidth = TRUE,
  aoColumnDefs = list(list(width = '100px', bSortable = TRUE, sType =
'NumericOrBlank', targets = c(5)))
), rownames = FALSE)


问:
What's the correct data design for recording the results of generic two player game?
Assume the game has two players.  Each player has a score and highest score wins.  A user table is self evident.  The first design I thought of is as follows:

match_id, user1_id, user2_id, score1, score2

The problem is suppose I want a quick way of ranking users by win %.  In the above table a single userid would be scattered between user1_id and user2_id.  It would seem to require multiple queries and seems messy.  The other way is to keep a separate stats table

user_id, winloss

This makes queries easy but doesn't seem theoretically correct because the stats table stores derive data.  Is there a way to solve this which involves a nice, clean theoretically correct data structure which is easy to query?

答:
I will have a user table (obviously), a Join table called Match with just match id and a transactional table that will have user_id, match_id, score. So for a particular match, there would be  two records corresponding to two user.

Also, I will also store a fk reference of the winning user_id in the match table. Just a quick way to find % of win for each user.