问:
AWS Glue takes a long time to finish
I just run a very simple job as follows

```<code>glueContext = GlueContext(SparkContext.getOrCreate())
l_table = glueContext.create_dynamic_frame.from_catalog(
             database="gluecatalog",
             table_name="fctable")
l_table = l_table.drop_fields(['seq','partition_0','partition_1','partition_2','partition_3']).rename_field('tbl_code','table_code')
print "Count: ", l_table.count()
l_table.printSchema()
l_table.select_fields(['trans_time']).toDF().distinct().show()
dfc = l_table.relationalize("table_root", "s3://my-bucket/temp/")
print "Before keys() call "
dfc.keys()
print "After keys() call "
l_table.select_fields('table').printSchema()
dfc.select('table_root_table').toDF().where("id = 1 or id = 2").orderBy(['id','index']).show()
dfc.select('table_root').toDF().where("table = 1 or table = 2").show()
</code>```

The data structure is simple too

```<code>root
|-- table: array
| |-- element: struct
| | |-- trans_time: string
| | |-- seq: null
| | |-- operation: string
| | |-- order_date: string
| | |-- order_code: string
| | |-- tbl_code: string
| | |-- ship_plant_code: string
|-- partition_0
|-- partition_1
|-- partition_2
|-- partition_3
</code>```

When I run job test, it took anywhere from 12 to 16 minutes to finish. But the cloud watch log showed that the job took 2 seconds to display all my data.

So my questions are:
 Where does AWS Glue job spend its time beyond the logging could show and is what it doing outside the logging period?

答: when taking the action of editing a job, you can add more DPUs under the "Script libraries and job parameters (optional)" section. It helps some, but do not expect any major improvement, my experience.</p>

Title: AWS Glue takes a long time to finish

Body:
I just run a very simple job as follows

glueContext = GlueContext(SparkContext.getOrCreate())
l_table = glueContext.create_dynamic_frame.from_catalog(
             database="gluecatalog",
             table_name="fctable")
l_table = l_table.drop_fields(['seq','partition_0','partition_1','partition_2','partition_3']).rename_field('tbl_code','table_code')
print "Count: ", l_table.count()
l_table.printSchema()
l_table.select_fields(['trans_time']).toDF().distinct().show()
dfc = l_table.relationalize("table_root", "s3://my-bucket/temp/")
print "Before keys() call "
dfc.keys()
print "After keys() call "
l_table.select_fields('table').printSchema()
dfc.select('table_root_table').toDF().where("id = 1 or id = 2").orderBy(['id','index']).show()
dfc.select('table_root').toDF().where("table = 1 or table = 2").show()

The data structure is simple too

root
|-- table: array
| |-- element: struct
| | |-- trans_time: string
| | |-- seq: null
| | |-- operation: string
| | |-- order_date: string
| | |-- order_code: string
| | |-- tbl_code: string
| | |-- ship_plant_code: string
|-- partition_0
|-- partition_1
|-- partition_2
|-- partition_3

When I run job test, it took anywhere from 12 to 16 minutes to finish. But the cloud watch log showed that the job took 2 seconds to display all my data.

So my questions are:
 Where does AWS Glue job spend its time beyond the logging could show and is what it doing outside the logging period?


来源: stackexchange

问:
Invalid Resource File Directory in Xamarin Studio
The entire code has compiled perfectly but I am getting an error of invalid resource directory name.

The exact error is :

C:\Users\DELL\Documents\Projects\PhoneWord\PhoneWord\aapt.exe: Error: Invalid resource directory name: "res aboutresources.txt". (PhoneWord)

Please help me resolve this issue.

答:
Check the Build Action of each of your images is set to AndroidAsset and not AndroidResource.

Steps:
1. Right click on the AboutResources.txt.
2. Goto Properties
3. Check the Build Action

ContentLicense: CC BY-SA 3.0


问:
Is it semantically correct to use a button in a table caption in HTML5?
I have a matrix of product data.

My goal is to:

display the matrix using HTML5 in a tabular format

display a left-aligned "title" above the data that describes it

display a right-aligned "add" button, vertically aligned with the title, which facilitates the addition of rows to the table

display a header row to describe each column of data

do all of the above in a semantically "correct" way, if possible

So, the end result would look similar to this:

--------------------------------------------------------
|Product Catalog                         [+Add Product]|
--------------------------------------------------------
| Title | Cost | Weight | and | so | on | ...          |
--------------------------------------------------------
| Thing1| $5.99| 3 oz   | ... | ...| ...| ...          |
| Thing2| $2.99| 2 oz   | ... | ...| ...| ...          |
--------------------------------------------------------
```

<p>My current code:</p>

```

Product Catalog <button style="float: right; display: block;">+Add Product</button>

            Title
            Cost
            Weight
            and
            so
            on
            ...

            Thing1
            $5.99
            3 oz
            ...
            ...
            ...
            ...

            Thing2
            $2.99
            2 oz
            ...
            ...
            ...
            ...

```

According to the HTML5 spec, the caption element can contain any flow content, which includes buttons.

From the spec:

Content Model: Flow content, but with no descendant table elements

However, the same spec defines the caption element as:

The caption element represents the title of the table that is its parent, if it has a parent and that is a table element.

Based on that description, it seems that a button does not belong inside of a caption, because it lends nothing to the title of the table, even though it is technically allowed.

My questions are:
Is it semantically "correct" to include a button inside of a table caption?  If it is not "correct", is it acceptable? Is there a more-semantically-correct way of achieving the desired result?

I found plenty of questions/answers dealing with table semantics, but most did not deal with buttons on the table.

This question/answer asks about buttons in a table, but it is specific to buttons inside of a "cell", not the caption.

HTML5 Specs:

caption element: https://www.w3.org/TR/html5/tabular-data.html#the-caption-element

flow-content: https://www.w3.org/TR/html5/dom.html#flow-content-1

EDIT:
This question/answer seems to be of the same nature as my question, but he is asking about putting his button(s) inside of a , not the table caption.

One solution I've considered is: don't use a caption at all.  Just put a
 or similar header tag before the table tag.  The only problem with this is that the title will no longer be relative to the table.... or will it?  Actually, that might be the answer.  If I wrap the
 and the
 in a
 or perhaps a
 then that might work?

I'm looking for the "most-correct" way.

答: I know this is a bit dated but putting a button that acts on the table is semantically legitimate in the thead (or tfoot) of the table element. I agree that caption is not the correct place but saying it should not be in the table anywhere is also not correct.

Body:
I have a matrix of product data.

My goal is to:

display the matrix using HTML5 in a tabular format

display a left-aligned "title" above the data that describes it

display a right-aligned "add" button, vertically aligned with the title, which facilitates the addition of rows to the table

display a header row to describe each column of data

do all of the above in a semantically "correct" way, if possible

So, the end result would look similar to this:

--------------------------------------------------------
|Product Catalog                         [+Add Product]|
--------------------------------------------------------
| Title | Cost | Weight | and | so | on | ...          |
--------------------------------------------------------
| Thing1| $5.99| 3 oz   | ... | ...| ...| ...          |
| Thing2| $2.99| 2 oz   | ... | ...| ...| ...          |
--------------------------------------------------------

My current code:

Product Catalog <button style="float: right; display: block;">+Add Product</button>

            Title
            Cost
            Weight
            and
            so
            on
            ...

            Thing1
            $5.99
            3 oz
            ...
            ...
            ...
            ...

            Thing2
            $2.99
            2 oz
            ...
            ...
            ...
            ...

According to the HTML5 spec, the caption element can contain any flow content, which includes buttons.

From the spec:

Content Model: Flow content, but with no descendant table elements

However, the same spec defines the caption element as:

The caption element represents the title of the table that is its parent, if it has a parent and that is a table element.

Based on that description, it seems that a button does not belong inside of a caption, because it lends nothing to the title of the table, even though it is technically allowed.

My questions are:
Is it semantically "correct" to include a button inside of a table caption?  If it is not "correct", is it acceptable? Is there a more-semantically-correct way of achieving the desired result?

I found plenty of questions/answers dealing with table semantics, but most did not deal with buttons on the table.

This question/answer asks about buttons in a table, but it is specific to buttons inside of a "cell", not the caption.

HTML5 Specs:

caption element: https://www.w3.org/TR/html5/tabular-data.html#the-caption-element

flow-content: https://www.w3.org/TR/html5/dom.html#flow-content-1

EDIT:
This question/answer seems to be of the same nature as my question, but he is asking about putting his button(s) inside of a , not the table caption.

One solution I've considered is: don't use a caption at all.  Just put a
 or similar header tag before the table tag.  The only problem with this is that the title will no longer be relative to the table.... or will it?  Actually, that might be the answer.  If I wrap the
 and the
 in a
 or perhaps a
 then that might work?

I'm looking for the "most-correct" way.


问:
Can't display values for a user profile in CodeIgniter?
I am making a simple twitter clone for practice with CodeIgniter and am having difficulty echoing the first_name and last_name and date_joined value from my users table in my user.php view. I just want to show the values for the user that is currently logged in.

I would want the values to echo below the session username in my view. My controller, view, and models are below. Right now I get the following error:

Message: Cannot use object of type stdClass as array

This is when I just try to echo $user['first_name'], $user['last_name], etc. I had it working before simply echoing out like this but now I can't.
If I do a var_dump of $user I just get the following:

/app/www/application/views/user.php:5: class stdClass#22 (1) { public $user_id => string(1) "1" }

Controller: User.php

```<code>class User extends CI_Controller
{
 function index()
 {
  $this->load->model('login_model');
  $data['user'] = $this->login_model->get_user();
  $data['tweets'] = $this->tweet_model->usertweets();
  $this->load->view('templates/header');
  $this->load->view('user', $data);
  $this->load->view('templates/footer');
 }
}
</code>```

Model: Login_model.php

```<code>class Login_model extends CI_Model
{
 function can_login($username, $password)
{
 $this->db->where('username', $username);
 $this->db->where('password', $password);
 $query = $this->db->get('users');

 //SELECT * FROM users WHERE username = '$username' AND password = '$password'

 if($query->num_rows() > 0)
 {
  return true;
 }
 else {
  return false;
 }
}

 function get_user()
 {
  $query = $this->db->get('users');

  $username = $_SESSION['username'];
  $this->db->select('user_id', 'first_name', 'last_name', 'date_joined');
  $this->db->from('users');
  $this->db->where('username', $username);
  $query = $this->db->get();
  return $query->row();
 }
}
</code>```

Model: Tweet_model.php

```<code>class Tweet_model extends CI_Model
{
public function __construct()
{
    $this->load->database();
}

public function get_tweets($tweet_id = false)
{
    if ($tweet_id === false) {
        $this->db->join('users', 'tweets.user_id = users.user_id');
        $query = $this->db->get('tweets');
        return $query->result_array();
    }

    $query = $this->db->get_where('tweets', array('tweet_id' => $tweet_id));
    return $query->row_array();
}

public function set_tweet()
{
    $tweet = url_title($this->input->post('tweet'), 'dash', true);

    $query = $this->db->get('users');

    $username = $_SESSION['username'];
    $this->db->select('user_id');
    $this->db->from('users');
    $this->db->where('username', $username);

    if ($this->db->affected_rows())
    {
        $user = $query->row();
        var_dump($user_id);
    }

    $data = array(
      'tweet' => $this->input->post('tweet'),
      'user_id' => $user->user_id
    );

    return $this->db->insert('tweets', $data);
}

function Usertweets() {
  $this->db->flush_cache();

  $username = $_SESSION['username'];
  $this->db->select('user_id');
  $this->db->from('users');
  $this->db->where('username', $username);

  $query = $this->db->get();
  $user = $query->row();

  $this->db->flush_cache();

  $this->db->select('*');
  $this->db->from('tweets');
  $this->db->where('user_id', $user->user_id);

  return $this->db->get()->result();

}
}
</code>```

View: user.php

```<code><div class="container">
 <div class="row">
  <div class="col-md-4">
   <h4><?php echo $_SESSION['username']; ?></h4>
  </div>
  <div class="col-md-8">
   <?php foreach ($tweets as $tweet): ?>
    <div class="user-tweet">
     <h4><?php echo $_SESSION['username']; ?></h4>
     <h6><?php echo $tweet->tweet_date; ?></h6>
     <p><?php echo $tweet->tweet; ?></p>
    </div>
   <?php endforeach; ?>
  </div>
 </div>
