问:
Can a sequential always block be triggered by a short pulse from a combi block
Could a sequential always block be triggered by a short lived pulse coming from a combi block ?

I have tried to trigger the always block, by assigning a value and set the value back to 0 in an attempt to trigger the sequential always block but to no avail, below is the pseudo code

```<code>
always_comb begin
 ...some code...
pulse_trigger = 1;
load_var= driver_var // assigning some values
pulse_trigger = 0;
 ...some code...
end

always @(pulse_trigger)begin
 ...some code part 2...
end

</code>```

I expect by assigning 1 to pulse_trigger the "always@(pulse_trigger)" block to get activated, but in my VCS simulation this does not seem to be the case.

Maybe this is because the pulse trigger is assigned 1 and unassigned 1 in the same combi block, which takes 0 simulation time, so pulse_trigger might not appear to have changed values. Or this method should've triggered "always@(pulse_trigger)" and executed "...some code part 2..", because I am looking at the wrong values ?

答:
The result is indeterminate. The SystemVerilog standard is written so that simulators are free to jump between independent processes at any point. But most wait for an event or time control to suspend the process before jumping to another one.

If you want to guarantee a trigger, use a non-blocking assignment in the second assignment to pulse_trigger or use a named event.

```<code>always @* begin
  pulse_trigger = 1;
  load_var= driver_var // assigning some values
  pulse_trigger <= 0; // adds a delta cycle or <= #1 delay without blocking the process
end
</code>```

Even better is replacing the second always @ block with a function declaration, then calling the function instead of triggering an event.

Body:
Could a sequential always block be triggered by a short lived pulse coming from a combi block ?

I have tried to trigger the always block, by assigning a value and set the value back to 0 in an attempt to trigger the sequential always block but to no avail, below is the pseudo code

always_comb begin
 ...some code...
pulse_trigger = 1;
load_var= driver_var // assigning some values
pulse_trigger = 0;
 ...some code...
end

always @(pulse_trigger)begin
 ...some code part 2...
end

I expect by assigning 1 to pulse_trigger the "always@(pulse_trigger)" block to get activated, but in my VCS simulation this does not seem to be the case.

Maybe this is because the pulse trigger is assigned 1 and unassigned 1 in the same combi block, which takes 0 simulation time, so pulse_trigger might not appear to have changed values. Or this method should've triggered "always@(pulse_trigger)" and executed "...some code part 2..", because I am looking at the wrong values ?

Body:
The result is indeterminate. The SystemVerilog standard is written so that simulators are free to jump between independent processes at any point. But most wait for an event or time control to suspend the process before jumping to another one.

If you want to guarantee a trigger, use a non-blocking assignment in the second assignment to pulse_trigger or use a named event.

always @* begin
  pulse_trigger = 1;
  load_var= driver_var // assigning some values
  pulse_trigger <= 0; // adds a delta cycle or <= #1 delay without blocking the process
end

Even better is replacing the second always @ block with a function declaration, then calling the function instead of triggering an event.


来源: stackexchange

问:
PHP Form not creating .csv file
Attempting to have a form filled out and generate a separate .csv file each time its submitted. When the form is filled out the page reloads but does not generate a file currently.

I know there are many other ways to do this but I am very new to this and this way I could kind of wrap my head around better than the others.

<?php

if(isset($_POST["submit"])){

    //collect form data
    $name = $_POST["name"];
    $email = $_POST["email"];
    $customer = $_POST["customer"];
    $reseller = $_POST["reseller"];
    $standardusers = $_POST["standardusers"];
    $ucusers = $_POST["ucusers"];
    $recording = $_POST["recording"];
    $firewall = $_POST["firewall"];

    //check name is set
    if($name ==''){
        $error[] = 'Name is required';
    }

    //check for a valid email address
    if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
         $error[] = 'Please enter a valid email address';
    }

    //check customer name is set
    if($customer ==''){
        $error[] = 'Customer Name is required and must match ConnectWise';
    }

    //check reseller name is set
    if($reseller ==''){
        $error[] = 'Reseller Name is required and must match ConnectWise';
    }

    //check standardusers is set
    if($standardusers ==''){
        $error[] = 'Number of users is required';
    }

    //check ucusers is set
    if($ucusers ==''){
        $error[] = 'Number of users is required';
    }

    //if no errors carry on
    if(!isset($error)){

        //# Title of the CSV
        $Content = "Name, Email, Customer, Reseller, Standard Users, UC Users, Call Recording, Firewall\n";

        //set the data of the CSV
        $Content .= "$name, $email, $customer, $reseller, $standardusers, $ucusers, $recording, $firewall\n";

        //# set the file name and create CSV file
        $filename = "formdata-".date("d-m-y-h:i:s").".csv";
        header('Content-Type: application/csv');
        header('Content-Disposition: attachment; filename="'.$FileName.'";');
        echo $Content;
        echo gethostname();
        exit();
    }
}

?>
```

Once the form is submitted it should drop the .csv file to the server and let the user know the form was submitted successfully.

答:
This is working successfully

```<code><?php
if(isset($_POST["submit"])){

  $data = array();

  $data['name'] = $_POST["name"] ?? '';
  $data['email'] = $_POST["email"] ?? '';
  $data['customer'] = $_POST["customer"] ?? '';
  $data['reseller'] = $_POST["reseller"] ?? '';
  $data['standardusers'] = $_POST["standardusers"] ?? '';
  $data['ucusers'] = $_POST["ucusers"] ?? '';
  $data['recording'] = $_POST["recording"] ?? '';
  $data['firewall'] = $_POST["firewall"] ?? '';

  $errors = '';

  foreach ($data as $key => $value) {
    if ($key == 'recording' || $key == 'firewall'){ } //do nothing
    else {
      if (empty($value)) {
        //Field is empty && email
        if ($key == 'email') {
          if(!filter_var($data['email'], FILTER_VALIDATE_EMAIL)){
            $errors .= 'Please enter a valid email address \r\n ';
          }
        } else {
          //Field is empty && !email
          $errors .= $key.' field is required. \r\n ';
        }
      }
    }
  }

  //if no errors carry on
  if(empty($errors)){
    //# Title of the CSV
    $Content = "Name, Email, Customer, Reseller, Standard Users, UC Users, Call Recording, Firewall\n";
    //set the data of the CSV
    // Added '' in each field as a delimiter
    // $Content .= "'".$data['name']."', '".$data['email']."', '".$data['customer']."', '".$data['reseller']."', '".$data['standardusers']."', '".$data['ucusers']."', '".$data['recording']."', '".$data['firewall']."'\n";
    $row = '';

    foreach ($data as $key => $value){
      $row .= $value.","; //Append data to csv
    }
    //Remove trailing comma
    $row = mb_substr($row, 0, -1);

    $Content .= $row;
    //# set the file name and create CSV file
    // $filename = "formdata-".date("d-m-y-h:i:s").".csv";
    // header('Content-Type: application/csv');
    // header('Content-Disposition: attachment; filename="'.$FileName.'";');
    // echo $Content;
    // echo gethostname();
    // exit();

    $csv_handler = fopen ('csvfile.csv','w');
    if(fwrite ($csv_handler,$Content)){
      echo 'Data saved to csvfile.csv';
    } else {
      echo "File not saved successfully";
    }
    fclose ($csv_handler);

  } else {
    echo $errors;
  }

}

?>
</code>```

I tested using this form, posting to the script

```<code><form class="" action="3.php" method="post">
  <input type="text" name="name" placeholder="name" >
  <input type="text" name="email" placeholder="email" >
  <input type="text" name="customer" placeholder="customer" >
  <input type="text" name="reseller" placeholder="reseller" >
  <input type="text" name="standardusers" placeholder="standardusers" >
  <input type="text" name="ucusers" placeholder="ucusers" >
  <input type="text" name="recording" placeholder="recording" >
  <input type="text" name="firewall" placeholder="firewall" >
  <input type="submit" name="submit" value="submit">
</form>

</code>```

ContentLicense: CC BY-SA 4.0

Title: PHP Form not creating .csv file

Body:
Attempting to have a form filled out and generate a separate .csv file each time its submitted. When the form is filled out the page reloads but does not generate a file currently.

I know there are many other ways to do this but I am very new to this and this way I could kind of wrap my head around better than the others.

<?php

if(isset($_POST["submit"])){

    //collect form data
    $name = $_POST["name"];
    $email = $_POST["email"];
    $customer = $_POST["customer"];
    $reseller = $_POST["reseller"];
    $standardusers = $_POST["standardusers"];
    $ucusers = $_POST["ucusers"];
    $recording = $_POST["recording"];
    $firewall = $_POST["firewall"];

    //check name is set
    if($name ==''){
        $error[] = 'Name is required';
    }

    //check for a valid email address
    if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
         $error[] = 'Please enter a valid email address';
    }

    //check customer name is set
    if($customer ==''){
        $error[] = 'Customer Name is required and must match ConnectWise';
    }

    //check reseller name is set
    if($reseller ==''){
        $error[] = 'Reseller Name is required and must match ConnectWise';
    }

    //check standardusers is set
    if($standardusers ==''){
        $error[] = 'Number of users is required';
    }

    //check ucusers is set
    if($ucusers ==''){
        $error[] = 'Number of users is required';
    }

    //if no errors carry on
    if(!isset($error)){

        //# Title of the CSV
        $Content = "Name, Email, Customer, Reseller, Standard Users, UC Users, Call Recording, Firewall\n";

        //set the data of the CSV
        $Content .= "$name, $email, $customer, $reseller, $standardusers, $ucusers, $recording, $firewall\n";

        //# set the file name and create CSV file
        $filename = "formdata-".date("d-m-y-h:i:s").".csv";
        header('Content-Type: application/csv');
        header('Content-Disposition: attachment; filename="'.$FileName.'";');
        echo $Content;
        echo gethostname();
        exit();
    }
}

?>

Once the form is submitted it should drop the .csv file to the server and let the user know the form was submitted successfully.

Body:
This is working successfully

<?php
if(isset($_POST["submit"])){

  $data = array();

  $data['name'] = $_POST["name"] ?? '';
  $data['email'] = $_POST["email"] ?? '';
  $data['customer'] = $_POST["customer"] ?? '';
  $data['reseller'] = $_POST["reseller"] ?? '';
  $data['standardusers'] = $_POST["standardusers"] ?? '';
  $data['ucusers'] = $_POST["ucusers"] ?? '';
  $data['recording'] = $_POST["recording"] ?? '';
  $data['firewall'] = $_POST["firewall"] ?? '';

  $errors = '';

  foreach ($data as $key => $value) {
    if ($key == 'recording' || $key == 'firewall'){ } //do nothing
    else {
      if (empty($value)) {
        //Field is empty && email
        if ($key == 'email') {
          if(!filter_var($data['email'], FILTER_VALIDATE_EMAIL)){
            $errors .= 'Please enter a valid email address \r\n ';
          }
        } else {
          //Field is empty && !email
          $errors .= $key.' field is required. \r\n ';
        }
      }
    }
  }

  //if no errors carry on
  if(empty($errors)){
    //# Title of the CSV
    $Content = "Name, Email, Customer, Reseller, Standard Users, UC Users, Call Recording, Firewall\n";
    //set the data of the CSV
    // Added '' in each field as a delimiter
    // $Content .= "'".$data['name']."', '".$data['email']."', '".$data['customer']."', '".$data['reseller']."', '".$data['standardusers']."', '".$data['ucusers']."', '".$data['recording']."', '".$data['firewall']."'\n";
    $row = '';

    foreach ($data as $key => $value){
      $row .= $value.","; //Append data to csv
    }
    //Remove trailing comma
    $row = mb_substr($row, 0, -1);

    $Content .= $row;
    //# set the file name and create CSV file
    // $filename = "formdata-".date("d-m-y-h:i:s").".csv";
    // header('Content-Type: application/csv');
    // header('Content-Disposition: attachment; filename="'.$FileName.'";');
    // echo $Content;
    // echo gethostname();
    // exit();

    $csv_handler = fopen ('csvfile.csv','w');
    if(fwrite ($csv_handler,$Content)){
      echo 'Data saved to csvfile.csv';
    } else {
      echo "File not saved successfully";
    }
    fclose ($csv_handler);

  } else {
    echo $errors;
  }

}

?>

I tested using this form, posting to the script

<form class="" action="3.php" method="post">
  <input type="text" name="name" placeholder="name" >
  <input type="text" name="email" placeholder="email" >
  <input type="text" name="customer" placeholder="customer" >
  <input type="text" name="reseller" placeholder="reseller" >
  <input type="text" name="standardusers" placeholder="standardusers" >
  <input type="text" name="ucusers" placeholder="ucusers" >
  <input type="text" name="recording" placeholder="recording" >
  <input type="text" name="firewall" placeholder="firewall" >
  <input type="submit" name="submit" value="submit">
</form>


问:
Extract a Value from the DOM
Q1) How do I get to '1' in the XML/HTML using the FindElement/By class?

```<code><h3 class="lemon--h3__373c0__sQmiG heading--h3__373c0__1n4Of alternate__373c0__1uacp">1<!-- -->. <a class="lemon--a__373c0__IEZFH link__373c0__29943 link-color--blue-dark__373c0__1mhJo link-size--inherit__373c0__2JXk5" href="/biz/teds-montana-grill-larimer-square-denver?osq=Teds+Montana+Grill" target="" name="Ted’s Montana Grill - Larimer Square" rel="">Ted’s Montana Grill - Larimer Square</a></h3>
</code>```

Q2) How can I get Ted's Montana Grill and Aurora from the xml below?
I managed to get Ted’s Montana Grill. However, Aurora is proving to be challenge.

Here is the URL - https://www.yelp.com/biz/teds-montana-grill-aurora-aurora?osq=Teds+Montana+Grill

```<code><h1 class="biz-page-title embossed-text-white">Ted’s Montana Grill -</h1>
<div class="u-inline-block">
            <h1 class="biz-page-title embossed-text-white">Aurora</h1>
            <div class="u-inline-block">