</div>
</code>```

答:
You are getting this error because $query->row() returns an object which means you get the values with $user->user_id, not $user['user_id']. If you want to use $user['user_id'], change </p>

```<code>$user = $query->row();
</code>```

<p>to </p>

```<code>$user = $query->row_array();
</code>```

Body:
I am making a simple twitter clone for practice with CodeIgniter and am having difficulty echoing the first_name and last_name and date_joined value from my users table in my user.php view. I just want to show the values for the user that is currently logged in.

I would want the values to echo below the session username in my view. My controller, view, and models are below. Right now I get the following error:

Message: Cannot use object of type stdClass as array

This is when I just try to echo $user['first_name'], $user['last_name], etc. I had it working before simply echoing out like this but now I can't.
If I do a var_dump of $user I just get the following:

/app/www/application/views/user.php:5: class stdClass#22 (1) { public $user_id => string(1) "1" }

Controller: User.php

class User extends CI_Controller
{
 function index()
 {
  $this->load->model('login_model');
  $data['user'] = $this->login_model->get_user();
  $data['tweets'] = $this->tweet_model->usertweets();
  $this->load->view('templates/header');
  $this->load->view('user', $data);
  $this->load->view('templates/footer');
 }
}

Model: Login_model.php

class Login_model extends CI_Model
{
 function can_login($username, $password)
{
 $this->db->where('username', $username);
 $this->db->where('password', $password);
 $query = $this->db->get('users');

 //SELECT * FROM users WHERE username = '$username' AND password = '$password'

 if($query->num_rows() > 0)
 {
  return true;
 }
 else {
  return false;
 }
}

 function get_user()
 {
  $query = $this->db->get('users');

  $username = $_SESSION['username'];
  $this->db->select('user_id', 'first_name', 'last_name', 'date_joined');
  $this->db->from('users');
  $this->db->where('username', $username);
  $query = $this->db->get();
  return $query->row();
 }
}

Model: Tweet_model.php

class Tweet_model extends CI_Model
{
public function __construct()
{
    $this->load->database();
}

public function get_tweets($tweet_id = false)
{
    if ($tweet_id === false) {
        $this->db->join('users', 'tweets.user_id = users.user_id');
        $query = $this->db->get('tweets');
        return $query->result_array();
    }

    $query = $this->db->get_where('tweets', array('tweet_id' => $tweet_id));
    return $query->row_array();
}

public function set_tweet()
{
    $tweet = url_title($this->input->post('tweet'), 'dash', true);

    $query = $this->db->get('users');

    $username = $_SESSION['username'];
    $this->db->select('user_id');
    $this->db->from('users');
    $this->db->where('username', $username);

    if ($this->db->affected_rows())
    {
        $user = $query->row();
        var_dump($user_id);
    }

    $data = array(
      'tweet' => $this->input->post('tweet'),
      'user_id' => $user->user_id
    );

    return $this->db->insert('tweets', $data);
}

function Usertweets() {
  $this->db->flush_cache();

  $username = $_SESSION['username'];
  $this->db->select('user_id');
  $this->db->from('users');
  $this->db->where('username', $username);

  $query = $this->db->get();
  $user = $query->row();

  $this->db->flush_cache();

  $this->db->select('*');
  $this->db->from('tweets');
  $this->db->where('user_id', $user->user_id);

  return $this->db->get()->result();

}
}

View: user.php

<?php echo $_SESSION['username']; ?>

   <?php foreach ($tweets as $tweet): ?>

<?php echo $_SESSION['username']; ?>

<?php echo $tweet->tweet_date; ?>

<?php echo $tweet->tweet; ?>

   <?php endforeach; ?>

Body:
You are getting this error because $query->row() returns an object which means you get the values with $user->user_id, not $user['user_id']. If you want to use $user['user_id'], change

$user = $query->row();

to

$user = $query->row_array();


问:
Get index of array element as Int
I have an array of UIViewController in my protocol

```<code>var viewControllers: [MyViewController] { get }
</code>```

I want to get the index of item with specific ViewController

```<code>let idfx = viewModel.viewControllers.index(of: viewController as! MyViewController)
</code>```

But the type of idfx is Array.index.

How can I get the index of an array element as an Int?

答: Actually the type Array.Index is a typealias to the type Int, so you can do the same operation as if you had an integer with the result of the method index(of:).

Title: Get index of array element as Int

Body:
I have an array of UIViewController in my protocol

var viewControllers: [MyViewController] { get }

I want to get the index of item with specific ViewController

let idfx = viewModel.viewControllers.index(of: viewController as! MyViewController)

But the type of idfx is Array.index.

How can I get the index of an array element as an Int?


问:
How to make one color transparent on a UIImage?
On my iPhone app I have a UIImage instance. I want to get a derived a UIImage that is the result of the first UIImage where one of its colors (e.g. magenta) is made transparent. How can I do this?</p>

答:
Swift 4: (for white masking)   </p>

```<code>extension UIImage {
func imageByMakingWhiteBackgroundTransparent() -> UIImage? {

    let image = UIImage(data: UIImageJPEGRepresentation(self, 1.0)!)!
    let rawImageRef: CGImage = image.cgImage!

    let colorMasking: [CGFloat] = [222, 255, 222, 255, 222, 255]
    UIGraphicsBeginImageContext(image.size);

    let maskedImageRef = rawImageRef.copy(maskingColorComponents: colorMasking)
    UIGraphicsGetCurrentContext()?.translateBy(x: 0.0,y: image.size.height)
    UIGraphicsGetCurrentContext()?.scaleBy(x: 1.0, y: -1.0)
    UIGraphicsGetCurrentContext()?.draw(maskedImageRef!, in: CGRect.init(x: 0, y: 0, width: image.size.width, height: image.size.height))
    let result = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return result

    }
}
</code>```

OwnerDisplayName: devguy

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Brent Royal-Gordon

Body:
Swift 4: (for white masking)

extension UIImage {
func imageByMakingWhiteBackgroundTransparent() -> UIImage? {

    let image = UIImage(data: UIImageJPEGRepresentation(self, 1.0)!)!
    let rawImageRef: CGImage = image.cgImage!

    let colorMasking: [CGFloat] = [222, 255, 222, 255, 222, 255]
    UIGraphicsBeginImageContext(image.size);

    let maskedImageRef = rawImageRef.copy(maskingColorComponents: colorMasking)
    UIGraphicsGetCurrentContext()?.translateBy(x: 0.0,y: image.size.height)
    UIGraphicsGetCurrentContext()?.scaleBy(x: 1.0, y: -1.0)
    UIGraphicsGetCurrentContext()?.draw(maskedImageRef!, in: CGRect.init(x: 0, y: 0, width: image.size.width, height: image.size.height))
    let result = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return result

    }
}


问:
Admob and ListActivity
I have a ListActivity with a custom layout. Now I'd like try to add AdMod my activity but I get the same problems I had when I added a button to the layout. If I have the layouts at 100px I see both list and ad but it really isn't looking good.

```<code>        <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="fill_parent"
    xmlns:myapp="http://schemas.android.com/apk/res/se.javalia.myDrinks"
    android:orientation="vertical">
    <RelativeLayout android:layout_width="fill_parent"
        android:layout_height="200px"
        android:gravity="center">
    <ListView android:id="@+id/android:list" android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
    <TextView android:id="@+id/android:empty"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:text="@string/main_no_items" />
    </RelativeLayout>
    <RelativeLayout android:layout_width="fill_parent"
        android:layout_height="48px"
        android:gravity="bottom">
        <com.admob.android.ads.AdView android:id="@+id/ad"
            android:layout_width="fill_parent" android:layout_height="wrap_content"
            myapp:backgroundColor="#000000" myapp:primaryTextColor="#FFFFFF"
            myapp:secondaryTextColor="#CCCCCC" android:layout_alignParentBottom="true"
            myapp:keywords="drink alcohol wiskey rum soda" myapp:refreshInterval="300" />
    </RelativeLayout>

</LinearLayout>
</code>```

Do you have any idea about why I don't see the ads when I have increased use 200px, and how to fill the screen without the ad disapering.

Thanks in advance
Roland

答:
at a first glance your code one prob which i think this error happens:in this code
<RelativeLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        <com.admob.android.ads.AdView android:id="@+id/ad"
            android:layout_width="fill_parent" android:layout_height="wrap_content"
            myapp:backgroundColor="#000000" myapp:primaryTextColor="#FFFFFF"
            myapp:secondaryTextColor="#CCCCCC" android:layout_alignParentBottom="true"
            myapp:keywords="drink alcohol wiskey rum soda" myapp:refreshInterval="300" />
    </RelativeLayout>

use fixed height for your admob custom class instead of fill parent try smaller value and you get listview visible

Title: Admob and ListActivity

Body:
I have a ListActivity with a custom layout. Now I'd like try to add AdMod my activity but I get the same problems I had when I added a button to the layout. If I have the layouts at 100px I see both list and ad but it really isn't looking good.

        <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="fill_parent"
    xmlns:myapp="http://schemas.android.com/apk/res/se.javalia.myDrinks"
    android:orientation="vertical">
    <RelativeLayout android:layout_width="fill_parent"
        android:layout_height="200px"
        android:gravity="center">
    <ListView android:id="@+id/android:list" android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
    <TextView android:id="@+id/android:empty"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:text="@string/main_no_items" />
    </RelativeLayout>
    <RelativeLayout android:layout_width="fill_parent"
        android:layout_height="48px"
        android:gravity="bottom">
        <com.admob.android.ads.AdView android:id="@+id/ad"
            android:layout_width="fill_parent" android:layout_height="wrap_content"
            myapp:backgroundColor="#000000" myapp:primaryTextColor="#FFFFFF"
            myapp:secondaryTextColor="#CCCCCC" android:layout_alignParentBottom="true"
            myapp:keywords="drink alcohol wiskey rum soda" myapp:refreshInterval="300" />
    </RelativeLayout>

</LinearLayout>

Do you have any idea about why I don't see the ads when I have increased use 200px, and how to fill the screen without the ad disapering.

Thanks in advance
Roland


问:
Rscript not found in mac
If I execute an R program through macOS Terminal it works fine, but if I execute that program through PHP exec() I get an error which says "Rscript not found".

submit.php:

```<code><?php
// print "hello";
$a = $_POST['a'];
$b = $_POST['b'];
// echo shell_exec("calc");
$output =  exec("Rscript /xampp/htdocs/demo/1.R ".$a." ".$b);
print $output
?>
</code>```

1.R:

```<code>setwd("C:/xampp/htdocs/demo")
print("hello")
args=commandArgs(trailingOnly = TRUE)
a = args[1]
b = args[2]
c = as.numeric(a)+as.numeric(b)
cat(c)
</code>```

答:
You need to tell the command interpreter where Rscript is located. In a normal login, you'd have a long PATH variable to search through, but when running from PHP you have a much more limited path. To figure out where the executable is located, type which Rscript from Terminal. Use the resulting path in your PHP script.

Also note that dumping raw user input into shell commands is a very bad idea. You should always use escapeshellarg() to make sure the input is sanitized. I would also suggest capturing the full output in the event that R outputs more than one line.

```<code><?php
$a = escapeshellarg($_POST["a"]);
$b = escapeshellarg($_POST["b"]);
$r = "/xampp/htdocs/demo/1.R";
$lastline = exec("/usr/local/bin/Rscript $r $a $b", $output, $return);
// you could check the value of $return for non-zero values as well
// full output is returned as an array
echo implode("\n", $output);
</code>```

Finally, you'll want to check your setwd() command in the R script. Might have some trouble with C: on a Mac! ;)

Title: Rscript not found in mac

Body:
If I execute an R program through macOS Terminal it works fine, but if I execute that program through PHP exec() I get an error which says "Rscript not found".

submit.php:

<?php
// print "hello";
$a = $_POST['a'];
$b = $_POST['b'];
// echo shell_exec("calc");
$output =  exec("Rscript /xampp/htdocs/demo/1.R ".$a." ".$b);
print $output
?>

1.R:

setwd("C:/xampp/htdocs/demo")
print("hello")
args=commandArgs(trailingOnly = TRUE)
a = args[1]
b = args[2]
c = as.numeric(a)+as.numeric(b)
cat(c)

Body:
You need to tell the command interpreter where Rscript is located. In a normal login, you'd have a long PATH variable to search through, but when running from PHP you have a much more limited path. To figure out where the executable is located, type which Rscript from Terminal. Use the resulting path in your PHP script.

Also note that dumping raw user input into shell commands is a very bad idea. You should always use escapeshellarg() to make sure the input is sanitized. I would also suggest capturing the full output in the event that R outputs more than one line.

<?php
$a = escapeshellarg($_POST["a"]);
$b = escapeshellarg($_POST["b"]);
$r = "/xampp/htdocs/demo/1.R";
$lastline = exec("/usr/local/bin/Rscript $r $a $b", $output, $return);
// you could check the value of $return for non-zero values as well
// full output is returned as an array
echo implode("\n", $output);

Finally, you'll want to check your setwd() command in the R script. Might have some trouble with C: on a Mac! ;)


问:
Runtime error (3020): How to add information to a new record?
I get a runtime error (3020) when trying to add information to a new record.

It errors out on the line: rs2!PlanTitle.Value = RWPSheetvalues(96)

```<code>Private Sub ImportRWPData_Click()
    Dim db As Database
    Dim rs As Recordset
    Dim rs2 As DAO.Recordset
    Dim File As Field
    Dim Location As String
    Set db = CurrentDb()
    Set rs = db.OpenRecordset("rwpT")
    Set rs2 = db.OpenRecordset("AIP&BOP")
    Set File = rs.Fields("File")
    Dim xls     As Excel.Application
    Dim wkb     As Excel.Workbook
    Dim wks     As Excel.Worksheet
    Set xls = New Excel.Application
    'Declare variables for column values in RWP spreadsheets
    Dim orgSheetCol(7) As String
        orgSheetCol(0) = "$A$" 'Auto Isolation Point
        orgSheetCol(1) = "$D$" 'Customer Minutes Lost
        orgSheetCol(2) = "$H$" '% work plan fix
        orgSheetCol(3) = "$E$" 'Customers in Incident Sustained
        orgSheetCol(4) = "$C3$" 'Plan Title
        orgSheetCol(5) = "$B33$" 'Years of Data
        orgSheetCol(6) = "$B37$" 'Annual Improved CML
    'Declare variables for cell values attained from RWP spreadsheets
     Dim RWPSheetvalues(100) As String
         RWPSheetvalues(0) = "" 'Autoisolation Point 1
         RWPSheetvalues(1) = "" 'CML for Point 1
         RWPSheetvalues(2) = "" '% Work Plan Fix
         RWPSheetvalues(3) = "" 'CI For Point 1
         RWPSheetvalues(4) = "" 'Autoisolation Point 2
         RWPSheetvalues(5) = "" 'CML for Point 2
         RWPSheetvalues(6) = "" '% Work Plan Fix
         RWPSheetvalues(7) = "" 'CI For Point 2
         RWPSheetvalues(8) = "" 'Autoisolation Point 3
         RWPSheetvalues(9) = "" 'CML for Point 3
         RWPSheetvalues(10) = "" '% Work Plan Fix
         RWPSheetvalues(11) = "" 'CI For Point 3
         RWPSheetvalues(12) = "" 'Autoisolation Point 4
         RWPSheetvalues(13) = "" 'CML for Point 4
         RWPSheetvalues(14) = "" '% Work Plan Fix
         RWPSheetvalues(15) = "" 'CI For Point 4
         RWPSheetvalues(16) = "" 'Autoisolation Point 5
         RWPSheetvalues(17) = "" 'CML for Point 5
         RWPSheetvalues(18) = "" '% Work Plan Fix
         RWPSheetvalues(19) = "" 'CI For Point 5
         RWPSheetvalues(20) = "" 'Autoisolation Point 6
         RWPSheetvalues(21) = "" 'CML for Point 6
         RWPSheetvalues(22) = "" '% Work Plan Fix
         RWPSheetvalues(23) = "" 'CI For Point 6
         RWPSheetvalues(24) = "" 'Autoisolation Point 7
         RWPSheetvalues(25) = "" 'CML for Point 7
         RWPSheetvalues(26) = "" '% Work Plan Fix
         RWPSheetvalues(27) = "" 'CI For Point 7
         RWPSheetvalues(28) = "" 'Autoisolation Point 8
         RWPSheetvalues(29) = "" 'CML for Point 8
         RWPSheetvalues(30) = "" '% Work Plan Fix
         RWPSheetvalues(31) = "" 'CI For Point 8
         RWPSheetvalues(32) = "" 'Autoisolation Point 9
         RWPSheetvalues(33) = "" 'CML for Point 9
         RWPSheetvalues(34) = "" '% Work Plan Fix
         RWPSheetvalues(35) = "" 'CI For Point 9
         RWPSheetvalues(36) = "" 'Autoisolation Point 10
         RWPSheetvalues(37) = "" 'CML for Point 10
         RWPSheetvalues(38) = "" '% Work Plan Fix
         RWPSheetvalues(39) = "" 'CI For Point 10
         RWPSheetvalues(40) = "" 'Autoisolation Point 11
         RWPSheetvalues(41) = "" 'CML for Point 11
         RWPSheetvalues(42) = "" '% Work Plan Fix
         RWPSheetvalues(43) = "" 'CI For Point 11
         RWPSheetvalues(44) = "" 'Autoisolation Point 12
         RWPSheetvalues(45) = "" 'CML for Point 12
         RWPSheetvalues(46) = "" '% Work Plan Fix
         RWPSheetvalues(47) = "" 'CI For Point 12
         RWPSheetvalues(48) = "" 'Autoisolation Point 13
         RWPSheetvalues(49) = "" 'CML for Point 13
         RWPSheetvalues(50) = "" '% Work Plan Fix
         RWPSheetvalues(51) = "" 'CI For Point 13
         RWPSheetvalues(52) = "" 'Autoisolation Point 14
         RWPSheetvalues(53) = "" 'CML for Point 14
         RWPSheetvalues(54) = "" '% Work Plan Fix
         RWPSheetvalues(55) = "" 'CI For Point 14
         RWPSheetvalues(56) = "" 'Autoisolation Point 15
         RWPSheetvalues(57) = "" 'CML for Point 15
         RWPSheetvalues(58) = "" '% Work Plan Fix
         RWPSheetvalues(59) = "" 'CI For Point 15
         RWPSheetvalues(60) = "" 'Autoisolation Point 16
         RWPSheetvalues(61) = "" 'CML for Point 16
         RWPSheetvalues(62) = "" '% Work Plan Fix
         RWPSheetvalues(63) = "" 'CI For Point 16
         RWPSheetvalues(64) = "" 'Autoisolation Point 17
         RWPSheetvalues(65) = "" 'CML for Point 17
         RWPSheetvalues(66) = "" '% Work Plan Fix
         RWPSheetvalues(67) = "" 'CI For Point 17
         RWPSheetvalues(68) = "" 'Autoisolation Point 18
         RWPSheetvalues(69) = "" 'CML for Point 18
         RWPSheetvalues(70) = "" '% Work Plan Fix
         RWPSheetvalues(71) = "" 'CI For Point 18
         RWPSheetvalues(72) = "" 'Autoisolation Point 19
         RWPSheetvalues(73) = "" 'CML for Point 19
         RWPSheetvalues(74) = "" '% Work Plan Fix
         RWPSheetvalues(75) = "" 'CI For Point 19
         RWPSheetvalues(76) = "" 'Autoisolation Point 20
         RWPSheetvalues(77) = "" 'CML for Point 20
         RWPSheetvalues(78) = "" '% Work Plan Fix
         RWPSheetvalues(79) = "" 'CI For Point 20
         RWPSheetvalues(80) = "" 'Autoisolation Point 21
         RWPSheetvalues(81) = "" 'CML for Point 21
         RWPSheetvalues(82) = "" '% Work Plan Fix
         RWPSheetvalues(83) = "" 'CI For Point 21
         RWPSheetvalues(84) = "" 'Autoisolation Point 22
         RWPSheetvalues(85) = "" 'CML for Point 22
         RWPSheetvalues(86) = "" '% Work Plan Fix
         RWPSheetvalues(87) = "" 'CI For Point 22
         RWPSheetvalues(88) = "" 'Autoisolation Point 23
         RWPSheetvalues(89) = "" 'CML for Point 23
         RWPSheetvalues(90) = "" '% Work Plan Fix
         RWPSheetvalues(91) = "" 'CI For Point 23
         RWPSheetvalues(92) = "" 'Autoisolation Point 24
         RWPSheetvalues(93) = "" 'CML for Point 24
         RWPSheetvalues(94) = "" '% Work Plan Fix
         RWPSheetvalues(95) = "" 'CI For Point 25
         RWPSheetvalues(96) = "" 'Plan Title
         RWPSheetvalues(97) = "" 'File Location
         RWPSheetvalues(98) = "" 'Years of Data
         RWPSheetvalues(99) = "" 'Annual Improved CML
     Dim cellstring As String
     Dim rowstring As String
     Dim rownumber As Integer
     Dim i As Integer
     Dim ii As Integer
     rowstring = CStr(rownumber)
     Dim Mycheck As String

     Do Until rs.EOF
         Set wkb = xls.Workbooks.Open(File, ReadOnly:=True, UpdateLinks:=False)
         Set wks = wkb.Worksheets("Benefit of Plan")
         ii = 0
         For rownumber = 7 To 30
             rowstring = CStr(rownumber)
             For i = 0 To 3
                 cellstring = orgSheetCol(i) & rowstring
                 RWPSheetvalues(ii) = wks.Range(cellstring).Value
                 If RWPSheetvalues(ii) = "" Then
                     RWPSheetvalues(ii) = "0"
                 End If
                 Mycheck = VarType(RWPSheetvalues(ii))
                 ii = ii + 1
                 Dim x As String
             Next i
         Next rownumber
         RWPSheetvalues(96) = wks.Range("C3").Value
         RWPSheetvalues(97) = File
         RWPSheetvalues(98) = wks.Range("B33").Value
         RWPSheetvalues(99) = wks.Range("B37").Value
         wkb.Close False 'Close workbook.  False is so that it doesn't save
         tablecheck = DCount("PlanTitle", "AIP&BOP", "PlanTitle = '" & RWPSheetvalues(96) & "'") 'check AIP & BOP table to see if plan is already there
         If tablecheck = 0 Then
             rs2!PlanTitle.Value = RWPSheetvalues(96)
             rs2!FileLocation.Value = RWPSheetvalues(97)
             rs2!YearsofData.Value = RWPSheetvalues(98)
             rs2!AnnualImprovedCML.Value = RWPSheetvalues(99)
             rs2!AIP1.Value = RWPSheetvalues(0)
             rs2!AIP1CML.Value = RWPSheetvalues(1)
             rs2!AIP1BOP.Value = RWPSheetvalues(2)
             rs2!AIP1CI.Value = RWPSheetvalues(3)
             rs2!AIP2.Value = RWPSheetvalues(4)
             rs2!AIP2CML.Value = RWPSheetvalues(5)
             rs2!AIP2BOP.Value = RWPSheetvalues(6)
             rs2!AIP2CI.Value = RWPSheetvalues(7)
             rs2!AIP3.Value = RWPSheetvalues(8)
             rs2!AIP3CML.Value = RWPSheetvalues(9)
             rs2!AIP3BOP.Value = RWPSheetvalues(10)
             rs2!AIP3CI.Value = RWPSheetvalues(11)
             rs2!AIP4.Value = RWPSheetvalues(12)
             rs2!AIP4CML.Value = RWPSheetvalues(13)
             rs2!AIP4BOP.Value = RWPSheetvalues(14)
             rs2!AIP4CI.Value = RWPSheetvalues(15)
             rs2!AIP5.Value = RWPSheetvalues(16)
             rs2!AIP5CML.Value = RWPSheetvalues(17)
             rs2!AIP5BOP.Value = RWPSheetvalues(18)
             rs2!AIP5CI.Value = RWPSheetvalues(19)
             rs2!AIP6.Value = RWPSheetvalues(20)
             rs2!AIP6CML.Value = RWPSheetvalues(21)
             rs2!AIP6BOP.Value = RWPSheetvalues(22)
             rs2!AIP6CI.Value = RWPSheetvalues(23)
             rs2!AIP7.Value = RWPSheetvalues(24)
             rs2!AIP7CML.Value = RWPSheetvalues(25)
             rs2!AIP7BOP.Value = RWPSheetvalues(26)
             rs2!AIP7CI.Value = RWPSheetvalues(27)
             rs2!AIP8.Value = RWPSheetvalues(28)
             rs2!AIP9CML.Value = RWPSheetvalues(29)
             rs2!AIP8BOP.Value = RWPSheetvalues(30)
             rs2!AIP8CI.Value = RWPSheetvalues(31)
             rs2!AIP9.Value = RWPSheetvalues(32)
             rs2!AIP9CML.Value = RWPSheetvalues(33)
             rs2!AIP9BOP.Value = RWPSheetvalues(34)
             rs2!AIP9CI.Value = RWPSheetvalues(35)
             rs2!AIP10.Value = RWPSheetvalues(36)
             rs2!AIP10CML.Value = RWPSheetvalues(37)
             rs2!AIP10BOP.Value = RWPSheetvalues(38)
             rs2!AIP10CI.Value = RWPSheetvalues(39)
             rs2!AIP11.Value = RWPSheetvalues(40)
             rs2!AIP11CML.Value = RWPSheetvalues(41)
             rs2!AIP11BOP.Value = RWPSheetvalues(42)
             rs2!AIP11CI.Value = RWPSheetvalues(43)
             rs2!AIP12.Value = RWPSheetvalues(44)
             rs2!AIP12CML.Value = RWPSheetvalues(45)
             rs2!AIP12BOP.Value = RWPSheetvalues(46)
             rs2!AIP12CI.Value = RWPSheetvalues(47)
             rs2!AIP13.Value = RWPSheetvalues(48)
             rs2!AIP13CML.Value = RWPSheetvalues(49)
             rs2!AIP13BOP.Value = RWPSheetvalues(50)
             rs2!AIP13CI.Value = RWPSheetvalues(51)
             rs2!AIP14.Value = RWPSheetvalues(52)
             rs2!AIP14CML.Value = RWPSheetvalues(53)
             rs2!AIP14BOP.Value = RWPSheetvalues(54)
             rs2!AIP14CI.Value = RWPSheetvalues(55)
             rs2!AIP15.Value = RWPSheetvalues(56)
             rs2!AIP15CML.Value = RWPSheetvalues(57)
             rs2!AIP15BOP.Value = RWPSheetvalues(58)
             rs2!AIP15CI.Value = RWPSheetvalues(59)
             rs2!AIP16.Value = RWPSheetvalues(60)
             rs2!AIP16CML.Value = RWPSheetvalues(61)
             rs2!AIP16BOP.Value = RWPSheetvalues(62)
             rs2!AIP16CI.Value = RWPSheetvalues(63)
             rs2!AIP17.Value = RWPSheetvalues(64)
             rs2!AIP17CML.Value = RWPSheetvalues(65)
             rs2!AIP17BOP.Value = RWPSheetvalues(66)
             rs2!AIP17CI.Value = RWPSheetvalues(67)
             rs2!AIP18.Value = RWPSheetvalues(68)
             rs2!AIP18CML.Value = RWPSheetvalues(69)
             rs2!AIP18BOP.Value = RWPSheetvalues(70)
             rs2!AIP18CI.Value = RWPSheetvalues(71)
             rs2!AIP19.Value = RWPSheetvalues(72)
             rs2!AIP9CML.Value = RWPSheetvalues(73)
             rs2!AIP19BOP.Value = RWPSheetvalues(74)
             rs2!AIP19CI.Value = RWPSheetvalues(75)
             rs2!AIP20.Value = RWPSheetvalues(76)
             rs2!AIP20CML.Value = RWPSheetvalues(77)
             rs2!AIP20BOP.Value = RWPSheetvalues(78)
             rs2!AIP20CI.Value = RWPSheetvalues(79)
             rs2!AIP21.Value = RWPSheetvalues(80)
             rs2!AIP21CML.Value = RWPSheetvalues(81)
             rs2!AIP21BOP.Value = RWPSheetvalues(82)
             rs2!AIP21CI.Value = RWPSheetvalues(83)
             rs2!AIP22.Value = RWPSheetvalues(84)
             rs2!AIP22CML.Value = RWPSheetvalues(85)
             rs2!AIP22BOP.Value = RWPSheetvalues(86)
             rs2!AIP22CI.Value = RWPSheetvalues(87)
             rs2!AIP23.Value = RWPSheetvalues(88)
             rs2!AIP23CML.Value = RWPSheetvalues(89)
             rs2!AIP23BOP.Value = RWPSheetvalues(90)
             rs2!AIP23CI.Value = RWPSheetvalues(91)
             rs2!AIP24.Value = RWPSheetvalues(92)
             rs2!AIP24CML.Value = RWPSheetvalues(93)
             rs2!AIP24BOP.Value = RWPSheetvalues(94)
             rs2!AIP24CI.Value = RWPSheetvalues(95)
             rs2.Update
         End If
         rs.MoveNext

     Loop
     rs.Close
     rs2.Close