</code>```

Trying with FindElement/By

答:
Q1:

```<code>document.getElementsByClassName("lemon--h3__373c0__sQmiG heading--h3__373c0__1n4Of alternate__373c0__1uacp");
</code>```

Q2:

```<code>let items = document.getElementsByClassName("biz-page-title embossed-text-white");
for (let i = 0; i < items.length; i++) {
    console.log(items[i].outerText);
}
</code>```

Title: Extract a Value from the DOM

Body:
Q1) How do I get to '1' in the XML/HTML using the FindElement/By class?

1. Ted’s Montana Grill - Larimer Square

Q2) How can I get Ted's Montana Grill and Aurora from the xml below?
I managed to get Ted’s Montana Grill. However, Aurora is proving to be challenge.

Here is the URL - https://www.yelp.com/biz/teds-montana-grill-aurora-aurora?osq=Teds+Montana+Grill

Ted’s Montana Grill -

Aurora

Trying with FindElement/By

Body:
Q1:

document.getElementsByClassName("lemon--h3__373c0__sQmiG heading--h3__373c0__1n4Of alternate__373c0__1uacp");

Q2:

let items = document.getElementsByClassName("biz-page-title embossed-text-white");
for (let i = 0; i < items.length; i++) {
    console.log(items[i].outerText);
}


问:
How to render a self-destructing paragraph at mouse position in React?
I am trying to get a paragraph to appear at the location of the mouse coordinates, but self-destruct after 1 second.

```<code>$(function(){
var fadeDelay = 1000;
var fadeDuration = 1000;
$(document).click(function(e){
    var div = $('<div class="image-wrapper">')
        .css({
            "left": e.pageX + 'px',
            "top": e.pageY + 'px'
        })
        .append($('<img src="" alt="myimage" />'))
        .appendTo(document.body);

    setTimeout(function() {
        div.addClass('fade-out');
        setTimeout(function() { div.remove(); }, fadeDuration);
    }, fadeDelay);
});
});
</code>```

The code above is from a fiddle which represents the effect that I am looking for; however, it uses jQuery - while I am working with React.

I tried following this linear process:

1 - In the state, toggle a boolean with mouse clicks

```<code>  playerAttack = () => {
    this.setState({ hasPlayerAttacked: true })
}
</code>```

2 - In a function, when the boolean is true, return a paragraph and set the boolean back to false

```<code>renderDamageDealtParagraph = () => {
  if (this.state.hasPlayerAttacked) {
    return <p>{this.state.playerAttack}</p>;
    this.setState({ hasPlayerAttacked: false });
  }
};
</code>```

However, with this approach there were too many fallacies; main one being that upon resetting the boolean back to false, the rendered paragraph immediately disappears (instead of after a timeout of 1000ms).

What is the best wait to implement something like the linked fiddle, in ReactJS using vanilla JS?

Thanks in advance to whoever might be able to help.

答:
You can basically do something like this:

Have state to track the mouse position x and y, and two booleans isShown and shouldHide to coordinate the disappering div

On click, show the div by setting isShown to true and immediately setTimeout to start hiding it in the future by adding a class by flipping the shouldHide to true

Once the class is added, the element will fade and will trigger the transitionend event at which point you can remove the div entirely by flipping the isShown to false and shouldHide to false boolean

Sample Implementation (Sorry for the shitty code, been a while since I React-ed)

JS Fiddle

```<code>class SelfDestructDemo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      x: 0,
      y: 0,
      isShown: false,
      shouldHide: false
    };
    this.handleClick = this.handleClick.bind(this);
    this.reset = this.reset.bind(this);
  }
  reset() {
    this.setState({
      x: 0,
      y: 0,
      isShown: false,
      shouldHide: false
    });
  }
  handleClick(event) {
    if (this.state.isShown) {
      return;
    }
    const { clientX, clientY } = event;
    this.setState({
      x: clientX,
      y: clientY,
      isShown: true,
      shouldHide: false
    });

    setTimeout(() => {
      this.setState({ shouldHide: true });
    }, 1000);
  }
  render() {
    const p = this.state.isShown && (
      <div
        onTransitionEnd={this.reset}
        className={`${this.state.shouldHide ? "should-hide" : ""} modal`}
        style={{ top: this.state.y, left: this.state.x }}
      >
        Self destructing....
      </div>
    );

    return (
      <div className="container" onClick={this.handleClick}>
        {p}
      </div>
    );
  }
}

ReactDOM.render(<SelfDestructDemo />, document.querySelector("#app"));
</code>```

Body:
I am trying to get a paragraph to appear at the location of the mouse coordinates, but self-destruct after 1 second.

$(function(){
var fadeDelay = 1000;
var fadeDuration = 1000;
$(document).click(function(e){
    var div = $('
')
        .css({
            "left": e.pageX + 'px',
            "top": e.pageY + 'px'
        })
        .append($(''))
        .appendTo(document.body);

    setTimeout(function() {
        div.addClass('fade-out');
        setTimeout(function() { div.remove(); }, fadeDuration);
    }, fadeDelay);
});
});

The code above is from a fiddle which represents the effect that I am looking for; however, it uses jQuery - while I am working with React.

I tried following this linear process:

1 - In the state, toggle a boolean with mouse clicks

  playerAttack = () => {
    this.setState({ hasPlayerAttacked: true })
}

2 - In a function, when the boolean is true, return a paragraph and set the boolean back to false

renderDamageDealtParagraph = () => {
  if (this.state.hasPlayerAttacked) {
    return
{this.state.playerAttack}
;
    this.setState({ hasPlayerAttacked: false });
  }
};

However, with this approach there were too many fallacies; main one being that upon resetting the boolean back to false, the rendered paragraph immediately disappears (instead of after a timeout of 1000ms).

What is the best wait to implement something like the linked fiddle, in ReactJS using vanilla JS?

Thanks in advance to whoever might be able to help.

Body:
You can basically do something like this:

Have state to track the mouse position x and y, and two booleans isShown and shouldHide to coordinate the disappering div

On click, show the div by setting isShown to true and immediately setTimeout to start hiding it in the future by adding a class by flipping the shouldHide to true

Once the class is added, the element will fade and will trigger the transitionend event at which point you can remove the div entirely by flipping the isShown to false and shouldHide to false boolean

Sample Implementation (Sorry for the shitty code, been a while since I React-ed)

JS Fiddle

class SelfDestructDemo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      x: 0,
      y: 0,
      isShown: false,
      shouldHide: false
    };
    this.handleClick = this.handleClick.bind(this);
    this.reset = this.reset.bind(this);
  }
  reset() {
    this.setState({
      x: 0,
      y: 0,
      isShown: false,
      shouldHide: false
    });
  }
  handleClick(event) {
    if (this.state.isShown) {
      return;
    }
    const { clientX, clientY } = event;
    this.setState({
      x: clientX,
      y: clientY,
      isShown: true,
      shouldHide: false
    });

    setTimeout(() => {
      this.setState({ shouldHide: true });
    }, 1000);
  }
  render() {
    const p = this.state.isShown && (
      <div
        onTransitionEnd={this.reset}
        className={`${this.state.shouldHide ? "should-hide" : ""} modal`}
        style={{ top: this.state.y, left: this.state.x }}
      >
        Self destructing....
      </div>
    );

    return (
      <div className="container" onClick={this.handleClick}>
        {p}
      </div>
    );
  }
}

ReactDOM.render(<SelfDestructDemo />, document.querySelector("#app"));


答:
2) They both have the same class so you can just iterate over all the nodes returned by getElementsByClassName.  All you need to do is access the textContent property.

```<code>const titles = document.getElementsByClassName("biz-page-title");
Array.prototype.forEach.call(titles, function(el) {
    console.log(el.textContent);
})
</code>```

1) Same thing for your first question: const value = document.getElementsByClassName("lemon--h3__373c0__sQmiG heading--h3__373c0__1n4Of alternate__373c0__1uacp")[0].textContent;

Title: Extract a Value from the DOM

Body:
2) They both have the same class so you can just iterate over all the nodes returned by getElementsByClassName.  All you need to do is access the textContent property.

const titles = document.getElementsByClassName("biz-page-title");
Array.prototype.forEach.call(titles, function(el) {
    console.log(el.textContent);
})

1) Same thing for your first question: const value = document.getElementsByClassName("lemon--h3__373c0__sQmiG heading--h3__373c0__1n4Of alternate__373c0__1uacp")[0].textContent;


问:
ERROR: more than one row returned by a subquery used as an expression. POSTGRESQL / LOOKER
I am trying to do a subquery in Looker that returns the assignee name from the person table where the person ID equals the assignedtoperson ID

I have tried to do a limit 1, but that just returns the first value for person in every row

```<code>SELECT
    "ID",

    (SELECT
        p."NAME"
    FROM
        view_321782990.person AS p, view_321782990.request AS r
    WHERE
        p."ID" = r."ASSIGNEDTOPERSON")
FROM view_321782990.request
</code>```

I wanti it to return the Name of who was assigned to the ticket, doing

```<code>SELECT
        p."NAME", r."ID"
    FROM
        view_321782990.person AS p, view_321782990.request AS r
    WHERE
        p."ID" = r."ASSIGNEDTOPERSON"
</code>```

returns what I want, however, I need to do the subquery this way because of how looker interprets SQL

答:
Use a join:</p>

```<code>SELECT
  p.name
  , r.id
FROM view_321782990.person p
LEFT JOIN view_321782990.request r ON
  p.id = r.assignedtoperson