End Sub
</code>```

答:
You seem to be missing

```<code>rs2.AddNew
</code>```

before setting its column values.

ContentLicense: CC BY-SA 4.0

Body:
I get a runtime error (3020) when trying to add information to a new record.

It errors out on the line: rs2!PlanTitle.Value = RWPSheetvalues(96)

Private Sub ImportRWPData_Click()
    Dim db As Database
    Dim rs As Recordset
    Dim rs2 As DAO.Recordset
    Dim File As Field
    Dim Location As String
    Set db = CurrentDb()
    Set rs = db.OpenRecordset("rwpT")
    Set rs2 = db.OpenRecordset("AIP&BOP")
    Set File = rs.Fields("File")
    Dim xls     As Excel.Application
    Dim wkb     As Excel.Workbook
    Dim wks     As Excel.Worksheet
    Set xls = New Excel.Application
    'Declare variables for column values in RWP spreadsheets
    Dim orgSheetCol(7) As String
        orgSheetCol(0) = "$A$" 'Auto Isolation Point
        orgSheetCol(1) = "$D$" 'Customer Minutes Lost
        orgSheetCol(2) = "$H$" '% work plan fix
        orgSheetCol(3) = "$E$" 'Customers in Incident Sustained
        orgSheetCol(4) = "$C3$" 'Plan Title
        orgSheetCol(5) = "$B33$" 'Years of Data
        orgSheetCol(6) = "$B37$" 'Annual Improved CML
    'Declare variables for cell values attained from RWP spreadsheets
     Dim RWPSheetvalues(100) As String
         RWPSheetvalues(0) = "" 'Autoisolation Point 1
         RWPSheetvalues(1) = "" 'CML for Point 1
         RWPSheetvalues(2) = "" '% Work Plan Fix
         RWPSheetvalues(3) = "" 'CI For Point 1
         RWPSheetvalues(4) = "" 'Autoisolation Point 2
         RWPSheetvalues(5) = "" 'CML for Point 2
         RWPSheetvalues(6) = "" '% Work Plan Fix
         RWPSheetvalues(7) = "" 'CI For Point 2
         RWPSheetvalues(8) = "" 'Autoisolation Point 3
         RWPSheetvalues(9) = "" 'CML for Point 3
         RWPSheetvalues(10) = "" '% Work Plan Fix
         RWPSheetvalues(11) = "" 'CI For Point 3
         RWPSheetvalues(12) = "" 'Autoisolation Point 4
         RWPSheetvalues(13) = "" 'CML for Point 4
         RWPSheetvalues(14) = "" '% Work Plan Fix
         RWPSheetvalues(15) = "" 'CI For Point 4
         RWPSheetvalues(16) = "" 'Autoisolation Point 5
         RWPSheetvalues(17) = "" 'CML for Point 5
         RWPSheetvalues(18) = "" '% Work Plan Fix
         RWPSheetvalues(19) = "" 'CI For Point 5
         RWPSheetvalues(20) = "" 'Autoisolation Point 6
         RWPSheetvalues(21) = "" 'CML for Point 6
         RWPSheetvalues(22) = "" '% Work Plan Fix
         RWPSheetvalues(23) = "" 'CI For Point 6
         RWPSheetvalues(24) = "" 'Autoisolation Point 7
         RWPSheetvalues(25) = "" 'CML for Point 7
         RWPSheetvalues(26) = "" '% Work Plan Fix
         RWPSheetvalues(27) = "" 'CI For Point 7
         RWPSheetvalues(28) = "" 'Autoisolation Point 8
         RWPSheetvalues(29) = "" 'CML for Point 8
         RWPSheetvalues(30) = "" '% Work Plan Fix
         RWPSheetvalues(31) = "" 'CI For Point 8
         RWPSheetvalues(32) = "" 'Autoisolation Point 9
         RWPSheetvalues(33) = "" 'CML for Point 9
         RWPSheetvalues(34) = "" '% Work Plan Fix
         RWPSheetvalues(35) = "" 'CI For Point 9
         RWPSheetvalues(36) = "" 'Autoisolation Point 10
         RWPSheetvalues(37) = "" 'CML for Point 10
         RWPSheetvalues(38) = "" '% Work Plan Fix
         RWPSheetvalues(39) = "" 'CI For Point 10
         RWPSheetvalues(40) = "" 'Autoisolation Point 11
         RWPSheetvalues(41) = "" 'CML for Point 11
         RWPSheetvalues(42) = "" '% Work Plan Fix
         RWPSheetvalues(43) = "" 'CI For Point 11
         RWPSheetvalues(44) = "" 'Autoisolation Point 12
         RWPSheetvalues(45) = "" 'CML for Point 12
         RWPSheetvalues(46) = "" '% Work Plan Fix
         RWPSheetvalues(47) = "" 'CI For Point 12
         RWPSheetvalues(48) = "" 'Autoisolation Point 13
         RWPSheetvalues(49) = "" 'CML for Point 13
         RWPSheetvalues(50) = "" '% Work Plan Fix
         RWPSheetvalues(51) = "" 'CI For Point 13
         RWPSheetvalues(52) = "" 'Autoisolation Point 14
         RWPSheetvalues(53) = "" 'CML for Point 14
         RWPSheetvalues(54) = "" '% Work Plan Fix
         RWPSheetvalues(55) = "" 'CI For Point 14
         RWPSheetvalues(56) = "" 'Autoisolation Point 15
         RWPSheetvalues(57) = "" 'CML for Point 15
         RWPSheetvalues(58) = "" '% Work Plan Fix
         RWPSheetvalues(59) = "" 'CI For Point 15
         RWPSheetvalues(60) = "" 'Autoisolation Point 16
         RWPSheetvalues(61) = "" 'CML for Point 16
         RWPSheetvalues(62) = "" '% Work Plan Fix
         RWPSheetvalues(63) = "" 'CI For Point 16
         RWPSheetvalues(64) = "" 'Autoisolation Point 17
         RWPSheetvalues(65) = "" 'CML for Point 17
         RWPSheetvalues(66) = "" '% Work Plan Fix
         RWPSheetvalues(67) = "" 'CI For Point 17
         RWPSheetvalues(68) = "" 'Autoisolation Point 18
         RWPSheetvalues(69) = "" 'CML for Point 18
         RWPSheetvalues(70) = "" '% Work Plan Fix
         RWPSheetvalues(71) = "" 'CI For Point 18
         RWPSheetvalues(72) = "" 'Autoisolation Point 19
         RWPSheetvalues(73) = "" 'CML for Point 19
         RWPSheetvalues(74) = "" '% Work Plan Fix
         RWPSheetvalues(75) = "" 'CI For Point 19
         RWPSheetvalues(76) = "" 'Autoisolation Point 20
         RWPSheetvalues(77) = "" 'CML for Point 20
         RWPSheetvalues(78) = "" '% Work Plan Fix
         RWPSheetvalues(79) = "" 'CI For Point 20
         RWPSheetvalues(80) = "" 'Autoisolation Point 21
         RWPSheetvalues(81) = "" 'CML for Point 21
         RWPSheetvalues(82) = "" '% Work Plan Fix
         RWPSheetvalues(83) = "" 'CI For Point 21
         RWPSheetvalues(84) = "" 'Autoisolation Point 22
         RWPSheetvalues(85) = "" 'CML for Point 22
         RWPSheetvalues(86) = "" '% Work Plan Fix
         RWPSheetvalues(87) = "" 'CI For Point 22
         RWPSheetvalues(88) = "" 'Autoisolation Point 23
         RWPSheetvalues(89) = "" 'CML for Point 23
         RWPSheetvalues(90) = "" '% Work Plan Fix
         RWPSheetvalues(91) = "" 'CI For Point 23
         RWPSheetvalues(92) = "" 'Autoisolation Point 24
         RWPSheetvalues(93) = "" 'CML for Point 24
         RWPSheetvalues(94) = "" '% Work Plan Fix
         RWPSheetvalues(95) = "" 'CI For Point 25
         RWPSheetvalues(96) = "" 'Plan Title
         RWPSheetvalues(97) = "" 'File Location
         RWPSheetvalues(98) = "" 'Years of Data
         RWPSheetvalues(99) = "" 'Annual Improved CML
     Dim cellstring As String
     Dim rowstring As String
     Dim rownumber As Integer
     Dim i As Integer
     Dim ii As Integer
     rowstring = CStr(rownumber)
     Dim Mycheck As String

     Do Until rs.EOF
         Set wkb = xls.Workbooks.Open(File, ReadOnly:=True, UpdateLinks:=False)
         Set wks = wkb.Worksheets("Benefit of Plan")
         ii = 0
         For rownumber = 7 To 30
             rowstring = CStr(rownumber)
             For i = 0 To 3
                 cellstring = orgSheetCol(i) & rowstring
                 RWPSheetvalues(ii) = wks.Range(cellstring).Value
                 If RWPSheetvalues(ii) = "" Then
                     RWPSheetvalues(ii) = "0"
                 End If
                 Mycheck = VarType(RWPSheetvalues(ii))
                 ii = ii + 1
                 Dim x As String
             Next i
         Next rownumber
         RWPSheetvalues(96) = wks.Range("C3").Value
         RWPSheetvalues(97) = File
         RWPSheetvalues(98) = wks.Range("B33").Value
         RWPSheetvalues(99) = wks.Range("B37").Value
         wkb.Close False 'Close workbook.  False is so that it doesn't save
         tablecheck = DCount("PlanTitle", "AIP&BOP", "PlanTitle = '" & RWPSheetvalues(96) & "'") 'check AIP & BOP table to see if plan is already there
         If tablecheck = 0 Then
             rs2!PlanTitle.Value = RWPSheetvalues(96)
             rs2!FileLocation.Value = RWPSheetvalues(97)
             rs2!YearsofData.Value = RWPSheetvalues(98)
             rs2!AnnualImprovedCML.Value = RWPSheetvalues(99)
             rs2!AIP1.Value = RWPSheetvalues(0)
             rs2!AIP1CML.Value = RWPSheetvalues(1)
             rs2!AIP1BOP.Value = RWPSheetvalues(2)
             rs2!AIP1CI.Value = RWPSheetvalues(3)
             rs2!AIP2.Value = RWPSheetvalues(4)
             rs2!AIP2CML.Value = RWPSheetvalues(5)
             rs2!AIP2BOP.Value = RWPSheetvalues(6)
             rs2!AIP2CI.Value = RWPSheetvalues(7)
             rs2!AIP3.Value = RWPSheetvalues(8)
             rs2!AIP3CML.Value = RWPSheetvalues(9)
             rs2!AIP3BOP.Value = RWPSheetvalues(10)
             rs2!AIP3CI.Value = RWPSheetvalues(11)
             rs2!AIP4.Value = RWPSheetvalues(12)
             rs2!AIP4CML.Value = RWPSheetvalues(13)
             rs2!AIP4BOP.Value = RWPSheetvalues(14)
             rs2!AIP4CI.Value = RWPSheetvalues(15)
             rs2!AIP5.Value = RWPSheetvalues(16)
             rs2!AIP5CML.Value = RWPSheetvalues(17)
             rs2!AIP5BOP.Value = RWPSheetvalues(18)
             rs2!AIP5CI.Value = RWPSheetvalues(19)
             rs2!AIP6.Value = RWPSheetvalues(20)
             rs2!AIP6CML.Value = RWPSheetvalues(21)
             rs2!AIP6BOP.Value = RWPSheetvalues(22)
             rs2!AIP6CI.Value = RWPSheetvalues(23)
             rs2!AIP7.Value = RWPSheetvalues(24)
             rs2!AIP7CML.Value = RWPSheetvalues(25)
             rs2!AIP7BOP.Value = RWPSheetvalues(26)
             rs2!AIP7CI.Value = RWPSheetvalues(27)
             rs2!AIP8.Value = RWPSheetvalues(28)
             rs2!AIP9CML.Value = RWPSheetvalues(29)
             rs2!AIP8BOP.Value = RWPSheetvalues(30)
             rs2!AIP8CI.Value = RWPSheetvalues(31)
             rs2!AIP9.Value = RWPSheetvalues(32)
             rs2!AIP9CML.Value = RWPSheetvalues(33)
             rs2!AIP9BOP.Value = RWPSheetvalues(34)
             rs2!AIP9CI.Value = RWPSheetvalues(35)
             rs2!AIP10.Value = RWPSheetvalues(36)
             rs2!AIP10CML.Value = RWPSheetvalues(37)
             rs2!AIP10BOP.Value = RWPSheetvalues(38)
             rs2!AIP10CI.Value = RWPSheetvalues(39)
             rs2!AIP11.Value = RWPSheetvalues(40)
             rs2!AIP11CML.Value = RWPSheetvalues(41)
             rs2!AIP11BOP.Value = RWPSheetvalues(42)
             rs2!AIP11CI.Value = RWPSheetvalues(43)
             rs2!AIP12.Value = RWPSheetvalues(44)
             rs2!AIP12CML.Value = RWPSheetvalues(45)
             rs2!AIP12BOP.Value = RWPSheetvalues(46)
             rs2!AIP12CI.Value = RWPSheetvalues(47)
             rs2!AIP13.Value = RWPSheetvalues(48)
             rs2!AIP13CML.Value = RWPSheetvalues(49)
             rs2!AIP13BOP.Value = RWPSheetvalues(50)
             rs2!AIP13CI.Value = RWPSheetvalues(51)
             rs2!AIP14.Value = RWPSheetvalues(52)
             rs2!AIP14CML.Value = RWPSheetvalues(53)
             rs2!AIP14BOP.Value = RWPSheetvalues(54)
             rs2!AIP14CI.Value = RWPSheetvalues(55)
             rs2!AIP15.Value = RWPSheetvalues(56)
             rs2!AIP15CML.Value = RWPSheetvalues(57)
             rs2!AIP15BOP.Value = RWPSheetvalues(58)
             rs2!AIP15CI.Value = RWPSheetvalues(59)
             rs2!AIP16.Value = RWPSheetvalues(60)
             rs2!AIP16CML.Value = RWPSheetvalues(61)
             rs2!AIP16BOP.Value = RWPSheetvalues(62)
             rs2!AIP16CI.Value = RWPSheetvalues(63)
             rs2!AIP17.Value = RWPSheetvalues(64)
             rs2!AIP17CML.Value = RWPSheetvalues(65)
             rs2!AIP17BOP.Value = RWPSheetvalues(66)
             rs2!AIP17CI.Value = RWPSheetvalues(67)
             rs2!AIP18.Value = RWPSheetvalues(68)
             rs2!AIP18CML.Value = RWPSheetvalues(69)
             rs2!AIP18BOP.Value = RWPSheetvalues(70)
             rs2!AIP18CI.Value = RWPSheetvalues(71)
             rs2!AIP19.Value = RWPSheetvalues(72)
             rs2!AIP9CML.Value = RWPSheetvalues(73)
             rs2!AIP19BOP.Value = RWPSheetvalues(74)
             rs2!AIP19CI.Value = RWPSheetvalues(75)
             rs2!AIP20.Value = RWPSheetvalues(76)
             rs2!AIP20CML.Value = RWPSheetvalues(77)
             rs2!AIP20BOP.Value = RWPSheetvalues(78)
             rs2!AIP20CI.Value = RWPSheetvalues(79)
             rs2!AIP21.Value = RWPSheetvalues(80)
             rs2!AIP21CML.Value = RWPSheetvalues(81)
             rs2!AIP21BOP.Value = RWPSheetvalues(82)
             rs2!AIP21CI.Value = RWPSheetvalues(83)
             rs2!AIP22.Value = RWPSheetvalues(84)
             rs2!AIP22CML.Value = RWPSheetvalues(85)
             rs2!AIP22BOP.Value = RWPSheetvalues(86)
             rs2!AIP22CI.Value = RWPSheetvalues(87)
             rs2!AIP23.Value = RWPSheetvalues(88)
             rs2!AIP23CML.Value = RWPSheetvalues(89)
             rs2!AIP23BOP.Value = RWPSheetvalues(90)
             rs2!AIP23CI.Value = RWPSheetvalues(91)
             rs2!AIP24.Value = RWPSheetvalues(92)
             rs2!AIP24CML.Value = RWPSheetvalues(93)
             rs2!AIP24BOP.Value = RWPSheetvalues(94)
             rs2!AIP24CI.Value = RWPSheetvalues(95)
             rs2.Update
         End If
         rs.MoveNext

     Loop
     rs.Close
     rs2.Close

End Sub

Body:
You seem to be missing

rs2.AddNew

before setting its column values.


问:
Constrained matrices
I need to create all the possible matrix of dimension 5 (5x5), where all elements are integers from 0 to 100 and its sum is 100.

I'm not sure how to do it, or how to start... Any suggestion?

Despite I program in R, I'm looking for an idea of how to do it. Pseucode is fine.

My firs approach was getting all the permutations of 100 elements 25 times (one for each element in the matrix) and then take only those that sum 100. But that is 100^25 permutations... no way to do it in this by this approach.

I will thanks any idea and/or help!

答:
Here's a function to generate a single target matrix -- probably not the most efficient way, and you'll only get all of the possible combos if you run a very large number of times. You can just use lapply() over rep(5, num) as below to generate num of them.

```<code>norm100 <- function(n=5){

  # generate some random values
  vec <- sample(0:100, size=n^2)

  # put them in a matrix, normalizing to 100 and rounding
  mat <- matrix(round((vec / sum(vec)) * 100), nrow=n)

  # find out how much the rounding makes us deviate from 100
  off_by <- sum(mat) - 100

  # get a random matrix element index
  modify_idx <- sample(length(mat), 1)

  # if adjusting by `off_by` would put us out of the target interval, try again
  while ((mat[modify_idx] - off_by) < 0 | (mat[modify_idx] - off_by) > 100){
    modify_idx <- sample(length(mat), 1)
  }

  # once we have one (usually on the first shot), adjust so that mat sums to 100
  mat[modify_idx] <- mat[modify_idx] - off_by
  return(mat)
}

runs <- 1000
matrices <- lapply(rep(5, runs), norm100)
</code>```

I haven't gotten any duplicates even after a few runs of 100,000, but if you do, you can always just toss the dupes.

Title: Constrained matrices

Body:
Here's a function to generate a single target matrix -- probably not the most efficient way, and you'll only get all of the possible combos if you run a very large number of times. You can just use lapply() over rep(5, num) as below to generate num of them.

norm100 <- function(n=5){

  # generate some random values
  vec <- sample(0:100, size=n^2)

  # put them in a matrix, normalizing to 100 and rounding
  mat <- matrix(round((vec / sum(vec)) * 100), nrow=n)

  # find out how much the rounding makes us deviate from 100
  off_by <- sum(mat) - 100

  # get a random matrix element index
  modify_idx <- sample(length(mat), 1)

  # if adjusting by `off_by` would put us out of the target interval, try again
  while ((mat[modify_idx] - off_by) < 0 | (mat[modify_idx] - off_by) > 100){
    modify_idx <- sample(length(mat), 1)
  }

  # once we have one (usually on the first shot), adjust so that mat sums to 100
  mat[modify_idx] <- mat[modify_idx] - off_by
  return(mat)
}

runs <- 1000
matrices <- lapply(rep(5, runs), norm100)

I haven't gotten any duplicates even after a few runs of 100,000, but if you do, you can always just toss the dupes.


问:
invalid syntax at cx_Freeze executables
I made a tkinter application in windows and now I want to make an executable version of it. multiframe.py contains all the the code of the tkinter application.

But when I try to build it I always get syntax error but I don't get it why. Here is a cmd snapshot.

This is how my setup.py looks like:

```<code>    import cx_Freeze

    base = None

    if sys.platform == 'Win32':
            base = "Win32GUI"

    executables = [cx_Freeze.Executable("frame.py"), base=base, icon='ds.ico']

    cx_Freeze.setup(
            name="cuQ",
            options = {"build_exe": {"packages":["tkinter"], include_files=["ds.ico"]},
            version= "0.01",
            description = "dasdasd",
            executables = executables
            )
</code>```

答:
base and icon are options of cx_Freeze.Executable in your code they're not being passed to it. They need to be in () just like "frame.py" is so use:

```<code>executables = cx_Freeze.Executable("frame.py", base=base, icon='ds.ico')
</code>```

In cx_Freeze.setup(options = ... you're first adding a dictionary key "packages" as part of the value for the dictionary key "build_exe" but then suddenly you're trying to add a list include_files instead of a key while still inside the dictionary that is the part of the value alongside "packages" to "build_exe" key. It's hard to describe. Anyway.

Your whole code should look like:

```<code>import cx_Freeze, sys

base = None

if sys.platform == 'Win32':
    base = "Win32GUI"

executables = cx_Freeze.Executable("frame.py", base=base, icon='ds.ico')

cx_Freeze.setup(
        name="cYou",
        options = {"build_exe": {"packages":["tkinter"], "include_files":["ds.ico"]}},
        version= "0.01",
        description = "dasdasd",
        executables = executables
        )
</code>```

Below is what I use for tkinter. I just put my tkinter script something.py next to this script. Then I just respond to it something. Some modifications may need to be done in order to include icon files and such:

```<code>from cx_Freeze import setup, Executable
import sys, os

fileName = input("What's the name of the py file to be converted to .exe?\n")
sys.argv.append('build')

os.environ['TCL_LIBRARY'] = r'C:\Users\username\AppData\Local\Programs\Python\Python36\tcl\tcl8.6'
os.environ['TK_LIBRARY'] = r'C:\Users\username\AppData\Local\Programs\Python\Python36\tcl\tk8.6'

base = None
if (sys.platform == "win32"):
    base = "Win32GUI"    # Tells the build script to hide the console.
elif (sys.platform == "win64"):
    base = "Win64GUI"    # Tells the build script to hide the console.

setup(
    name='KutsalAklinNerde?',
    version='0.1',              #Further information about its version
    description='Parse stuff',  #It's description
    executables=[Executable(fileName + ".py", base=base)])
</code>```

Title: invalid syntax at cx_Freeze executables

Body:
I made a tkinter application in windows and now I want to make an executable version of it. multiframe.py contains all the the code of the tkinter application.

But when I try to build it I always get syntax error but I don't get it why. Here is a cmd snapshot.

This is how my setup.py looks like:

    import cx_Freeze

    base = None

    if sys.platform == 'Win32':
            base = "Win32GUI"

    executables = [cx_Freeze.Executable("frame.py"), base=base, icon='ds.ico']

    cx_Freeze.setup(
            name="cuQ",
            options = {"build_exe": {"packages":["tkinter"], include_files=["ds.ico"]},
            version= "0.01",
            description = "dasdasd",
            executables = executables
            )

Body:
base and icon are options of cx_Freeze.Executable in your code they're not being passed to it. They need to be in () just like "frame.py" is so use:

executables = cx_Freeze.Executable("frame.py", base=base, icon='ds.ico')

In cx_Freeze.setup(options = ... you're first adding a dictionary key "packages" as part of the value for the dictionary key "build_exe" but then suddenly you're trying to add a list include_files instead of a key while still inside the dictionary that is the part of the value alongside "packages" to "build_exe" key. It's hard to describe. Anyway.

Your whole code should look like:

import cx_Freeze, sys

base = None

if sys.platform == 'Win32':
    base = "Win32GUI"

executables = cx_Freeze.Executable("frame.py", base=base, icon='ds.ico')

cx_Freeze.setup(
        name="cYou",
        options = {"build_exe": {"packages":["tkinter"], "include_files":["ds.ico"]}},
        version= "0.01",
        description = "dasdasd",
        executables = executables
        )

Below is what I use for tkinter. I just put my tkinter script something.py next to this script. Then I just respond to it something. Some modifications may need to be done in order to include icon files and such:

from cx_Freeze import setup, Executable
import sys, os

fileName = input("What's the name of the py file to be converted to .exe?\n")
sys.argv.append('build')

os.environ['TCL_LIBRARY'] = r'C:\Users\username\AppData\Local\Programs\Python\Python36\tcl\tcl8.6'
os.environ['TK_LIBRARY'] = r'C:\Users\username\AppData\Local\Programs\Python\Python36\tcl\tk8.6'

base = None
if (sys.platform == "win32"):
    base = "Win32GUI"    # Tells the build script to hide the console.
elif (sys.platform == "win64"):
    base = "Win64GUI"    # Tells the build script to hide the console.

setup(
    name='KutsalAklinNerde?',
    version='0.1',              #Further information about its version
    description='Parse stuff',  #It's description
    executables=[Executable(fileName + ".py", base=base)])


问:
Can't see admob on real android device
I have app in the android market
I add to this app admob ,I can see the advertisement in the test mode.
so I upload a upgrade version to the market.
after that I download the app to my device but I dont see there nothing.
On the website of admob I can see 635 Requests but no money 0.0$
So what is the reason that the advertisement don't show up?

Thanks
Beno

答:
Admob doesn't serve ads for all requests. In the administration of admob you should be able to find something they call impressions. That is the number of ads actually viewed. You should also find something they call "fillrate". That is the ratio between impressions and requests.

Admob says it might take a while before the system is warmed up before starting to actually return impressions for requests. And you will not see that you make any money unless people press the ads.

So be a little patient and the ads will probably show up.

Best regards
Roland

Title: Can't see admob on real android device


问:
What's a RegEx to match any numeric OR question mark?
I'm using this Regular Expression "\d+" to match any numeric (0-9)
in my code, but how can I alter it to also include question marks?

For example, I want 04/??/1992 to return 04??1992, and I want -123?6 to return 123?6, and I want just 123 to return 123. Basically, I want to match any number (0-9) and question marks only.

Any help would be greatly appreciated! Thank you.

答:
You can use the [] operator to specify the character class, which expands what is allowed to match.

Your solution would be [\d?]+


问:
How can I decode a JSON response with an unknown key in Swift?
I would like to split up the data in https://blockchain.info/ticker so that each line is its own String in an array.

I'm making an app that gets the price of the selected currency. So if someone wants AUD then it will get the second string in the array and then show the price which is in the last tag.

I currently just have it downloading the json..

```<code>func reloadJson(){

    if globalVariables.currencySelected == "" {
        globalVariables.currencySelected = globalVariables.currencySelected + "AUD"
    }
    print(globalVariables.currencySelected)

    if let blockchainTickerURL = URL(string: "https://blockchain.info/ticker") {

        let request = NSMutableURLRequest(url: blockchainTickerURL)
        let task = URLSession.shared.dataTask(with: request as URLRequest) {
            data, response, error in
            var message = ""

            if error != nil {
                print("error")
            } else {
                if let unwrappedData = data {
                    let dataString = NSString(data: unwrappedData, encoding: String.Encoding.utf8.rawValue)
</code>```

Thats just a copy and paste of what I currently have, its not exactly formatted right.

Thanks

答:
You should take a look at Swift4 Codable protocol.

Create a structure for the currency dictionary values that conforms to Codable with the corresponding properties:

```<code>struct Currency: Codable {
    let fifteenM: Double
    let last: Double
    let buy: Double
    let sell: Double
    let symbol: String
    private enum CodingKeys: String, CodingKey {
        case fifteenM = "15m", last, buy, sell, symbol
    }
}
</code>```

To decode your JSON data you need to use JSONDecoder passing the dictionary with custom values [String: Currency] as the type to be decoded:

```<code>let url = URL(string: "https://blockchain.info/ticker")!
URLSession.shared.dataTask(with: url) { data, response, error in
    guard let data = data else { return }
    do {
        let currencies = try JSONDecoder().decode([String: Currency].self, from: data)
        if let usd = currencies["USD"] {
            print("USD - 15m:", usd.fifteenM)
            print("USD - last:", usd.last)
            print("USD - buy:", usd.buy)
            print("USD - sell:", usd.sell)
            print("USD - symbol:", usd.symbol)
        }
    } catch { print(error) }

}.resume()
</code>```

This will print

USD - 15m: 11694.03

USD - last: 11694.03

USD - buy: 11695.01

USD - sell: 11693.04

USD - symbol: $

Body:
I would like to split up the data in https://blockchain.info/ticker so that each line is its own String in an array.

I'm making an app that gets the price of the selected currency. So if someone wants AUD then it will get the second string in the array and then show the price which is in the last tag.

I currently just have it downloading the json..

func reloadJson(){

    if globalVariables.currencySelected == "" {
        globalVariables.currencySelected = globalVariables.currencySelected + "AUD"
    }
    print(globalVariables.currencySelected)

    if let blockchainTickerURL = URL(string: "https://blockchain.info/ticker") {

        let request = NSMutableURLRequest(url: blockchainTickerURL)
        let task = URLSession.shared.dataTask(with: request as URLRequest) {
            data, response, error in
            var message = ""

            if error != nil {
                print("error")
            } else {
                if let unwrappedData = data {
                    let dataString = NSString(data: unwrappedData, encoding: String.Encoding.utf8.rawValue)

Thats just a copy and paste of what I currently have, its not exactly formatted right.

Thanks

Body:
You should take a look at Swift4 Codable protocol.

Create a structure for the currency dictionary values that conforms to Codable with the corresponding properties:

struct Currency: Codable {
    let fifteenM: Double
    let last: Double
    let buy: Double
    let sell: Double
    let symbol: String
    private enum CodingKeys: String, CodingKey {
        case fifteenM = "15m", last, buy, sell, symbol
    }
}

To decode your JSON data you need to use JSONDecoder passing the dictionary with custom values [String: Currency] as the type to be decoded:

let url = URL(string: "https://blockchain.info/ticker")!
URLSession.shared.dataTask(with: url) { data, response, error in
    guard let data = data else { return }
    do {
        let currencies = try JSONDecoder().decode([String: Currency].self, from: data)
        if let usd = currencies["USD"] {
            print("USD - 15m:", usd.fifteenM)
            print("USD - last:", usd.last)
            print("USD - buy:", usd.buy)
            print("USD - sell:", usd.sell)
            print("USD - symbol:", usd.symbol)
        }
    } catch { print(error) }

}.resume()

This will print

USD - 15m: 11694.03

USD - last: 11694.03

USD - buy: 11695.01

USD - sell: 11693.04

USD - symbol: $


问:
How to reference foreign key in mysql at phpmyadmin
I am using mysql in phpmyadmin. I have created two tables.

```<code>company (
company_id INT PRIMARY KEY,
company_name VARCHAR(20)
);

users (
user_id INT PRIMARY KEY,
user_first_name VARCHAR(20) ,
user_last_name VARCHAR(20),
user_type VARCHAR(10),
user_email VARCHAR(40)
);
</code>```

Now i want to declare Foreign key company(company) reference to users(user_id). SO company will be primary and foreign key at same time. How do i Do that?

答:
You're looking to add the following to the users table:

```<code>FOREIGN KEY (company) REFERENCES company(company_id)
</code>```

Which will create a new key in that table called company, which references the company_id of the company table.

Body:
I am using mysql in phpmyadmin. I have created two tables.

company (
company_id INT PRIMARY KEY,
company_name VARCHAR(20)
);

users (
user_id INT PRIMARY KEY,
user_first_name VARCHAR(20) ,
user_last_name VARCHAR(20),
user_type VARCHAR(10),
user_email VARCHAR(40)
);

Now i want to declare Foreign key company(company) reference to users(user_id). SO company will be primary and foreign key at same time. How do i Do that?

Body:
You're looking to add the following to the users table:

FOREIGN KEY (company) REFERENCES company(company_id)

Which will create a new key in that table called company, which references the company_id of the company table.


问:
"total += i;" does not work for some reason
For some reason the "total += i;" wont work and when i go to return "total" it returns as 0.

```<code>long int sumOfGroup(int k) {
    long int special = (k * k) + (k - 1);
    long int limit =  special - ((k-1) * 2);
    cout << special << " " << limit << endl;
    long int total = 0;
    for(int i = special; i <= limit; i - 2){
        total += i;
    }
    return  total;
}

int main() {
    int k;
    cin >> k;
    long answer = sumOfGroup(k);
    cout << answer << endl;
    return 0;
}
</code>```

if you ran this no matter the input the answer is 0. all my other numbers are correct and I am quite sure it has something to do with the for loop.

答:
Your total += i doesn't make any effect because it is never executed!

What are the values of special and limit printed before you try to enter the loop?

Body:
For some reason the "total += i;" wont work and when i go to return "total" it returns as 0.

long int sumOfGroup(int k) {
    long int special = (k * k) + (k - 1);
    long int limit =  special - ((k-1) * 2);
    cout << special << " " << limit << endl;
    long int total = 0;
    for(int i = special; i <= limit; i - 2){
        total += i;
    }
    return  total;
}

int main() {
    int k;
    cin >> k;
    long answer = sumOfGroup(k);
    cout << answer << endl;
    return 0;
}

if you ran this no matter the input the answer is 0. all my other numbers are correct and I am quite sure it has something to do with the for loop.


问:
What algorithm to use for Dynamic Scheduling System?
I'm planning to develop an expert system that automatically fits the school faculty's work load (time, teaching load, etc), and generate class sections, room that is at least 90% accurate with what the Director of a certain department wants to assign the schedule for a certain semester.

What algorithm to use? Heuristics? Optimization? Any suggestions or help is highly appreciated!

答:
Here are some general observations:

1) Manual scheduling is rarely attempted from scratch. Instead, somebody starts with the schedule for the previous year and alters it to take account of changes in requirements. One way of mimicing this with a computer is to use a hill-climbing algorithm, which repeatedly tries a number of small changes to improve a solution so far. This can then be started off at the current schedule.

2) Does the manual process ever terminate with the conclusion that the requirements are collectively unachievable and that some of them must be dropped? In that case your algorithm must be transparent enough that failures can be understood, or at least capable of proposing such changes (e.g. by maximising a penalty function which allows it to produce a "least bad" solution which does not satisfy all of the original constraints). I know of one case where a sophisticated constraint-based approach was replaced by a much simpler algorithm because failures of the constraint-based system did not give enough user feed back.

3) Curiously enough, the next generation system did not use sophisticated scheduling at all. It turned out - roughly speaking - that at the time the decisions had to be made not all of the consequences of sophisticated scheduling decisions could be forseen, and, in the long run, a simple predictable schedule that could be maintained indefinitely was more productive than constantly rearranging schedules to grab small momentary advantages.


问:
XML files are downloading rather than viewing in Sharepoint
We have two SharePoint 2013 sites. On one site, sitemap.xml is opened up in the browser. On another site, sitemap.xml is automatically downloaded rather than rendered in the browser.

Is there a setting that can be changed for this?

(fyi, this stackoverflow post does not resolve the issue: SharePoint: render, rather than download, XML file).

答: In central admin, Application Management > manage web applications, select your web app and go to it's settings.  In there, you should be a "Browser File Handling" section.  If it's set to strict, that's what's likely causing the file to download.  Set it to permissive and your problem may go away.  Keep in mind, that is a security feature.  </p>


问:
How to run SVC classifier after running 10-fold cross validation in sklearn?
I'm relatively new to machine learning and would like some help in the following:

I ran a Support Vector Machine Classifier (SVC) on my data with 10-fold cross validation and calculated the accuracy score (which was around 89%). I'm using Python and scikit-learn to perform the task. Here's a code snippet:

```<code>def get_scores(features,target,classifier):
  X_train, X_test, y_train, y_test =train_test_split(features, target ,
    test_size=0.3)
    scores = cross_val_score(
    classifier,
    X_train,
    y_train,
    cv=10,
    scoring='accuracy',
    n_jobs=-1)
 return(scores)

get_scores(features_from_df,target_from_df,svm.SVC())
</code>```

Now, how can I use my classifier (after running the 10-folds cv) to test it on X_test and compare the predicted results to y_test? As you may have noticed, I only used X_train and y_train in the cross validation process.

I noticed that sklearn have cross_val_predict:
http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.cross_val_predict.html should I replace my cross_val_score by cross_val_predict? just FYI: my target data column is binarized (have values of 0s and 1s).

If my approach is wrong, please advise me with the best way to proceed with.

Thanks!

答:
You're almost there:

```<code># Build your classifier
classifier = svm.SVC()

# Train it on the entire training data set
classifier.fit(X_train, y_train)

# Get predictions on the test set
y_pred = classifier.predict(X_test)
</code>```

At this point, you can use any metric from the sklearn.metrics module to determine how well you did. For example:

```<code>from sklearn.metrics import accuracy_score
print(accuracy_score(y_test, y_pred))
</code>```

Body:
I'm relatively new to machine learning and would like some help in the following:

I ran a Support Vector Machine Classifier (SVC) on my data with 10-fold cross validation and calculated the accuracy score (which was around 89%). I'm using Python and scikit-learn to perform the task. Here's a code snippet:

def get_scores(features,target,classifier):
  X_train, X_test, y_train, y_test =train_test_split(features, target ,
    test_size=0.3)
    scores = cross_val_score(
    classifier,
    X_train,
    y_train,
    cv=10,
    scoring='accuracy',
    n_jobs=-1)
 return(scores)

get_scores(features_from_df,target_from_df,svm.SVC())

Now, how can I use my classifier (after running the 10-folds cv) to test it on X_test and compare the predicted results to y_test? As you may have noticed, I only used X_train and y_train in the cross validation process.

I noticed that sklearn have cross_val_predict:
http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.cross_val_predict.html should I replace my cross_val_score by cross_val_predict? just FYI: my target data column is binarized (have values of 0s and 1s).

If my approach is wrong, please advise me with the best way to proceed with.

Thanks!

Body:
You're almost there:

# Build your classifier
classifier = svm.SVC()

# Train it on the entire training data set
classifier.fit(X_train, y_train)

# Get predictions on the test set
y_pred = classifier.predict(X_test)

At this point, you can use any metric from the sklearn.metrics module to determine how well you did. For example:

from sklearn.metrics import accuracy_score
print(accuracy_score(y_test, y_pred))


问:
DocumentBuilder.newDocument() is returning null
Here is something I wouldn't have anticipated, and the documentation doesn't say whether this is even possible, but after calling DocumentBuilder's newDocument() method, it is returning null :

```<code>    // Initialize the DocumentBuilderFactory and DocumentBuilder factories.
    try {
        m_docFactory = DocumentBuilderFactory.newInstance();
        m_Log.error("m_docFactory is {}", m_docFactory);
        m_docBuilder = m_docFactory.newDocumentBuilder();
        m_Log.error("m_docBuilder is {}", m_docBuilder);
        m_doc = m_docBuilder.newDocument();
        m_Log.error("m_doc is {}", m_doc);
        m_xpath = XPathFactory.newInstance().newXPath();
        m_QCodeParameters = new QCodeParameters();
    }
    catch (DOMException e) {
        m_Log.error(e.toString());
    }
    catch (ParserConfigurationException e) {
        m_Log.error(e.toString());
    }
</code>```

The output I am getting is

```<code>m_docFactory is org.apache.xerces.jaxp.DocumentBuilderFactoryImpl@f20d394c
m_docBuilder is org.apache.xerces.jaxp.DocumentBuilderImpl@a7ce296c
m_doc is [#document: null]
</code>```

Am I missing a jar?  Weird!

答:
It's not returning null, otherwise it would've printed m_doc is null. But, the toString method of the Document that you just built is being called and is the following one in class org.apache.xerces.dom.NodeImpl:

```<code>/** NON-DOM method for debugging convenience. */
public String toString() {
    return "["+getNodeName()+": "+getNodeValue()+"]";
}
</code>```

getNodeValue() is returning null

If you check the method in NodeImpl:

```<code>/**
 * Returns the node value.
 * @throws DOMException(DOMSTRING_SIZE_ERR)
 */
public String getNodeValue()
    throws DOMException {
    return null;            // overridden in some subclasses
}
</code>```

Try to access some attribute of m_doc and happy coding!

Cheers!

Body:
Here is something I wouldn't have anticipated, and the documentation doesn't say whether this is even possible, but after calling DocumentBuilder's newDocument() method, it is returning null :

    // Initialize the DocumentBuilderFactory and DocumentBuilder factories.
    try {
        m_docFactory = DocumentBuilderFactory.newInstance();
        m_Log.error("m_docFactory is {}", m_docFactory);
        m_docBuilder = m_docFactory.newDocumentBuilder();
        m_Log.error("m_docBuilder is {}", m_docBuilder);
        m_doc = m_docBuilder.newDocument();
        m_Log.error("m_doc is {}", m_doc);
        m_xpath = XPathFactory.newInstance().newXPath();
        m_QCodeParameters = new QCodeParameters();
    }
    catch (DOMException e) {
        m_Log.error(e.toString());
    }
    catch (ParserConfigurationException e) {
        m_Log.error(e.toString());
    }

The output I am getting is

m_docFactory is org.apache.xerces.jaxp.DocumentBuilderFactoryImpl@f20d394c
m_docBuilder is org.apache.xerces.jaxp.DocumentBuilderImpl@a7ce296c
m_doc is [#document: null]

Am I missing a jar?  Weird!

Body:
It's not returning null, otherwise it would've printed m_doc is null. But, the toString method of the Document that you just built is being called and is the following one in class org.apache.xerces.dom.NodeImpl:

/** NON-DOM method for debugging convenience. */
public String toString() {
    return "["+getNodeName()+": "+getNodeValue()+"]";
}

getNodeValue() is returning null

If you check the method in NodeImpl:

/**
 * Returns the node value.
 * @throws DOMException(DOMSTRING_SIZE_ERR)
 */
public String getNodeValue()
    throws DOMException {
    return null;            // overridden in some subclasses
}

Try to access some attribute of m_doc and happy coding!

Cheers!


问:
Is there a good block cipher that supports small block sizes?

Possible Duplicate:

  Which “good” block encryption algorithm has the shortest output?

I am looking for a block cipher that supports small block sizes,  ideally 16bits in size.  I want to use CMAC mode,  so using a block cipher with OFB mode or a stream cipher is undesirable.  Speed is very important,  and the cipher shouldn't be susceptible to known attacks.  This is a theoretical application and high security isn't required,  however speed is very important.

Does something like this exist?  How close to these specs can I get?

答: Skipjack has a 64bit block size and is a NIST Approved Block Cipher.</p>


问:
How to plot a series of stacked histograms in R and ggplot 2?
I have several likert-type survey questions around attitudes on foreign policy including Syria (syria_threat), North Korea (nk_threat), and Brexit (brexit). Each response is coded as a factor: "No Threat", "Slight Threat", "Medium Threat", "High Threat", and "Grave Threat." A minimal data example is given below

```<code>#Reading the data#
syria_threat<-c("High Threat", "Slight Threat", "Slight Threat", "Medium Threat")
nk_threat<-c("Grave Threat", "Grave Threat", "High Threat", "Medium Threat")

brexit<-c("Medium Threat", "Slight Threat", "Slight Threat", "No Threat")

data<-cbind.data.frame(syria_threat, nk_threat, brexit)

#Showing the structure of the data
 data
   syria_threat     nk_threat        brexit
1   High Threat  Grave Threat Medium Threat
2 Slight Threat  Grave Threat Slight Threat
3 Slight Threat   High Threat Slight Threat
4 Medium Threat Medium Threat     No Threat
</code>```

I would like to create a stack of histogram density plots that visualizes the perceived threat for each threat/crisis. So for each question (Syria, North Korea, and Brexit) I would have a histogram from No Threat to Grave stacked one on top of the other. Not all of the questions have all the same values (i.e., nobody saw Brexit as a "Grave Threat"). I would like it to look something like the answer to this question Multiple histograms in ggplot2 (but with the histogram bars rotated 90 degrees https://i.stack.imgur.com/3CPOS.png).

I am using the following code:

```<code> ggplot(melt(data), aes(x=as.factor(value), fill=as.factor(value))) +
 geom_bar() + xlab("") +
 scale_fill_discrete("Threat")
</code>```

And am getting the following error message:

```<code>Using syria_threat, nk_threat, brexit as id variables
Error in is.factor(x) : object 'value' not found
</code>```

Any help would be appreciated. Thanks!

答:
So for each question (Syria, North Korea, and Brexit) I would have a histogram from No Threat to Grave stacked one on top of the other.

Based on that, I think you want the following:

```<code>library(tidyverse)

# Converting factors to characters
data[] <- lapply(data, as.character)

data %>%
  gather(key, value) %>%
  group_by(key, value) %>%
  mutate(count = n()) %>%
  distinct() %>%
  ggplot(aes(value, count, fill = value)) +
  geom_col(position = position_dodge()) +
  facet_wrap(~ key, ncol = 1) +
  coord_flip() +
  scale_x_discrete(limits = c("No Threat",
                              "Slight Threat",
                              "Medium Threat",
                              "High Threat",
                              "Grave Threat")) +
  theme_bw() +
  theme(
    text = element_text(family = "Source Code Pro"),
    panel.grid.minor = element_blank(),
    panel.grid.major.y = element_blank()
    )
</code>```

Note: I'm using tidyr instead of reshape2 since tidyr is meant to replace reshape2. Also, ignore/modify the theme components if you don't want them (for example, you might not have the Source Code Pro font installed).

Body:
I have several likert-type survey questions around attitudes on foreign policy including Syria (syria_threat), North Korea (nk_threat), and Brexit (brexit). Each response is coded as a factor: "No Threat", "Slight Threat", "Medium Threat", "High Threat", and "Grave Threat." A minimal data example is given below

#Reading the data#
syria_threat<-c("High Threat", "Slight Threat", "Slight Threat", "Medium Threat")
nk_threat<-c("Grave Threat", "Grave Threat", "High Threat", "Medium Threat")

brexit<-c("Medium Threat", "Slight Threat", "Slight Threat", "No Threat")

data<-cbind.data.frame(syria_threat, nk_threat, brexit)

#Showing the structure of the data
 data
   syria_threat     nk_threat        brexit
1   High Threat  Grave Threat Medium Threat
2 Slight Threat  Grave Threat Slight Threat
3 Slight Threat   High Threat Slight Threat
4 Medium Threat Medium Threat     No Threat

I would like to create a stack of histogram density plots that visualizes the perceived threat for each threat/crisis. So for each question (Syria, North Korea, and Brexit) I would have a histogram from No Threat to Grave stacked one on top of the other. Not all of the questions have all the same values (i.e., nobody saw Brexit as a "Grave Threat"). I would like it to look something like the answer to this question Multiple histograms in ggplot2 (but with the histogram bars rotated 90 degrees https://i.stack.imgur.com/3CPOS.png).

I am using the following code:

 ggplot(melt(data), aes(x=as.factor(value), fill=as.factor(value))) +
 geom_bar() + xlab("") +
 scale_fill_discrete("Threat")

And am getting the following error message:

Using syria_threat, nk_threat, brexit as id variables
Error in is.factor(x) : object 'value' not found

Any help would be appreciated. Thanks!

Body:
So for each question (Syria, North Korea, and Brexit) I would have a histogram from No Threat to Grave stacked one on top of the other.

Based on that, I think you want the following:

library(tidyverse)

# Converting factors to characters
data[] <- lapply(data, as.character)

data %>%
  gather(key, value) %>%
  group_by(key, value) %>%
  mutate(count = n()) %>%
  distinct() %>%
  ggplot(aes(value, count, fill = value)) +
  geom_col(position = position_dodge()) +
  facet_wrap(~ key, ncol = 1) +
  coord_flip() +
  scale_x_discrete(limits = c("No Threat",
                              "Slight Threat",
                              "Medium Threat",
                              "High Threat",
                              "Grave Threat")) +
  theme_bw() +
  theme(
    text = element_text(family = "Source Code Pro"),
    panel.grid.minor = element_blank(),
    panel.grid.major.y = element_blank()
    )

Note: I'm using tidyr instead of reshape2 since tidyr is meant to replace reshape2. Also, ignore/modify the theme components if you don't want them (for example, you might not have the Source Code Pro font installed).


问:
Replicate Wireshark Capture of 802.11 QoS Packet in Scapy
I have captured some WLAN 802.11 QoS packets using Wireshark and I am trying to replicate same packets using Scapy

Here goes the screenshot of the captured packet. Please let me know if more screenshots will help.

Here is the scapy commands I used to generate a packet with 4 bytes of dummy data.

```<code>dot11=Dot11(type=2, subtype=8, addr1='11:11:11:11:11:11', addr2='22:22:22:22:22:22', addr3='33:33:33:33:33:33')
frame = RadioTap()/dot11/Dot11QoS()/"abcd"
</code>```

If I use Wireshark to look into the packet using wireshark(frame) command, it identifies the packet as 802.11 QoS packet. But just above the Data field, it shows a Logical Link Control field.

On the other hand, if I send the packet on the interface using sendp(frame, iface='wlan0'), wireshark will capture the packet as LLC packet. My question is why same packet is shown differently in two different case?

Also my idea is to replicate exactly same packet to send it to an IoT device and get the response. Is it possible to forge packets for that? If it is possible, what am I missing to generate same packet using scapy?

答:
To replicate packets, the easiest way would be to directly sniff them on Scapy. The sniff function does just that: it have two main parameters, filter and prn.

filter specifies which packets to capture according to the BPF syntax.

prn specifies which function to apply to the filtered packets.

For example:

```<code>def f(pkt):
    pkt.show()
filt="src host 1.2.3.4"
sniff(prn=f,filter=filt)
</code>```

This code will capture all packets coming from the machine having the IP address 1.2.3.4 and will show their fields.

But if you absolutely want to do the sniffing via Wireshark, you can check that you replicate all the fields thanks to the scapy ls function that displays all the field names of a layer constructor:

```<code>>>> ls(ARP)
sport
dport
len
chksum
</code>```

Good luck in whatever you're trying to do

Body:
I have captured some WLAN 802.11 QoS packets using Wireshark and I am trying to replicate same packets using Scapy

Here goes the screenshot of the captured packet. Please let me know if more screenshots will help.

Here is the scapy commands I used to generate a packet with 4 bytes of dummy data.

dot11=Dot11(type=2, subtype=8, addr1='11:11:11:11:11:11', addr2='22:22:22:22:22:22', addr3='33:33:33:33:33:33')
frame = RadioTap()/dot11/Dot11QoS()/"abcd"

If I use Wireshark to look into the packet using wireshark(frame) command, it identifies the packet as 802.11 QoS packet. But just above the Data field, it shows a Logical Link Control field.

On the other hand, if I send the packet on the interface using sendp(frame, iface='wlan0'), wireshark will capture the packet as LLC packet. My question is why same packet is shown differently in two different case?

Also my idea is to replicate exactly same packet to send it to an IoT device and get the response. Is it possible to forge packets for that? If it is possible, what am I missing to generate same packet using scapy?

Body:
To replicate packets, the easiest way would be to directly sniff them on Scapy. The sniff function does just that: it have two main parameters, filter and prn.

filter specifies which packets to capture according to the BPF syntax.

prn specifies which function to apply to the filtered packets.

For example:

def f(pkt):
    pkt.show()
filt="src host 1.2.3.4"
sniff(prn=f,filter=filt)

This code will capture all packets coming from the machine having the IP address 1.2.3.4 and will show their fields.

But if you absolutely want to do the sniffing via Wireshark, you can check that you replicate all the fields thanks to the scapy ls function that displays all the field names of a layer constructor:

>>> ls(ARP)
sport
dport
len
chksum

Good luck in whatever you're trying to do


问:
UICollectionView, full width cells, allow autolayout dynamic height?
Note For 2021!  See @Ely answer regarding UICollectionLayoutListConfiguration !!!!

In a vertical UICollectionView ,

Is it possible to have full-width cells, but, allow the dynamic height to be controlled by autolayout?

This strikes me as perhaps the "most important question in iOS with no really good answer."

Important:

Note that in 99% of cases, to achieve full width cells + autolayout dynamic height, simply use a table view. It's that easy.

So what's an example of where you need a collection view?

Collection views are far more powerful than table views.

One straightforward example where you must use a collection view with autolayout dynamic height:

If you animate between two layouts in a collection view. For example, between a 1 and 2 column layout, when the device rotates.

That's a common idiom in iOS. Unfortunately it can only be achieved by solving the problem posed in this QA.  :-/

答:
None of the solutions were working for me as I need dynamic width to adapt between iPhones width.</p>

```<code>    class CustomLayoutFlow: UICollectionViewFlowLayout {
        override init() {
            super.init()
            minimumInteritemSpacing = 1 ; minimumLineSpacing = 1 ; scrollDirection = .horizontal
        }

        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            minimumInteritemSpacing = 1 ; minimumLineSpacing = 1 ; scrollDirection = .horizontal
        }

        override var itemSize: CGSize {
            set { }
            get {
                let width = (self.collectionView?.frame.width)!
                let height = (self.collectionView?.frame.height)!
                return CGSize(width: width, height: height)
            }
        }
    }

    class TextCollectionViewCell: UICollectionViewCell {
        @IBOutlet weak var textView: UITextView!

        override func prepareForReuse() {
            super.prepareForReuse()
        }
    }

    class IntroViewController: UIViewController, UITextViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate, UINavigationControllerDelegate {
        @IBOutlet weak var collectionViewTopDistanceConstraint: NSLayoutConstraint!
        @IBOutlet weak var collectionViewTopDistanceConstraint: NSLayoutConstraint!
        @IBOutlet weak var collectionView: UICollectionView!
        var collectionViewLayout: CustomLayoutFlow!

        override func viewDidLoad() {
            super.viewDidLoad()

            self.collectionViewLayout = CustomLayoutFlow()
            self.collectionView.collectionViewLayout = self.collectionViewLayout
        }

        override func viewWillLayoutSubviews() {
            self.collectionViewTopDistanceConstraint.constant = UIScreen.main.bounds.height > 736 ? 94 : 70

            self.view.layoutIfNeeded()
        }
    }
</code>```

Body:
None of the solutions were working for me as I need dynamic width to adapt between iPhones width.

    class CustomLayoutFlow: UICollectionViewFlowLayout {
        override init() {
            super.init()
            minimumInteritemSpacing = 1 ; minimumLineSpacing = 1 ; scrollDirection = .horizontal
        }

        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            minimumInteritemSpacing = 1 ; minimumLineSpacing = 1 ; scrollDirection = .horizontal
        }

        override var itemSize: CGSize {
            set { }
            get {
                let width = (self.collectionView?.frame.width)!
                let height = (self.collectionView?.frame.height)!
                return CGSize(width: width, height: height)
            }
        }
    }

    class TextCollectionViewCell: UICollectionViewCell {
        @IBOutlet weak var textView: UITextView!

        override func prepareForReuse() {
            super.prepareForReuse()
        }
    }

    class IntroViewController: UIViewController, UITextViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate, UINavigationControllerDelegate {
        @IBOutlet weak var collectionViewTopDistanceConstraint: NSLayoutConstraint!
        @IBOutlet weak var collectionViewTopDistanceConstraint: NSLayoutConstraint!
        @IBOutlet weak var collectionView: UICollectionView!
        var collectionViewLayout: CustomLayoutFlow!

        override func viewDidLoad() {
            super.viewDidLoad()

            self.collectionViewLayout = CustomLayoutFlow()
            self.collectionView.collectionViewLayout = self.collectionViewLayout
        }

        override func viewWillLayoutSubviews() {
            self.collectionViewTopDistanceConstraint.constant = UIScreen.main.bounds.height > 736 ? 94 : 70

            self.view.layoutIfNeeded()
        }
    }