</code>```

Body:
I am trying to do a subquery in Looker that returns the assignee name from the person table where the person ID equals the assignedtoperson ID

I have tried to do a limit 1, but that just returns the first value for person in every row

SELECT
    "ID",

    (SELECT
        p."NAME"
    FROM
        view_321782990.person AS p, view_321782990.request AS r
    WHERE
        p."ID" = r."ASSIGNEDTOPERSON")
FROM view_321782990.request

I wanti it to return the Name of who was assigned to the ticket, doing

SELECT
        p."NAME", r."ID"
    FROM
        view_321782990.person AS p, view_321782990.request AS r
    WHERE
        p."ID" = r."ASSIGNEDTOPERSON"

returns what I want, however, I need to do the subquery this way because of how looker interprets SQL

Body:
Use a join:

SELECT
  p.name
  , r.id
FROM view_321782990.person p
LEFT JOIN view_321782990.request r ON
  p.id = r.assignedtoperson


问:
Why I cannot see line numbers in gdb backtrace?
I cannot see line numbers in gdb. I have compiled everything with -g flags with mpiicc.

gdb is not showing line numbers even for breakpoints for me.

May be the problem is in "Missing separate debuginfos, use: debuginfo-install glibc-2.12-1.166.el6_7.7.x86_64 numactl-2.0.9-2.el6.x86_64" but I am not a superuser so I cannot install these.

```<code> gdb  --args ./central -g 5 51
GNU gdb (GDB) Red Hat Enterprise Linux (7.2-83.el6)
Copyright (C) 2010 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-redhat-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /home/dslavchev/NuclearTesting/MPI/project-a-test-mpi/central...done.
(gdb) break direct.c:55
Breakpoint 1 at 0x40855d: file direct.c, line 55.
(gdb) l direct.c:55
50
51  void direct(int* N, double **PA, Coord **points)
52  {
53      int     i ,j ,k ,l, ir, irr,
54              md = suma(N , NUM_AIRFOILS) - NUM_AIRFOILS,
55              m;
56      double  *D, // **D,
57              *A, *sv;
58
59      int matrix_size_D = md*md;
(gdb) r
Starting program: /home/dslavchev/NuclearTesting/MPI/project-a-test-mpi/central -g 5 51
[Thread debugging using libthread_db enabled]

Breakpoint 1, 0x000000000040855d in direct ()
Missing separate debuginfos, use: debuginfo-install glibc-2.12-1.166.el6_7.7.x86_64 numactl-2.0.9-2.el6.x86_64
(gdb) bt
#0  0x000000000040855d in direct ()
#1  0x0000000000405ee9 in main ()
(gdb) s
Single stepping until exit from function direct,
which has no line number information.
PMPI_Comm_size (comm=1140850688, size=0x7fffffffc240) at ../../src/mpi/comm/comm_size.c:57
57  ../../src/mpi/comm/comm_size.c: No such file or directory.
    in ../../src/mpi/comm/comm_size.c
(gdb) s
65  in ../../src/mpi/comm/comm_size.c
(gdb) s
57  in ../../src/mpi/comm/comm_size.c
(gdb)
58  in ../../src/mpi/comm/comm_size.c
(gdb)
59  in ../../src/mpi/comm/comm_size.c
(gdb)
65  in ../../src/mpi/comm/comm_size.c
(gdb)
</code>```

Here is the build commands as well:

```<code>mpiicc -g -c -o central.o central.c -qopenmp
mpiicc -g -c -o contours.o contours.c -qopenmp
mpiicc -g -c -o mymath.o mymath.c -qopenmp
mpiicc -g -c -o vort.o vort.c -qopenmp
mpiicc -g -qopenmp   -I/opt/intel/parallel_studio_xe_2017.2.050/compilers_and_libraries_2017/linux/mkl/include -c -o  direct.o direct.c
mpiicc -g -c -o a_liftarg.o a_liftarg.c -qopenmp
mpiicc -g -c -o psavel.o psavel.c -qopenmp
mpiicc -g -c -o euler.o euler.c -qopenmp
mpiicc -g -c -o streamline.o streamline.c -qopenmp
mpiicc -g -c -o speedmap.o speedmap.c -qopenmp
mpiicc -g -o central central.o contours.o mymath.o vort.o direct.o a_liftarg.o psavel.o euler.o streamline.o speedmap.o /opt/intel/parallel_studio_xe_2017.2.050/compilers_and_libraries_2017/linux/mkl/lib/intel64/libmkl_scalapack_lp64.a -Wl,--start-group /opt/intel/parallel_studio_xe_2017.2.050/compilers_and_libraries_2017/linux/mkl/lib/intel64/libmkl_intel_lp64.a /opt/intel/parallel_studio_xe_2017.2.050/compilers_and_libraries_2017/linux/mkl/lib/intel64/libmkl_intel_thread.a /opt/intel/parallel_studio_xe_2017.2.050/compilers_and_libraries_2017/linux/mkl/lib/intel64/libmkl_core.a /opt/intel/parallel_studio_xe_2017.2.050/compilers_and_libraries_2017/linux/mkl/lib/intel64/libmkl_blacs_intelmpi_lp64.a -Wl,--end-group -liomp5 -lpthread -lm -ldl -qopenmp
</code>```

答:
Try to add the flag

-debug expr-source-pos

It should add the line informations

https://software.intel.com/en-us/cpp-compiler-developer-guide-and-reference-debug-linux-and-macos

Body:
I cannot see line numbers in gdb. I have compiled everything with -g flags with mpiicc.

gdb is not showing line numbers even for breakpoints for me.

May be the problem is in "Missing separate debuginfos, use: debuginfo-install glibc-2.12-1.166.el6_7.7.x86_64 numactl-2.0.9-2.el6.x86_64" but I am not a superuser so I cannot install these.

 gdb  --args ./central -g 5 51
GNU gdb (GDB) Red Hat Enterprise Linux (7.2-83.el6)
Copyright (C) 2010 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-redhat-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /home/dslavchev/NuclearTesting/MPI/project-a-test-mpi/central...done.
(gdb) break direct.c:55
Breakpoint 1 at 0x40855d: file direct.c, line 55.
(gdb) l direct.c:55
50
51  void direct(int* N, double **PA, Coord **points)
52  {
53      int     i ,j ,k ,l, ir, irr,
54              md = suma(N , NUM_AIRFOILS) - NUM_AIRFOILS,
55              m;
56      double  *D, // **D,
57              *A, *sv;
58
59      int matrix_size_D = md*md;
(gdb) r
Starting program: /home/dslavchev/NuclearTesting/MPI/project-a-test-mpi/central -g 5 51
[Thread debugging using libthread_db enabled]

Breakpoint 1, 0x000000000040855d in direct ()
Missing separate debuginfos, use: debuginfo-install glibc-2.12-1.166.el6_7.7.x86_64 numactl-2.0.9-2.el6.x86_64
(gdb) bt
#0  0x000000000040855d in direct ()
#1  0x0000000000405ee9 in main ()
(gdb) s
Single stepping until exit from function direct,
which has no line number information.
PMPI_Comm_size (comm=1140850688, size=0x7fffffffc240) at ../../src/mpi/comm/comm_size.c:57
57  ../../src/mpi/comm/comm_size.c: No such file or directory.
    in ../../src/mpi/comm/comm_size.c
(gdb) s
65  in ../../src/mpi/comm/comm_size.c
(gdb) s
57  in ../../src/mpi/comm/comm_size.c
(gdb)
58  in ../../src/mpi/comm/comm_size.c
(gdb)
59  in ../../src/mpi/comm/comm_size.c
(gdb)
65  in ../../src/mpi/comm/comm_size.c
(gdb)

Here is the build commands as well:

mpiicc -g -c -o central.o central.c -qopenmp
mpiicc -g -c -o contours.o contours.c -qopenmp
mpiicc -g -c -o mymath.o mymath.c -qopenmp
mpiicc -g -c -o vort.o vort.c -qopenmp
mpiicc -g -qopenmp   -I/opt/intel/parallel_studio_xe_2017.2.050/compilers_and_libraries_2017/linux/mkl/include -c -o  direct.o direct.c
mpiicc -g -c -o a_liftarg.o a_liftarg.c -qopenmp
mpiicc -g -c -o psavel.o psavel.c -qopenmp
mpiicc -g -c -o euler.o euler.c -qopenmp
mpiicc -g -c -o streamline.o streamline.c -qopenmp
mpiicc -g -c -o speedmap.o speedmap.c -qopenmp
mpiicc -g -o central central.o contours.o mymath.o vort.o direct.o a_liftarg.o psavel.o euler.o streamline.o speedmap.o /opt/intel/parallel_studio_xe_2017.2.050/compilers_and_libraries_2017/linux/mkl/lib/intel64/libmkl_scalapack_lp64.a -Wl,--start-group /opt/intel/parallel_studio_xe_2017.2.050/compilers_and_libraries_2017/linux/mkl/lib/intel64/libmkl_intel_lp64.a /opt/intel/parallel_studio_xe_2017.2.050/compilers_and_libraries_2017/linux/mkl/lib/intel64/libmkl_intel_thread.a /opt/intel/parallel_studio_xe_2017.2.050/compilers_and_libraries_2017/linux/mkl/lib/intel64/libmkl_core.a /opt/intel/parallel_studio_xe_2017.2.050/compilers_and_libraries_2017/linux/mkl/lib/intel64/libmkl_blacs_intelmpi_lp64.a -Wl,--end-group -liomp5 -lpthread -lm -ldl -qopenmp


问:
Using "umlauts" in C++ code

Possible Duplicate:

  C++ source in unicode

I just discovered this line of code in a project:

```<code>string überwachung;
</code>```

I was surprised, because actually I thought you are not allowed to use umlauts like 'äöü' in C++ code other than in strings and so on, and it would result in a compiler error. But this compiles just fine with visual studio 2008.

Is this a special microsoft feature, or are umlauts allowed with other compilers too?

Are there any potential problems with that (portability,system language settings..)?

I can clearly remember this was not allowed. When did it change?

Kind regards for any clarification

P.S.: the tool cppcheck will even mark this usage as an error, even though it compiles

答:
GCC complains on it:
codepad

: error: stray '\303' in program

The C++ language standard itself limits the basic source character set to 91 printable characters plus tabs, form feed and new-line, which are all within ASCII. However, there's a nice footnote:

The glyphs for the members of the basic source character set are intended to identify characters from the subset of
  ISO/IEC 10646 which corresponds to the ASCII character set. However, because the mapping from source file characters to the
  source character set (described in translation phase 1) is specified as implementation-defined, an implementation is required to
  document how the basic source characters are represented in source files.

.. translation phase 1 is (emphasis mine)

Physical source file characters are mapped, in an implementation-defined manner, to the basic source
  character set (introducing new-line characters for end-of-line indicators) if necessary. The set of physical
  source file characters accepted is implementation-defined.

Generally, you shouldn't use umlauts or other special characters in your code. If may work, but if it does, it's a compiler-specific feature.

ContentLicense: CC BY-SA 3.0

Title: Using "umlauts" in C++ code

Body:
Possible Duplicate:

  C++ source in unicode

I just discovered this line of code in a project:

string überwachung;

I was surprised, because actually I thought you are not allowed to use umlauts like 'äöü' in C++ code other than in strings and so on, and it would result in a compiler error. But this compiles just fine with visual studio 2008.

Is this a special microsoft feature, or are umlauts allowed with other compilers too?

Are there any potential problems with that (portability,system language settings..)?

I can clearly remember this was not allowed. When did it change?

Kind regards for any clarification

P.S.: the tool cppcheck will even mark this usage as an error, even though it compiles


问:
R function to identify cases where condition is met x number of times in any of n number of columns?
I have a dataframe where I would like to identify cases (rows) where a given condition is met at least a certain number of times in a set of columns. In the toy example below, I would like to identify cases where "A" is the choice for two of three columns (Choice_1 to Choice_3). I do not care in which two of the three columns "A" is found. In my example, ID = 1 and ID = 4 would be identified.

This should work with any number of "A"s desired in any number of columns (e.g if I wanted to identify cases where "A" is the choice in three of the four Choice columns, only ID = 1 would be identified).

```<code>ID <- 1:4
Choice_1 <- c("A", "B", "C", "D")
Choice_2 <- c("A", "D", "C", "A")
Choice_3 <- c("A", "C", "A", "A")
Choice_4 <- c("B", "B", "A", "B")

df <- data.frame(ID, Choice_1, Choice_2, Choice_3, Choice_4)

> df
ID Choice_1 Choice_2 Choice_3 Choice_4
 1        A        A        A        B
 2        B        D        C        B
 3        C        C        A        A
 4        D        A        A        B
</code>```

One kind of roundabout way to do this would be to convert "A"s to 1 and all else to 0, sum the Choice columns I am interested in and check the sum is equal or higher than my threshold, but I feel like there must be a better way.

The way I imagine it, it would be some form of if_else statement included in a mutate so rows that match the condition would be identified with 1 and those that don't with 0:

```<code>df %>% mutate(cond_matched = if_else( two of (Choice_1, Choice_2, Choice_3) == "A", 1, 0))

ID Choice_1 Choice_2 Choice_3 Choice_4 cond_matched
 1        A        A        A        B            1
 2        B        D        C        B            0
 3        C        C        A        A            0
 4        D        A        A        B            1
</code>```

I'm hoping I've just been searching with the wrong keywords. Thank you for any help!

答:
A base R option wuld be to create logical matrix from selected columns (df[2:4] == "A"), get the row wise sum of TRUE elements and check if it is greater than or equal to 2, coerce the logical vector to binary with as.integer or + (hacky)

```<code>df$cond_matched <- +(rowSums(df[2:4] == "A") >= 2)
df$cond_matched
#[1] 1 0 0 1
</code>```

Or with tidyverse (with a similar logic from base R solution, but not exactly the same syntax)

```<code>library(tidyverse)
df %>%
    mutate(cond_matched = select(., 2:4) %>%
                            map(~ .x == 'A') %>%
                            reduce(`+`) %>%
                            `>=`(2) %>%
                            as.integer)
#   ID Choice_1 Choice_2 Choice_3 Choice_4 cond_matched
#1  1        A        A        A        B            1
#2  2        B        D        C        B            0
#3  3        C        C        A        A            0
#4  4        D        A        A        B            1
</code>```

Body:
I have a dataframe where I would like to identify cases (rows) where a given condition is met at least a certain number of times in a set of columns. In the toy example below, I would like to identify cases where "A" is the choice for two of three columns (Choice_1 to Choice_3). I do not care in which two of the three columns "A" is found. In my example, ID = 1 and ID = 4 would be identified.

This should work with any number of "A"s desired in any number of columns (e.g if I wanted to identify cases where "A" is the choice in three of the four Choice columns, only ID = 1 would be identified).

ID <- 1:4
Choice_1 <- c("A", "B", "C", "D")
Choice_2 <- c("A", "D", "C", "A")
Choice_3 <- c("A", "C", "A", "A")
Choice_4 <- c("B", "B", "A", "B")

df <- data.frame(ID, Choice_1, Choice_2, Choice_3, Choice_4)

> df
ID Choice_1 Choice_2 Choice_3 Choice_4
 1        A        A        A        B
 2        B        D        C        B
 3        C        C        A        A
 4        D        A        A        B

One kind of roundabout way to do this would be to convert "A"s to 1 and all else to 0, sum the Choice columns I am interested in and check the sum is equal or higher than my threshold, but I feel like there must be a better way.

The way I imagine it, it would be some form of if_else statement included in a mutate so rows that match the condition would be identified with 1 and those that don't with 0:

df %>% mutate(cond_matched = if_else( two of (Choice_1, Choice_2, Choice_3) == "A", 1, 0))

ID Choice_1 Choice_2 Choice_3 Choice_4 cond_matched
 1        A        A        A        B            1
 2        B        D        C        B            0
 3        C        C        A        A            0
 4        D        A        A        B            1

I'm hoping I've just been searching with the wrong keywords. Thank you for any help!

Body:
A base R option wuld be to create logical matrix from selected columns (df[2:4] == "A"), get the row wise sum of TRUE elements and check if it is greater than or equal to 2, coerce the logical vector to binary with as.integer or + (hacky)

df$cond_matched <- +(rowSums(df[2:4] == "A") >= 2)
df$cond_matched
#[1] 1 0 0 1

Or with tidyverse (with a similar logic from base R solution, but not exactly the same syntax)

library(tidyverse)
df %>%
    mutate(cond_matched = select(., 2:4) %>%
                            map(~ .x == 'A') %>%
                            reduce(`+`) %>%
                            `>=`(2) %>%
                            as.integer)
#   ID Choice_1 Choice_2 Choice_3 Choice_4 cond_matched
#1  1        A        A        A        B            1
#2  2        B        D        C        B            0
#3  3        C        C        A        A            0
#4  4        D        A        A        B            1


问:
Is there a way to keep Word using VBA on top of UFT while is running?
I need to keep MS WORD on top of the applications, in this case HP UFT for my code to work properly, I don't know why, but this is the only way the macro I created does what it is supposed to.

I created a function that calls the creation of a macro and fills the Word Document with the data sent in the call to the function, but this data is kept only when the Document is being shown, if the document is in the background the data goes away for some reason I don't know yet.

I tried with some properties for the Application like :

```<code>   Application.Visible = True
   Application.ScreenUpdating = True
</code>```

But none of them worked, is this possible to achieve with UFT?

答:
To fix the deletion or removal of the data sent, I had to use the following:

```<code>Application.Activate()
</code>```

So the focus is on the Word File

Body:
I need to keep MS WORD on top of the applications, in this case HP UFT for my code to work properly, I don't know why, but this is the only way the macro I created does what it is supposed to.

I created a function that calls the creation of a macro and fills the Word Document with the data sent in the call to the function, but this data is kept only when the Document is being shown, if the document is in the background the data goes away for some reason I don't know yet.

I tried with some properties for the Application like :

   Application.Visible = True
   Application.ScreenUpdating = True

But none of them worked, is this possible to achieve with UFT?

Body:
To fix the deletion or removal of the data sent, I had to use the following:

Application.Activate()

So the focus is on the Word File


问:
Kubectl create "invalid object"
I am creating namespace using kubectl with yaml. The following is my yaml configuration

```<code>apiVersion: v1
kind: Namespace
metadata:
    name: "slackishapp"
    labels:
        name: "slackishapp"
</code>```

But, when I run kubectl create -f ./slackish-namespace-manifest.yaml, I got an error like the following

```<code>error: SchemaError(io.k8s.api.autoscaling.v2beta2.PodsMetricStatus): invalid object doesn't have additional properties.
</code>```

What goes wrong on my yaml? I am reading about it on the documentation as well. I don't see any difference with my configuration.

答:
Download the kubectl.exe on https://kubernetes.io/docs/tasks/tools/install-kubectl/#before-you-begin then replace it on Program Files\Docker\Docker\resources\bin if you have docker desktop

Like Andreas Wederbrand said, it is a version problem.

Title: Kubectl create "invalid object"

Body:
I am creating namespace using kubectl with yaml. The following is my yaml configuration

apiVersion: v1
kind: Namespace
metadata:
    name: "slackishapp"
    labels:
        name: "slackishapp"

But, when I run kubectl create -f ./slackish-namespace-manifest.yaml, I got an error like the following

error: SchemaError(io.k8s.api.autoscaling.v2beta2.PodsMetricStatus): invalid object doesn't have additional properties.

What goes wrong on my yaml? I am reading about it on the documentation as well. I don't see any difference with my configuration.


问:
A Foreign key referring Triple from Annotation has the wrong number of columns.
Although I made a little research on this, and I found a lot of threats opened in Internet, I couldn't solve my problem. I attach my code:

Triple.java  the primary key is made by 3 URIs from three different concepts, but it is the same column (is it a problem?)

```<code>        @Entity
        @IdClass(ConceptPk.class)
        @Table(name = "triple")
        public class TripleDBModel {

            protected List<Annotation> annotations;
            public String conceptUriSubject;
            public String conceptUriObject;
            public String conceptUriPredicate;
            public String id;

            @ManyToMany(
                    cascade={CascadeType.ALL},
                    fetch=FetchType.LAZY
            )
            @JoinTable(name = "triple_has_annotation",
                    joinColumns=@JoinColumn(name="annotation_id"),
                    inverseJoinColumns={@JoinColumn(name="uri_concept_subject", referencedColumnName="triple_id"), @JoinColumn(name="uri_concept_object", referencedColumnName="triple_id"), @JoinColumn(name="uri_concept_predicate", referencedColumnName="triple_id")
         })//EDIT
            public List<Annotation> getAnnotations() {
                return annotations;
            }
            public void setAnnotations(List<Annotation> annotations) {
                this.annotations = annotations;
            }
            @Id
            @Column(name = "uri_concept_subject", length = 100)
            public String getConceptUriSubject() {
                return conceptUriSubject;
            }
            public void setConceptUriSubject(String conceptUriSubject) {
                this.conceptUriSubject = conceptUriSubject;
            }
            @Id
            @Column(name = "uri_concept_object", length = 100)
            public String getConceptUriObject() {
                return conceptUriObject;
            }
            public void setConceptUriObject(String conceptUriObject) {
                this.conceptUriObject = conceptUriObject;
            }
            @Id
            @Column(name = "uri_concept_predicate", length = 100)
            public String getConceptUriPredicate() {
                return conceptUriPredicate;
            }
            public void setConceptUriPredicate(String conceptUriPredicate) {
                this.conceptUriPredicate = conceptUriPredicate;
            }

 @Id
        @Column(name = "triple_id", unique = true, nullable = false)
        public String getId() {
            return id;
        }
        public void setId(String id) {
            this.id = id;
        }
    }
</code>```

ConceptPk.java

```<code>    @Embeddable
    public class ConceptPk implements java.io.Serializable {

        private static final long serialVersionUID = 1L;
        public String conceptUriSubject;
        public String conceptUriObject;
        public String conceptUriPredicate;

        @Id
        @Column(name = "uri", length = 100, unique = true, nullable = false)
        public String getConceptUriSubject() {
            return conceptUriSubject;
        }
        public void setConceptUriSubject(String conceptUriSubject) {
            this.conceptUriSubject = conceptUriSubject;
        }

        @Id
        @Column(name = "uri", length = 100, unique = true, nullable = false)
        public String getConceptUriObject() {
            return conceptUriObject;
        }
        public void setConceptUriObject(String conceptUriObject) {
            this.conceptUriObject = conceptUriObject;
        }

        @Id
        @Column(name = "uri", length = 100, unique = true, nullable = false)
        public String getConceptUriPredicate() {
            return conceptUriPredicate;
        }
        public void setConceptUriPredicate(String conceptUriPredicate) {
            this.conceptUriPredicate = conceptUriPredicate;
        }
</code>```

Annotation.java

```<code>    @Entity
    @Table(name = "annotations")
    public class Annotation {

        private Integer id;
        private List<TripleDBModel> triples;

    @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "annotation_id", unique = true, nullable = false)
        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

    @ManyToMany(
                cascade={CascadeType.ALL},
                mappedBy = "annotations", //EDIT
                fetch=FetchType.LAZY
        )
        public List<TripleDBModel> getTriples() {
            return triples;
        }

        public void setTriples(List<TripleDBModel> triples) {
            this.triples = triples;
        }
</code>```

But I am getting this error:

```<code>Caused by: org.hibernate.AnnotationException: A Foreign key refering TripleDBModel from Annotation has the wrong number of column. should be 3
</code>```

What am I doing wrong?? Thanks in advance

答:
```<code>@ManyToMany(
        cascade={CascadeType.ALL},
        mappedBy = "annotation",
        fetch=FetchType.LAZY
)
public List<TripleDBModel> getTriples() {
    return triples;
}
</code>```

The mappedBy should be  "annotations"

Edit: Have a look at this wikibook, especially the bottom section. This is a quite good reference for association mappings etc.

Body:
Although I made a little research on this, and I found a lot of threats opened in Internet, I couldn't solve my problem. I attach my code:

Triple.java  the primary key is made by 3 URIs from three different concepts, but it is the same column (is it a problem?)

        @Entity
        @IdClass(ConceptPk.class)
        @Table(name = "triple")
        public class TripleDBModel {

            protected List<Annotation> annotations;
            public String conceptUriSubject;
            public String conceptUriObject;
            public String conceptUriPredicate;
            public String id;

            @ManyToMany(
                    cascade={CascadeType.ALL},
                    fetch=FetchType.LAZY
            )
            @JoinTable(name = "triple_has_annotation",
                    joinColumns=@JoinColumn(name="annotation_id"),
                    inverseJoinColumns={@JoinColumn(name="uri_concept_subject", referencedColumnName="triple_id"), @JoinColumn(name="uri_concept_object", referencedColumnName="triple_id"), @JoinColumn(name="uri_concept_predicate", referencedColumnName="triple_id")
         })//EDIT
            public List<Annotation> getAnnotations() {
                return annotations;
            }
            public void setAnnotations(List<Annotation> annotations) {
                this.annotations = annotations;
            }
            @Id
            @Column(name = "uri_concept_subject", length = 100)
            public String getConceptUriSubject() {
                return conceptUriSubject;
            }
            public void setConceptUriSubject(String conceptUriSubject) {
                this.conceptUriSubject = conceptUriSubject;
            }
            @Id
            @Column(name = "uri_concept_object", length = 100)
            public String getConceptUriObject() {
                return conceptUriObject;
            }
            public void setConceptUriObject(String conceptUriObject) {
                this.conceptUriObject = conceptUriObject;
            }
            @Id
            @Column(name = "uri_concept_predicate", length = 100)
            public String getConceptUriPredicate() {
                return conceptUriPredicate;
            }
            public void setConceptUriPredicate(String conceptUriPredicate) {
                this.conceptUriPredicate = conceptUriPredicate;
            }

 @Id
        @Column(name = "triple_id", unique = true, nullable = false)
        public String getId() {
            return id;
        }
        public void setId(String id) {
            this.id = id;
        }
    }

ConceptPk.java

    @Embeddable
    public class ConceptPk implements java.io.Serializable {

        private static final long serialVersionUID = 1L;
        public String conceptUriSubject;
        public String conceptUriObject;
        public String conceptUriPredicate;

        @Id
        @Column(name = "uri", length = 100, unique = true, nullable = false)
        public String getConceptUriSubject() {
            return conceptUriSubject;
        }
        public void setConceptUriSubject(String conceptUriSubject) {
            this.conceptUriSubject = conceptUriSubject;
        }

        @Id
        @Column(name = "uri", length = 100, unique = true, nullable = false)
        public String getConceptUriObject() {
            return conceptUriObject;
        }
        public void setConceptUriObject(String conceptUriObject) {
            this.conceptUriObject = conceptUriObject;
        }

        @Id
        @Column(name = "uri", length = 100, unique = true, nullable = false)
        public String getConceptUriPredicate() {
            return conceptUriPredicate;
        }
        public void setConceptUriPredicate(String conceptUriPredicate) {
            this.conceptUriPredicate = conceptUriPredicate;
        }

Annotation.java

    @Entity
    @Table(name = "annotations")
    public class Annotation {

        private Integer id;
        private List<TripleDBModel> triples;

    @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "annotation_id", unique = true, nullable = false)
        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

    @ManyToMany(
                cascade={CascadeType.ALL},
                mappedBy = "annotations", //EDIT
                fetch=FetchType.LAZY
        )
        public List<TripleDBModel> getTriples() {
            return triples;
        }

        public void setTriples(List<TripleDBModel> triples) {
            this.triples = triples;
        }

But I am getting this error:

Caused by: org.hibernate.AnnotationException: A Foreign key refering TripleDBModel from Annotation has the wrong number of column. should be 3

What am I doing wrong?? Thanks in advance

Body:
@ManyToMany(
        cascade={CascadeType.ALL},
        mappedBy = "annotation",
        fetch=FetchType.LAZY
)
public List<TripleDBModel> getTriples() {
    return triples;
}

The mappedBy should be  "annotations"

Edit: Have a look at this wikibook, especially the bottom section. This is a quite good reference for association mappings etc.


问:
Web application hangs while calling Graph API
We have developed an asp.net web application in which we perform authentication using Azure B2C and also calling Azure Graph API to fetch additional custom attributes. I am able to successfully authenticate using OpenIDConnectMiddleware. But when I try to get the user information using Azure Graph API it hangs.

AuthenticationResult result = await authContext.AcquireTokenAsync(this.aadGraphResourceId, credential);

答:
I am calling wait in blocking method

Change that Wait to await. When using asynchronous code, you should go async all the way. If you don't, then you can cause a deadlock.


问:
Is it possible to recover a value which i deleted form SQL table?
I just deleted some record from my database table.i just want to retrieve those data is this possible?

i don't have any backup of the database

答:
If by any chance you're using SQL 2016+ and your table is temporal table please try this:</p>

```<code>SELECT * FROM [yourTable] FOR SYSTEM_TIME ALL
</code>```

Body:
If by any chance you're using SQL 2016+ and your table is temporal table please try this:

SELECT * FROM [yourTable] FOR SYSTEM_TIME ALL


问:
Interpolate based on group
I am trying to perform an interpolation based on the input data ( test_data_Inputs) on the test_data data frame. The way I have it set up now is I do it by Peril so so I first created a dataframe that only contained the fire peril (see below) then perform the interpolation on that specific peril group:

The goal is to have a column in the test_data_inputs that has both the Peril Type, and Factor. One of the issues I have been encountering is the situation where the amount of insurance in the test_data_input is a perfect match within the test_data dataframe. It still interpolates regardless of if it is a perfect match or not.

```<code>fire_peril_test=test_data[test_data['Peril Type'=='Fire']]
from scipy import interpolate
x=fire_peril_test['Amount of Insurance']
x=fire_peril_test['Amount Of Insurance']
y=_fire_peril_test['Factor']
y=fire_peril_test['Factor']
f=interpolate.interp1d(x,y)
xnew=test_data_Inputs["Amount of Insurance"]
ynew=f(xnew)

test_data_Inputs=pd.DataFrame({'Amount of Insurance':[320000,330000,340000]})
test_data=pd.DataFrame({'Amount of Insurance':[300000,350000,400000,300000,350000,400000],'Peril Type':['Fire','Fire','Fire','Water','Water','Water'],'Factor':[.10,.20,.35,.20,.30,.40]})
</code>```

Appreciate all of the assistance.

答:
```<code>amount_of_insurance=pd.DataFrame()
df['Amount of Insurance']=pd.melt(df['Amount of Insurance'],id_vars=['Amount Of Insurance'],var_name='Peril Type',value_name='Factor')

for peril in df['Amount of Insurance']['Peril Type'].unique():
    #peril='Fire'
    x=df['Amount of Insurance']['Amount Of Insurance'][df['Amount of Insurance']['Peril Type']==str(peril)]
    y=df['Amount of Insurance']['Factor'][df['Amount of Insurance']['Peril Type']==str(peril)]
    f=interpolate.interp1d(x,y)
    xnew=data_for_rater[['Enter Amount of Insurance']]
    ynew=f(xnew)
    append_frame=data_for_rater[['Group','Enter Amount of Insurance']]
    append_frame['Peril Type']=str(peril)
    append_frame['Factor']=ynew
    amount_of_insurance=amount_of_insurance.append(append_frame)
</code>```

My solution with my actual data. Pretty much I melted the data to be able to loop through the unique Peril Types. If you guys have any alternatives let me know...

Title: Interpolate based on group

Body:
I am trying to perform an interpolation based on the input data ( test_data_Inputs) on the test_data data frame. The way I have it set up now is I do it by Peril so so I first created a dataframe that only contained the fire peril (see below) then perform the interpolation on that specific peril group:

The goal is to have a column in the test_data_inputs that has both the Peril Type, and Factor. One of the issues I have been encountering is the situation where the amount of insurance in the test_data_input is a perfect match within the test_data dataframe. It still interpolates regardless of if it is a perfect match or not.

fire_peril_test=test_data[test_data['Peril Type'=='Fire']]
from scipy import interpolate
x=fire_peril_test['Amount of Insurance']
x=fire_peril_test['Amount Of Insurance']
y=_fire_peril_test['Factor']
y=fire_peril_test['Factor']
f=interpolate.interp1d(x,y)
xnew=test_data_Inputs["Amount of Insurance"]
ynew=f(xnew)

test_data_Inputs=pd.DataFrame({'Amount of Insurance':[320000,330000,340000]})
test_data=pd.DataFrame({'Amount of Insurance':[300000,350000,400000,300000,350000,400000],'Peril Type':['Fire','Fire','Fire','Water','Water','Water'],'Factor':[.10,.20,.35,.20,.30,.40]})

Appreciate all of the assistance.

Body:
amount_of_insurance=pd.DataFrame()
df['Amount of Insurance']=pd.melt(df['Amount of Insurance'],id_vars=['Amount Of Insurance'],var_name='Peril Type',value_name='Factor')

for peril in df['Amount of Insurance']['Peril Type'].unique():
    #peril='Fire'
    x=df['Amount of Insurance']['Amount Of Insurance'][df['Amount of Insurance']['Peril Type']==str(peril)]
    y=df['Amount of Insurance']['Factor'][df['Amount of Insurance']['Peril Type']==str(peril)]
    f=interpolate.interp1d(x,y)
    xnew=data_for_rater[['Enter Amount of Insurance']]
    ynew=f(xnew)
    append_frame=data_for_rater[['Group','Enter Amount of Insurance']]
    append_frame['Peril Type']=str(peril)
    append_frame['Factor']=ynew
    amount_of_insurance=amount_of_insurance.append(append_frame)

My solution with my actual data. Pretty much I melted the data to be able to loop through the unique Peril Types. If you guys have any alternatives let me know...


问:
How to do Led blink with each port, using stm32 (stm32f103c8t6) boards and Adruino
I am completely new to this and willing to do a simple task using stm32f103c8t6 board, which is "led blink".

Using ArduinoIDE and a simple circuit as shown in the picture, everything goes fine on port PC13. but as soon as I try other ports, it doesn't work.
My aim is to be able to toggle the led status using ports PA0 to PA5.

Here is my code:

```<code>void setup() {
  // initialize the digital pin as an output.
  pinMode(PC13, OUTPUT);
}

void loop() {
  digitalWrite(PC13, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(PC13, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}
</code>```

I change PC13 to PA0, and rewire the board, but no luck :(

How can I solve this issue.
Any kind of help is highly appreciated.

答:
You are using an external LED right (it's a bit difficult to tell for sure in your photo)? The "blue pill"'s internal LED is tied to PC13 only. If you are using an external LED and the program with PC13 works, then there should not be any issue with PA0 to PA5. The only thing I can think of currently is that somehow your program is not being flashed correctly so it's still running the old code.

To test this theory, start with the working PC13 program and then modify the delay time to 2 secs or whatever. Then you can be sure that the new program is downloaded correctly.

Body:
I am completely new to this and willing to do a simple task using stm32f103c8t6 board, which is "led blink".

Using ArduinoIDE and a simple circuit as shown in the picture, everything goes fine on port PC13. but as soon as I try other ports, it doesn't work.
My aim is to be able to toggle the led status using ports PA0 to PA5.

Here is my code:

void setup() {
  // initialize the digital pin as an output.
  pinMode(PC13, OUTPUT);
}

void loop() {
  digitalWrite(PC13, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(PC13, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}

I change PC13 to PA0, and rewire the board, but no luck :(

How can I solve this issue.
Any kind of help is highly appreciated.


问:
What is the maximum amount of data i passed through querystring of jquery ajax?
What is the maximum amount of data i passed through querystring of jquery ajax?</p>

答:
This would depend on the browser and/or server

IE 4.0 and above is ~2048 characters

All other browsers seem to support much more.  So basically if you are trying to implement a cross browser web site/application then its probably best not to exceed 2048 characters.

Also note Web servers can be configured to limit the amount of data passed though a QueryString.  This is rare but it can be done.


问:
How do I Join tables the order by all
I am attempting "Union" 5 Tables and the "order by" the [Date/time]. This works well but the problem is the result is 225000+ rows. this will not fit into excel.

I tried to limit the number of rows By "select top #" which limits the size but the top is the first in data I need the last in or most current data

```<code>SELECT top 1000 [Timestmp]
 ,[Audience]
 ,[Severity]
,[Verbosity]
,[UserFullName]
FROM [PD_SQL_DB].[dbo].[Client1_DiagList]
wHERE [aUDIENCE]='8' AND [SEVERITY] = '4'AND [VERBOSITY] = '0'
Union
SELECT top 1000 [TimeStmp]
,[MessageText]
,[Audience]
,[Severity]
,[Verbosity]
,[UserFullName]
FROM [PD_S`enter code here`QL_DB].[dbo].[Client2_DiagList]
WHERE [AUDIENCE]='8' AND [SEVERITY] = '4'AND [VERBOSITY] = '0'
 Order by [TimeStmp] desc
</code>```

With Query it only gives me the top 1000 oldest rows. What is another way to limit the number or rows and order by desc.

答:
You can nest the UNION inside another SELECT and do the TOP/ORDER BY there:

```<code>SELECT TOP 1000 *
FROM (
    SELECT [Timestmp]
      ,[Audience]
      ,[Severity]
      ,[Verbosity]
      ,[UserFullName]
    FROM [PD_SQL_DB].[dbo].[Client1_DiagList]
    WHERE [aUDIENCE]='8' AND [SEVERITY] = '4'AND [VERBOSITY] = '0'

    Union

    SELECT [TimeStmp]
      ,[MessageText]
      ,[Audience]
      ,[Severity]
      ,[Verbosity]
      ,[UserFullName]
    FROM [PD_S`enter code here`QL_DB].[dbo].[Client2_DiagList]
    WHERE [AUDIENCE]='8' AND [SEVERITY] = '4'AND [VERBOSITY] = '0'
) t
ORDER BY [TimeStmp] DESC
</code>```

Title: How do I Join tables the order by all

Body:
I am attempting "Union" 5 Tables and the "order by" the [Date/time]. This works well but the problem is the result is 225000+ rows. this will not fit into excel.

I tried to limit the number of rows By "select top #" which limits the size but the top is the first in data I need the last in or most current data

SELECT top 1000 [Timestmp]
 ,[Audience]
 ,[Severity]
,[Verbosity]
,[UserFullName]
FROM [PD_SQL_DB].[dbo].[Client1_DiagList]
wHERE [aUDIENCE]='8' AND [SEVERITY] = '4'AND [VERBOSITY] = '0'
Union
SELECT top 1000 [TimeStmp]
,[MessageText]
,[Audience]
,[Severity]
,[Verbosity]
,[UserFullName]
FROM [PD_S`enter code here`QL_DB].[dbo].[Client2_DiagList]
WHERE [AUDIENCE]='8' AND [SEVERITY] = '4'AND [VERBOSITY] = '0'
 Order by [TimeStmp] desc

With Query it only gives me the top 1000 oldest rows. What is another way to limit the number or rows and order by desc.

Body:
You can nest the UNION inside another SELECT and do the TOP/ORDER BY there:

SELECT TOP 1000 *
FROM (
    SELECT [Timestmp]
      ,[Audience]
      ,[Severity]
      ,[Verbosity]
      ,[UserFullName]
    FROM [PD_SQL_DB].[dbo].[Client1_DiagList]
    WHERE [aUDIENCE]='8' AND [SEVERITY] = '4'AND [VERBOSITY] = '0'

    Union

    SELECT [TimeStmp]
      ,[MessageText]
      ,[Audience]
      ,[Severity]
      ,[Verbosity]
      ,[UserFullName]
    FROM [PD_S`enter code here`QL_DB].[dbo].[Client2_DiagList]
    WHERE [AUDIENCE]='8' AND [SEVERITY] = '4'AND [VERBOSITY] = '0'
) t
ORDER BY [TimeStmp] DESC


问:
Validation Error: Invalid Bundle. The bundle at ... contains disallowed file 'Frameworks'
I'm trying to submit an app with the Xcode 6 GM, and I get this error on validation. The app has an action extension and a dynamic framework that's shared between the extension and the app itself.

I don't have a file called 'Frameworks' anywhere in the project, so I'm really not sure what this is supposed to mean. Has anyone gotten this issue or have any ideas?

Archive validation failed due to the issues listed below.

iTunes Store operation failed.

Invalid Bundle. The bundle at ... contains disallowed file 'Frameworks'.

答: I was getting the same error, and it is because I was copying the framework into the extension bundle. As it turns out, frameworks that are used by the extension should be copied into the Main App bundle and only linked in the extension build settings (not copied). Be sure to have the search path '@executable_path/../../Frameworks' in the extension build. I think that path was added automatically by XCode 10.</p>


问:
Pandas Python - Comparing different date ranges and checking if they are in the same time period
I am currently solving a problem and was recommended to use 'Pandas', as it would fit for my solution, so my apologies, as I am kind of new to the 'Pandas' package.

The problem I am trying to solve is to read a text file with data such as this:

```<code>EmpID,ProjectID,DateFrom,DateTo
1,100,2014-11-01,2015-05-01
2,101,2013-12-06,2014-10-06
3,102,2015-06-04,2017-09-04
5,103,2014-10-01,2015-12-01
2,100,2013-03-07,2015-11-07
2,103,2015-07-09,2019-01-19
4,102,2013-11-13,2014-03-13
4,103,2016-02-14,2017-03-15
5,104,2014-03-15,2015-11-09
</code>```

Now my task was to say which employees worked together the longest time period on a common project.

This is my progress so far:

```<code>import pandas as pd
import datetime as dt
import numpy as np

date_parser = lambda c: pd.to_datetime(c, format='%Y/%m/%d', errors='coerce')
df = pd.read_csv('data.csv', delimiter = ',', parse_dates=[2,3], date_parser=date_parser)
#df.set_index("EmpID", inplace = True)
df.sort_values(['ProjectID'], inplace=True)
df['Days Worked'] = (df['DateTo'] - df['DateFrom']).dt.days
cutdown_projecs = df.groupby('ProjectID').filter(lambda x: len(x) >= 2)

print(cutdown_projecs)
</code>```

What I do is order the table, make the date values the correct format, sort by ProjectID and then cut down to projects that repeat themselves two or more times (as this would mean employees worked together on them). I also added a new column, which adds "Days Worked". Which leads me to the following result:

```<code>     EmpID  ProjectID   DateFrom     DateTo      Days Worked
0      1        100    2014-11-01 2015-05-01          181
4      2        100    2013-03-07 2015-11-07          975
2      3        102    2015-06-04 2017-09-04          823
6      4        102    2013-11-13 2014-03-13          120
3      5        103    2014-10-01 2015-12-01          426
5      2        103    2015-07-09 2019-01-19         1290
7      4        103    2016-02-14 2017-03-15          395
</code>```

Now, I am in need of advice as to how to approach the problem correctly. I somehow need to check, which data ranges 'collide' on the same project and then calculate the working days of the employees together. I would very much appreciate it if you could give me a tip. Thank you.

EDIT: Fixed the table.

答:
I cobbled up a solution, but don't know if it meets your needs. It gets the longest time worked together on a job by 2 employees.

```<code>from collections import defaultdict
from itertools import combinations
from datetime import datetime

data ='''\
1,100,2014-11-01,2015-05-01
2,101,2013-12-06,2014-10-06
3,102,2015-06-04,2017-09-04
5,103,2014-10-01,2015-12-01
2,100,2013-03-07,2015-11-07
2,103,2015-07-09,2019-01-19
4,102,2013-11-13,2014-03-13
4,103,2016-02-14,2017-03-15
5,104,2014-03-15,2015-11-09'''.splitlines()

d = defaultdict(list)
for line in data:
    empID, job, start, finish = line.split(',')
    d[job].append([empID,start,finish])

for job, aref in d.items():
    if len(aref) >= 2:
        for ref in combinations(aref, 2):
            begin = max(map(lambda x: x[1], ref))
            end = min(map(lambda x: x[2], ref))
            delta = datetime.strptime(end, '%Y-%m-%d') \
                    - datetime.strptime(begin, '%Y-%m-%d')
            dd = delta.days
            if dd > 0:
                print('employees', ref[0][0], 'and', ref[1][0],
                      'worked together', dd, 'days on job', job)
</code>```

Output was:

```<code>employees 1 and 2 worked together 181 days on job 100
employees 5 and 2 worked together 145 days on job 103
employees 2 and 4 worked together 395 days on job 103
>>>
</code>```

Body:
I am currently solving a problem and was recommended to use 'Pandas', as it would fit for my solution, so my apologies, as I am kind of new to the 'Pandas' package.

The problem I am trying to solve is to read a text file with data such as this:

EmpID,ProjectID,DateFrom,DateTo
1,100,2014-11-01,2015-05-01
2,101,2013-12-06,2014-10-06
3,102,2015-06-04,2017-09-04
5,103,2014-10-01,2015-12-01
2,100,2013-03-07,2015-11-07
2,103,2015-07-09,2019-01-19
4,102,2013-11-13,2014-03-13
4,103,2016-02-14,2017-03-15
5,104,2014-03-15,2015-11-09

Now my task was to say which employees worked together the longest time period on a common project.

This is my progress so far:

import pandas as pd
import datetime as dt
import numpy as np

date_parser = lambda c: pd.to_datetime(c, format='%Y/%m/%d', errors='coerce')
df = pd.read_csv('data.csv', delimiter = ',', parse_dates=[2,3], date_parser=date_parser)
#df.set_index("EmpID", inplace = True)
df.sort_values(['ProjectID'], inplace=True)
df['Days Worked'] = (df['DateTo'] - df['DateFrom']).dt.days
cutdown_projecs = df.groupby('ProjectID').filter(lambda x: len(x) >= 2)

print(cutdown_projecs)

What I do is order the table, make the date values the correct format, sort by ProjectID and then cut down to projects that repeat themselves two or more times (as this would mean employees worked together on them). I also added a new column, which adds "Days Worked". Which leads me to the following result:

     EmpID  ProjectID   DateFrom     DateTo      Days Worked
0      1        100    2014-11-01 2015-05-01          181
4      2        100    2013-03-07 2015-11-07          975
2      3        102    2015-06-04 2017-09-04          823
6      4        102    2013-11-13 2014-03-13          120
3      5        103    2014-10-01 2015-12-01          426
5      2        103    2015-07-09 2019-01-19         1290
7      4        103    2016-02-14 2017-03-15          395

Now, I am in need of advice as to how to approach the problem correctly. I somehow need to check, which data ranges 'collide' on the same project and then calculate the working days of the employees together. I would very much appreciate it if you could give me a tip. Thank you.

EDIT: Fixed the table.

Body:
I cobbled up a solution, but don't know if it meets your needs. It gets the longest time worked together on a job by 2 employees.

from collections import defaultdict
from itertools import combinations
from datetime import datetime

data ='''\
1,100,2014-11-01,2015-05-01
2,101,2013-12-06,2014-10-06
3,102,2015-06-04,2017-09-04
5,103,2014-10-01,2015-12-01
2,100,2013-03-07,2015-11-07
2,103,2015-07-09,2019-01-19
4,102,2013-11-13,2014-03-13
4,103,2016-02-14,2017-03-15
5,104,2014-03-15,2015-11-09'''.splitlines()

d = defaultdict(list)
for line in data:
    empID, job, start, finish = line.split(',')
    d[job].append([empID,start,finish])

for job, aref in d.items():
    if len(aref) >= 2:
        for ref in combinations(aref, 2):
            begin = max(map(lambda x: x[1], ref))
            end = min(map(lambda x: x[2], ref))
            delta = datetime.strptime(end, '%Y-%m-%d') \
                    - datetime.strptime(begin, '%Y-%m-%d')
            dd = delta.days
            if dd > 0:
                print('employees', ref[0][0], 'and', ref[1][0],
                      'worked together', dd, 'days on job', job)

Output was:

employees 1 and 2 worked together 181 days on job 100
employees 5 and 2 worked together 145 days on job 103
employees 2 and 4 worked together 395 days on job 103
>>>


问:
Is it normal for writing ~27k rows 38 cols of data to take ~6+ hours?
I'm creating a pandas dataframe of ~27k rows with 8 columns of text and 30 columns of floats. Pulling the data from Google BigQuery and creating the DataFrame and other formatting variables takes ~5 minutes. I run into a brick wall once I start the writing process though. It takes over 6 hours on average to write this data to a worksheet. It writes about 1.2 rows per second. Other excel templates I've made take at least 70x less time, writing 70-250+ rows per second. I don't understand why it's taking so long. Is there something I could be doing more efficiently?

I've tried using Pandas' integration with xlsxwriter but I can't/don't know how to use cell-level formatting with it. Everything I've found seems to indicate that it doesn't support this. When I do use it, it takes all of 8 minutes to query, create, and write. How can adding cell-level formatting take so much more time?

I've also tried adding the 'constant_memory':True option when creating the workbook lith negligible effect. I'm not sure what else there is to try. I've looked at the size of the data I'm accessing and it's ~24mb for the dataframe and like 0.6 for the format variable.

A minimal example of my writing function is:

    num_rows, num_cols = main_df.shape

    for r in tqdm(xrange(num_rows), desc = 'Writing Rows'):
        for c in xrange(num_cols):
            worksheet.write(r, c, main_df.iloc[r, c], excel_format_data[r][c])
```

I know tqdm adds overhead but I use it with the other files I've talked about and they're much faster with the same code. The only difference is the number of rows but it doesn't scale 1-1.

I expect the output to take a while, maybe 2-3 hours based on other templates I've run. According to the xlsxwriter documentation it took them less than 30 seconds to write 12,800 rows with 50 columns of data. Their table shows time scaling relatively 1 to 1 with the number of rows so it should be taking me about a minute? It currently takes over 6 hours so something is clearly wrong.

I'm using a MacBook pro 2017 with a 2.3 GHz Intel Core i5 and 16 GB 2133 MHz LPDDR3.

答:
@juanpa.arrivillaga has provided an answer in the comments that has helped me greatly (see above).

Basically, .iloc is incredibly inefficient and by using .iat instead I have been able to cut the write time from ~6 hours to ~7 minutes.

Body:
I'm creating a pandas dataframe of ~27k rows with 8 columns of text and 30 columns of floats. Pulling the data from Google BigQuery and creating the DataFrame and other formatting variables takes ~5 minutes. I run into a brick wall once I start the writing process though. It takes over 6 hours on average to write this data to a worksheet. It writes about 1.2 rows per second. Other excel templates I've made take at least 70x less time, writing 70-250+ rows per second. I don't understand why it's taking so long. Is there something I could be doing more efficiently?

I've tried using Pandas' integration with xlsxwriter but I can't/don't know how to use cell-level formatting with it. Everything I've found seems to indicate that it doesn't support this. When I do use it, it takes all of 8 minutes to query, create, and write. How can adding cell-level formatting take so much more time?

I've also tried adding the 'constant_memory':True option when creating the workbook lith negligible effect. I'm not sure what else there is to try. I've looked at the size of the data I'm accessing and it's ~24mb for the dataframe and like 0.6 for the format variable.

A minimal example of my writing function is:

    num_rows, num_cols = main_df.shape

    for r in tqdm(xrange(num_rows), desc = 'Writing Rows'):
        for c in xrange(num_cols):
            worksheet.write(r, c, main_df.iloc[r, c], excel_format_data[r][c])

I know tqdm adds overhead but I use it with the other files I've talked about and they're much faster with the same code. The only difference is the number of rows but it doesn't scale 1-1.

I expect the output to take a while, maybe 2-3 hours based on other templates I've run. According to the xlsxwriter documentation it took them less than 30 seconds to write 12,800 rows with 50 columns of data. Their table shows time scaling relatively 1 to 1 with the number of rows so it should be taking me about a minute? It currently takes over 6 hours so something is clearly wrong.

I'm using a MacBook pro 2017 with a 2.3 GHz Intel Core i5 and 16 GB 2133 MHz LPDDR3.


问:
In Springboot, how to serialize properties into objects when using @ConfigurationProperties and @PropertySource?
When using @ConfigurationProperties with @PropertySource(value = "myconfig.yml") Springboot doesn't serialize my properties into an object

If I put this same config in application.yml and remove the @PropertySource(value = "myconfig.yml"), then it works

```<code>---
testPrefix.simpleProperty: my.property.haha
testPrefix.complexProperties:
  -
    firstName: 'Clark'
    lastName: 'Ken'
  -
    firstName: 'Roger'
    lastName: 'Federer'
</code>```

```<code>@Configuration
@ConfigurationProperties(prefix = "testPrefix")
@PropertySource(value = "testConfigFile.yml")
public class MyTestProperties {
  private String simpleProperty;
  private List<Person> complexProperties;

getters

setters
</code>```

```<code>@SpringBootApplication
public class App implements CommandLineRunner {

  MyTestProperties myProperties;

  @Autowired
  public App(MyTestProperties properties) {
    this.properties = properties;
  }

  public static void main(String[] args) {
    SpringApplication app = new SpringApplication((App.class));
    app.run(args);
  }

  @Override
  public void run(String... args) throws Exception {
    System.out.println(myProperties.getSimpleProperty());
    myProperties.getComplexProperties.stream.forEach(System.out::println));
  }
}
</code>```

Output:

```<code>my.property.haha
</code>```

答:
To my knowledge, YAML properties cannot be loaded using a @PropertySource. I'll look it up as I'm not sure whether the issue has been resolved in the meantime.

[edit]
Apparently, it hasn't been fixed:

YAML files cannot be loaded by using the @PropertySource annotation.
  So, in the case that you need to load values that way, you need to use
  a properties file.

Body:
When using @ConfigurationProperties with @PropertySource(value = "myconfig.yml") Springboot doesn't serialize my properties into an object

If I put this same config in application.yml and remove the @PropertySource(value = "myconfig.yml"), then it works

---
testPrefix.simpleProperty: my.property.haha
testPrefix.complexProperties:
  -
    firstName: 'Clark'
    lastName: 'Ken'
  -
    firstName: 'Roger'
    lastName: 'Federer'

@Configuration
@ConfigurationProperties(prefix = "testPrefix")
@PropertySource(value = "testConfigFile.yml")
public class MyTestProperties {
  private String simpleProperty;
  private List<Person> complexProperties;

getters

setters

@SpringBootApplication
public class App implements CommandLineRunner {

  MyTestProperties myProperties;

  @Autowired
  public App(MyTestProperties properties) {
    this.properties = properties;
  }

  public static void main(String[] args) {
    SpringApplication app = new SpringApplication((App.class));
    app.run(args);
  }

  @Override
  public void run(String... args) throws Exception {
    System.out.println(myProperties.getSimpleProperty());
    myProperties.getComplexProperties.stream.forEach(System.out::println));
  }
}

Output:

my.property.haha


问:
How can I do a function that outputs the not of another function in bash shell?
I have an existing function is_active_instance, which determines if a database instance is running (true) or not. I am working in a new function called is_inactive_instance which needs to return true if is_active_instance returns false.

How can I call is_active_instance from is_inactive_instance and negate its return to return True to main program?

I already tried to call is_instance_active with ! to change the result of the original function.

```<code>is_active_instance(){
    dbservice=""
    if is_mysql_db
    then
        dbservice="mysqld"
    elif is_mariadb_db
    then
        dbservice="mysqld"
    elif is_postgre_db
    then
        dbservice='postgresql'
    fi
    [ $(ps -ef | grep -v grep | grep $dbservice* | wc -l) > 0 ]
}

is_inactive_instance(){
    [ [ ! is_active_instance ] ]
}

if is_active_instance
then
        echo "Is active instance"
elif is_inactive_instance
then
        echo "Is inactive instance"
else
        echo "Other result"
fi

</code>```

In Main body I will need to be able to detect if the instance is running, stopped or other for my purposes.

答:
```<code>Here is an example of how to do this in BASH.  Your code is on the right track but needs syntax changes to work in BASH.

Instead of checking for a NOT you would check for "Yes" or "No", and you may change the outputs to zeroes and ones if you wish and test for those.

Copy the code between CODE STARTS and CODE ENDS into ./active_instance.sh.

Type the line below and press RETURN.
     chmod 755 ./active_instance.sh

CODE STARTS HERE ==================
#!/usr/bin/env bash

for some_db in mariadb mysqld postgres oracle sybase
do
        echo -n "Checking ${some_db}..."
        set `ps -ef|grep -v grep|grep ${some_db}|wc`

        if test ${1} -gt 0
                then
                        echo "Yes"
                else
                        echo "No"
        fi
done
CODE ENDS HERE ==================

To run, type the line below and press RETURN.
     ./active_instance.sh

Sample execution:

./active_instance.sh
Checking mariadb...Yes
Checking mysqld...Yes
Checking postgres...Yes
Checking oracle...No
Checking sybase...No
</code>```

Body:
I have an existing function is_active_instance, which determines if a database instance is running (true) or not. I am working in a new function called is_inactive_instance which needs to return true if is_active_instance returns false.

How can I call is_active_instance from is_inactive_instance and negate its return to return True to main program?

I already tried to call is_instance_active with ! to change the result of the original function.

is_active_instance(){
    dbservice=""
    if is_mysql_db
    then
        dbservice="mysqld"
    elif is_mariadb_db
    then
        dbservice="mysqld"
    elif is_postgre_db
    then
        dbservice='postgresql'
    fi
    [ $(ps -ef | grep -v grep | grep $dbservice* | wc -l) > 0 ]
}

is_inactive_instance(){
    [ [ ! is_active_instance ] ]
}

if is_active_instance
then
        echo "Is active instance"
elif is_inactive_instance
then
        echo "Is inactive instance"
else
        echo "Other result"
fi

In Main body I will need to be able to detect if the instance is running, stopped or other for my purposes.


问:
Find top 4 most common object in list
Let's say I have a list of "Suggestions". I need to get TOP 4 video id's.

```<code>public class Suggestion{

   static allSuggestions = new ArrayList<Suggestion>();

   int id;
   String videoId;

   public Suggestion(int id, String videoId){
     this.id = id;
     this.videoId = videoId;
     allSuggestions.add(this);
   }

   public String getVideoId(){
     return videoId;
   }

   public static List<Suggestion> getAllSuggestions(){
      return allSuggestions;
   }
}
</code>```

I tried this:

```<code>Suggestion.getAllSuggestions()
        .stream()
        .collect(Collectors.groupingBy(Suggestion::getVideoId, Collectors.counting()))
        .entrySet()
        .stream()
        .max(Comparator.comparing(Entry::getValue))
        .ifPresent(System.out::println);
</code>```

But it only returned one, most common video id and not top 4.

答:
Sort the entries descending by count, then select the first 4 using limit:

```<code>Suggestion.getAllSuggestions()
    .stream()
    .collect(Collectors.groupingBy(Suggestion::getVideoId, Collectors.counting()))
    .entrySet()
    .stream()
    .sorted(Comparator.comparing(Entry::getValue).reversed()) // Sort descending by count
    .limit(4) // Top 4 only
    .forEach(System.out::println); // Print them, one per line
</code>```

Title: Find top 4 most common object in list

Body:
Let's say I have a list of "Suggestions". I need to get TOP 4 video id's.

public class Suggestion{

   static allSuggestions = new ArrayList<Suggestion>();

   int id;
   String videoId;

   public Suggestion(int id, String videoId){
     this.id = id;
     this.videoId = videoId;
     allSuggestions.add(this);
   }

   public String getVideoId(){
     return videoId;
   }

   public static List<Suggestion> getAllSuggestions(){
      return allSuggestions;
   }
}

I tried this:

Suggestion.getAllSuggestions()
        .stream()
        .collect(Collectors.groupingBy(Suggestion::getVideoId, Collectors.counting()))
        .entrySet()
        .stream()
        .max(Comparator.comparing(Entry::getValue))
        .ifPresent(System.out::println);

But it only returned one, most common video id and not top 4.

Body:
Sort the entries descending by count, then select the first 4 using limit:

Suggestion.getAllSuggestions()
    .stream()
    .collect(Collectors.groupingBy(Suggestion::getVideoId, Collectors.counting()))
    .entrySet()
    .stream()
    .sorted(Comparator.comparing(Entry::getValue).reversed()) // Sort descending by count
    .limit(4) // Top 4 only
    .forEach(System.out::println); // Print them, one per line


问:
PowerShell Multiple Catch Issue
I'm following Microsoft examples and I get an error when I run this in PowerShell (5.1). I am unable to repro this in the ISE.

```<code>$app="notepad2354.exe"
try{
   iex $app
}
catch [System.Management.Automation.CommandNotFoundException]{
   write-host 'ERROR! The app file could not be found.'
}
catch {
   write-host 'ERROR! Unknown error when executing the step. Error: ' + $_.Exception.Message
}
</code>```

Error:

catch : The term 'catch' is not recognized as the name of a cmdlet,
  function, script file, or operable program. Check the spelling of the
  name, or if a path was included, verify that the path is correct and
  try again.

The odd thing is it works fine on the first catch. If I switch the order, the second one always fails with this message.  Any ideas why this is error'ing?

答:
To add to @UnhandledExcepSean answer where he saw that his issue is with Copy\Pasting into PowerShell console.

The root issue is that PSReadline changed the right-click pasting functionality.

PSReadline, originally offered as an installable module for PowerShell v3 and v4, now comes default with PowerShell v5+ and PowerShell Core 6+. It is a nice module that adds a bunch of new things like syntax highlighting, better multi-line editing experience, etc.

When PSReadline is imported, Right-Click pasting doesn't "work" as expected see GitHub issue: Right click paste should work mostly like Ctrl+v paste 579. What happens is in:

PSReadLine, if the input is "complete", as in, it parses without an
  IncompleteParseException, then the input will be accepted...

[https://github.com/PowerShell/PSReadLine/issues/579#issuecomment-345824783]

Basically, the Right-Click pasting comes from the Windows PowerShell terminal "GUI" host, and streams in the characters into the PowerShell console, where they are being intercepted and interpreted by PSReadline to provide things like syntax highlighting. As it streams in, the trailing } curly brace + newline, completes the statement, and it executes. The second catch statement on the new line then errors out because it is, indeed, on it's own not correct.

Instead, if you use Ctrl+V to paste, the above Copy/Pasting of code does work. the Ctrl+V functionality delivers the entire clipboard contents at once to PSReadline, which interprets everything as a whole before continuing with the execution.

You don't see this happen PowerShell ISE or scripts because Right-Click Pasting doesn't happen.

For fun, you can remove PSReadline in your PowerShell console session:

```<code>Remove-Module PSReadline
</code>```

And then see that Right-Click paste now works as "expected".... Although all the goodness of PSReadline are also gone :-(

Since the Right-Click functionality is specifically a Windows PowerShell terminal issue, even if PSReadline wanted to intercept the Right-Click mouse-hook, it would require PSReadline to now use Windows specific API's to emulate the Windows clipboard feature. This go against "Core" cross-platform functionality. This means that this Right-Click anomaly will likely persist with Ctrl+V to paste as the <s>only</s> recommended way to paste.

Title: PowerShell Multiple Catch Issue

Body:
I'm following Microsoft examples and I get an error when I run this in PowerShell (5.1). I am unable to repro this in the ISE.

$app="notepad2354.exe"
try{
   iex $app
}
catch [System.Management.Automation.CommandNotFoundException]{
   write-host 'ERROR! The app file could not be found.'
}
catch {
   write-host 'ERROR! Unknown error when executing the step. Error: ' + $_.Exception.Message
}

Error:

catch : The term 'catch' is not recognized as the name of a cmdlet,
  function, script file, or operable program. Check the spelling of the
  name, or if a path was included, verify that the path is correct and
  try again.

The odd thing is it works fine on the first catch. If I switch the order, the second one always fails with this message.  Any ideas why this is error'ing?

Body:
To add to @UnhandledExcepSean answer where he saw that his issue is with Copy\Pasting into PowerShell console.

The root issue is that PSReadline changed the right-click pasting functionality.

PSReadline, originally offered as an installable module for PowerShell v3 and v4, now comes default with PowerShell v5+ and PowerShell Core 6+. It is a nice module that adds a bunch of new things like syntax highlighting, better multi-line editing experience, etc.

When PSReadline is imported, Right-Click pasting doesn't "work" as expected see GitHub issue: Right click paste should work mostly like Ctrl+v paste 579. What happens is in:

PSReadLine, if the input is "complete", as in, it parses without an
  IncompleteParseException, then the input will be accepted...

[https://github.com/PowerShell/PSReadLine/issues/579#issuecomment-345824783]

Basically, the Right-Click pasting comes from the Windows PowerShell terminal "GUI" host, and streams in the characters into the PowerShell console, where they are being intercepted and interpreted by PSReadline to provide things like syntax highlighting. As it streams in, the trailing } curly brace + newline, completes the statement, and it executes. The second catch statement on the new line then errors out because it is, indeed, on it's own not correct.

Instead, if you use Ctrl+V to paste, the above Copy/Pasting of code does work. the Ctrl+V functionality delivers the entire clipboard contents at once to PSReadline, which interprets everything as a whole before continuing with the execution.

You don't see this happen PowerShell ISE or scripts because Right-Click Pasting doesn't happen.

For fun, you can remove PSReadline in your PowerShell console session:

Remove-Module PSReadline

And then see that Right-Click paste now works as "expected".... Although all the goodness of PSReadline are also gone :-(

Since the Right-Click functionality is specifically a Windows PowerShell terminal issue, even if PSReadline wanted to intercept the Right-Click mouse-hook, it would require PSReadline to now use Windows specific API's to emulate the Windows clipboard feature. This go against "Core" cross-platform functionality. This means that this Right-Click anomaly will likely persist with Ctrl+V to paste as the <s>only</s> recommended way to paste.


问:
Repeat range of items multiple times in Google Sheets
I want to repeat the range of items multiple times (Value provided).

e.g.

I have this in a sheet1!A

```<code>Detroit
Texas
Utah
California
</code>```

Now I want to repeat them 3 times to get the output at Sheet2!A like:

```<code>Detroit
Texas
Utah
California
Detroit
Texas
Utah
California
Detroit
Texas
Utah
California
</code>```

What should be the formula?

I got this formula:

https://www.excel-bytes.com/how-to-repeat-a-range-of-items-multiple-times-in-excel/

But it's not working in Google Sheets

答:
You might copy down from Row1:

```<code>=offset(Sheet1!A$1,mod(row()-1,4),)
</code>```

for as many sets of four as suits you.

Body:
I want to repeat the range of items multiple times (Value provided).

e.g.

I have this in a sheet1!A

Detroit
Texas
Utah
California

Now I want to repeat them 3 times to get the output at Sheet2!A like:

Detroit
Texas
Utah
California
Detroit
Texas
Utah
California
Detroit
Texas
Utah
California

What should be the formula?

I got this formula:

https://www.excel-bytes.com/how-to-repeat-a-range-of-items-multiple-times-in-excel/

But it's not working in Google Sheets

Body:
You might copy down from Row1:

=offset(Sheet1!A$1,mod(row()-1,4),)

for as many sets of four as suits you.


问:
pip install numpy doesn't work: "No matching distribution found"
I am a newbie in Python. I installed Python 2.7.10 and it comes already with pip. I tried to run this command to download the NumPy library.

```<code>D:\workspace\python>pip install numpy
Collecting numpy
  Could not find a version that satisfies the requirement numpy (from versions: )
No matching distribution found for numpy
</code>```

But I got this error. How can I solve this?

I also want to know the difference between easy_install and pip.

答:
Two steps

install https://www.microsoft.com/en-us/download/confirmation.aspx?id=44266

pip install lightfm --upgrade --ignore-installed scipy

Body:
I am a newbie in Python. I installed Python 2.7.10 and it comes already with pip. I tried to run this command to download the NumPy library.

D:\workspace\python>pip install numpy
Collecting numpy
  Could not find a version that satisfies the requirement numpy (from versions: )
No matching distribution found for numpy

But I got this error. How can I solve this?

I also want to know the difference between easy_install and pip.


问:
How to assign a reference value to a generic property
I am dealing with generics here but I have this strange situation where I trying to assign an instance of a class to a generic property.</p>

```<code>class Context<A,T>  where A: Answer<T>
{
    void SomeMethod()
    {
        A answer; // suppose it have a value;
        answer.context=this; // produce CS00029 error
    }
}

class Answer<T>
{
    Context<Answer<T>,T> context {get;set;}
}
</code>```

答:
To whom interested, I found a solution from someone outside this site, and that is his suggestion:

```<code>public class Context<A, T>: IContext<A, T> where A : Answer<T>
{
   void SomeMethod()
   {
    A answer = Activator.CreateInstance<A>();
    answer.context = this;
   }
}

public class Answer<T>
{
   public IContext<Answer<T>, T> context { get; set; }
}

public interface IContext<out A, T> {}
</code>```

The Solution Link

Body:
I am dealing with generics here but I have this strange situation where I trying to assign an instance of a class to a generic property.

class Context  where A: Answer<T>
{
    void SomeMethod()
    {
        A answer; // suppose it have a value;
        answer.context=this; // produce CS00029 error
    }
}

class Answer<T>
{
    Context<Answer<T>,T> context {get;set;}
}

Body:
To whom interested, I found a solution from someone outside this site, and that is his suggestion:

public class Context<A, T>: IContext<A, T> where A : Answer<T>
{
   void SomeMethod()
   {
    A answer = Activator.CreateInstance<A>();
    answer.context = this;
   }
}

public class Answer<T>
{
   public IContext<Answer<T>, T> context { get; set; }
}

public interface IContext<out A, T> {}

The Solution Link