问:
React.js Navbar Hamburger Menu won't toggle closed
So, I have a react.js app built with a group. Our Navbar works, but when the Navbar is toggled from a smaller screen using the Hamburger menu, it will open, but the toggle doesn't work to close it, it stays stuck open. I didn't program this page, but I've been trying to debug why it won't close, and for what I can see, it should work. </p>

<p>Yes, I know react.bootstrap is a thing, and I was thinking about converting it, but I'm on a deadline and don't want to rewrite this entire component from scratch if it is at all possible. Any thoughts, or suggestions. I thought it was likely in the toggleNav function, but from what I've tested it seems to be correct. </p>

```<code>import React, { Component } from "react";
import { Link } from "react-router-dom";
import "./style.css";

class Nav extends Component {
  state = {
    open: false,
    width: window.innerWidth,
  };

  updateWidth = () => {
    const newState = { width: window.innerWidth };

    if (this.state.open && newState.width > 991) {
      newState.open = false;
    }

    this.setState(newState);
  };

  toggleNav = () => {
    this.setState({ open: !this.state.open });
  };

  setActiveNavItem = (path) => {
    return window.location.pathname === path ? "nav-link active" : "nav-link";
  };

  componentDidMount() {
    window.addEventListener("resize", this.updateWidth);
  }

  componentWillUnmount() {
    window.removeEventListener("resize", this.updateWidth);
  }

  render() {
    return (
      <nav className="navbar navbar-expand-lg navbar-light">
        <Link className="navbar-brand" to="/">
          Seenit
        </Link>
        <button
          onClick={this.toggleNav}
          className="navbar-toggler"
          data-toggle="collapse"
          data-target="#navbarNav"
          aria-controls="navbarNav"
          aria-expanded="false"
          aria-label="Toggle navigation"
        >
          <span className="navbar-toggler-icon" />
        </button>
        <div
          className={`${this.state.open ? "" : "collapse "}navbar-collapse`}
          id="navbarNav"
        >
          {/* Navbar items */}
          <ul className="navbar-nav">
            <li className="nav-item">
              <Link
                onClick={this.toggleNav}
                className={this.setActiveNavItem("/")}
                to="/"
              >
                Home
              </Link>
            </li>

            <li className="nav-item">
              <Link
                onClick={this.toggleNav}
                className={this.setActiveNavItem("/create-post")}
                to="/create-post"
              >
                Create a Post
              </Link>
            </li>

            <li className="nav-item">
              <Link
                onClick={this.toggleNav}
                className={this.setActiveNavItem("/log-in")}
                to="/log-in"
              >
                Log In
              </Link>
            </li>

            <li className="nav-item">
              <Link
                onClick={this.toggleNav}
                className={this.setActiveNavItem("/sign-up")}
                to="/sign-up"
              >
                Sign Up
              </Link>
            </li>
          </ul>
        </div>
      </nav>
    );
  }
}

export default Nav;
</code>```

答:
This React component is a direct implementation of the Bootstrap Toggler Navbar.

Unfortunately, this component also contains code that modifies the navbar, which almost certainly breaks the Bootstrap code that controls collapsible navbars.

Here is the pure HTML version of this navbar component. Note that it collapses to a hamburger on narrow screens (as desired).

It should be straightforward to remove from this component the code that modifies the Bootstrap Toggler navbar.

.navbar {
  outline: 1px solid #ddd;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

<body class="p-2">
  <nav class="navbar navbar-expand-lg navbar-light mr-5">
    Seenit
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>

    <div class="collapse navbar-collapse" id="navbarNav">

      <ul class="navbar-nav">
        <li class="nav-item">
          Home
        </li>

        <li class="nav-item">
          Create a Post
        </li>

        <li class="nav-item">
          Log In
        </li>

        <li class="nav-item">
          Sign Up
        </li>
      </ul>

    </div>
  </nav>

  <!-- JS required for Bootstrap -->
  <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
</body></code>```

Body:
So, I have a react.js app built with a group. Our Navbar works, but when the Navbar is toggled from a smaller screen using the Hamburger menu, it will open, but the toggle doesn't work to close it, it stays stuck open. I didn't program this page, but I've been trying to debug why it won't close, and for what I can see, it should work.

Yes, I know react.bootstrap is a thing, and I was thinking about converting it, but I'm on a deadline and don't want to rewrite this entire component from scratch if it is at all possible. Any thoughts, or suggestions. I thought it was likely in the toggleNav function, but from what I've tested it seems to be correct.

import React, { Component } from "react";
import { Link } from "react-router-dom";
import "./style.css";

class Nav extends Component {
  state = {
    open: false,
    width: window.innerWidth,
  };

  updateWidth = () => {
    const newState = { width: window.innerWidth };

    if (this.state.open && newState.width > 991) {
      newState.open = false;
    }

    this.setState(newState);
  };

  toggleNav = () => {
    this.setState({ open: !this.state.open });
  };

  setActiveNavItem = (path) => {
    return window.location.pathname === path ? "nav-link active" : "nav-link";
  };

  componentDidMount() {
    window.addEventListener("resize", this.updateWidth);
  }

  componentWillUnmount() {
    window.removeEventListener("resize", this.updateWidth);
  }

  render() {
    return (

        <Link className="navbar-brand" to="/">
          Seenit
        </Link>
        <button
          onClick={this.toggleNav}
          className="navbar-toggler"
          data-toggle="collapse"
          data-target="#navbarNav"
          aria-controls="navbarNav"
          aria-expanded="false"
          aria-label="Toggle navigation"
        >

        </button>
        <div
          className={`${this.state.open ? "" : "collapse "}navbar-collapse`}
          id="navbarNav"
        >
          {/* Navbar items */}

              <Link
                onClick={this.toggleNav}
                className={this.setActiveNavItem("/")}
                to="/"
              >
                Home
              </Link>

              <Link
                onClick={this.toggleNav}
                className={this.setActiveNavItem("/create-post")}
                to="/create-post"
              >
                Create a Post
              </Link>

              <Link
                onClick={this.toggleNav}
                className={this.setActiveNavItem("/log-in")}
                to="/log-in"
              >
                Log In
              </Link>

              <Link
                onClick={this.toggleNav}
                className={this.setActiveNavItem("/sign-up")}
                to="/sign-up"
              >
                Sign Up
              </Link>

    );
  }
}

export default Nav;

Body:
This React component is a direct implementation of the Bootstrap Toggler Navbar.

Unfortunately, this component also contains code that modifies the navbar, which almost certainly breaks the Bootstrap code that controls collapsible navbars.

Here is the pure HTML version of this navbar component. Note that it collapses to a hamburger on narrow screens (as desired).

It should be straightforward to remove from this component the code that modifies the Bootstrap Toggler navbar.

.navbar {
  outline: 1px solid #ddd;
}

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

<body class="p-2">
  <nav class="navbar navbar-expand-lg navbar-light mr-5">
    <a class="navbar-brand" href="#">Seenit</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>

    <div class="collapse navbar-collapse" id="navbarNav">

      <ul class="navbar-nav">
        <li class="nav-item">
          <a class="nav-link" href="#">Home</a>
        </li>

        <li class="nav-item">
          <a class="nav-link" href="#">Create a Post</a>
        </li>

        <li class="nav-item">
          <a class="nav-link" href="#">Log In</a>
        </li>

        <li class="nav-item">
          <a class="nav-link" href="#">Sign Up</a>
        </li>
      </ul>

    </div>
  </nav>

  <!-- JS required for Bootstrap -->
  <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
</body>


来源: stackexchange

问:
Kafka streams API - deserialize dynyamically generated JSON
I've been trying to find a solution to the following situation with no avail:

I have a Kafka Streams application which should read from a single input topic a series of JSON objects, all not exactly the same as one another. Practically speaking, each JSON is a representation of an HTTP request object, thus not all JSON records have the same headers, request parameters, cookies and so forth. Furthermore, the JSON objects are written

Is there any way to achieve this? Not expecting for any detailed how-to solutions. Only for some leads on how I can achieve this, as my search over the internet has ended me with nothing so far.

答:
Here's an idea: use Jackson's tree model to dynamically parse your JSON into a JsonNode, and then use this tree representation in your Kafka Streams topology to process the requests.

```<code>ObjectMapper objectMapper = new ObjectMapper();
JsonNode rootNode = objectMapper.readTree(json);
...
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Here's an idea: use Jackson's tree model to dynamically parse your JSON into a JsonNode, and then use this tree representation in your Kafka Streams topology to process the requests.

ObjectMapper objectMapper = new ObjectMapper();
JsonNode rootNode = objectMapper.readTree(json);
...


问:
check boolean value again and again
I am trying to build infinite scroll for my cards.
I am using a variable reload in data.service to check for need to load more data which is getting set to true when page end is getting reached.

The variable setting to true is done by app.component

The content population is done in post.component

And ```reload`` is present in <strong><em>data.service</em></strong> which is using http service to fetch for content from php server.<br>
Curently I am using <em>observable</em> and trying to access reload status repeatedly but it is getting subscribed only once on Init.
<br><br>
<strong><em>app.component.ts</em></strong></p>

```import { Component,HostListener } from '@angular/core';
import * as M from 'materialize-css';
import {DataService} from './current/posts/post-card/data.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent
{

  title = 'cosmos';
  constructor(private scrollSet: DataService){}

  @HostListener('scroll', ['$event'])
  onScroll(event:any)
  {
    if (event.target.offsetHeight + event.target.scrollTop >= event.target.scrollHeight-100)
      {
        console.log("noww");
        this.scrollSet.setValue(true);
      }
  }
}
```

<p><br>
<strong><em>post.component.ts</em></strong></p>

```import { Component, OnInit} from '@angular/core';
import {DataService} from './data.service';
import { DomSanitizer } from '@angular/platform-browser';
import {Title} from "@angular/platform-browser";

@Component({
  selector: 'app-post-card',
  templateUrl: './post-card.component.html',
  styleUrls: ['./post-card.component.css']
})
export class PostCardComponent implements OnInit {

  constructor(private data: DataService,public sanitizer: DomSanitizer,private titleService:Title)
  {
    this.titleService.setTitle("Current Feed | Cosmos");
  }

  received = 'none';

  posts: any = [];

  ngOnInit()
  {
    this.data.getPostData().subscribe(data =>
      {
      this.posts.push(data);
      this.received='success';
      },
      error =>
      {
        this.received='error';
      });

    this.data.getValue().subscribe((value) => {
      this.data.getPostData().subscribe(data =>
      {
      this.posts.push(data);
      this.received='success';
      },
      error =>
      {
        this.received='error';
      });
    });
  }
}
```

<p><br>
<strong><em>data.service.ts</em></strong></p>

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

@Injectable({
  providedIn: 'root'
})
export class DataService {

  private reload: BehaviorSubject<boolean>;
  constructor(private http: HttpClient)
  {
    this.reload = new BehaviorSubject<boolean>(false);
  }

  fetchGap=5; // use this to set number of results wanted per fetch
  fetchEnd:number= 0;

  setValue(newValue): void {
    this.reload.next(newValue);
  }
  getValue(): Observable<boolean> {
    return this.reload.asObservable();
  }
  getPostData(){
    this.fetchEnd+=this.fetchGap;
    return this.http.get('http://localhost:1234/Server/getPosts.php?fetchEnd='+this.fetchEnd+'&fetchGap='+this.fetchGap);
  }
}
```

答:
the problem is that you haven't set the value of reload to false after your treatment.
try to check inside post.component.ts. here is a portion of that code, the block which suscribe to reload.

post.component.ts reload block

```<code>   this.data.getValue().subscribe((value) => {
      if(value){
        this.data.getPostData().subscribe(data =>
          {
            this.posts.push(data);
            this.received='success';
          },
          error =>
          {
            this.received='error';
          });
          this.data.setValue(false);
       }
   });
</code>```

Title: check boolean value again and again

Body:
I am trying to build infinite scroll for my cards.
I am using a variable reload in data.service to check for need to load more data which is getting set to true when page end is getting reached.

The variable setting to true is done by app.component

The content population is done in post.component

And ```reload`` is present in data.service which is using http service to fetch for content from php server.

Curently I am using observable and trying to access reload status repeatedly but it is getting subscribed only once on Init.

app.component.ts

import { Component,HostListener } from '@angular/core';
import * as M from 'materialize-css';
import {DataService} from './current/posts/post-card/data.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent
{

  title = 'cosmos';
  constructor(private scrollSet: DataService){}

  @HostListener('scroll', ['$event'])
  onScroll(event:any)
  {
    if (event.target.offsetHeight + event.target.scrollTop >= event.target.scrollHeight-100)
      {
        console.log("noww");
        this.scrollSet.setValue(true);
      }
  }
}

post.component.ts

import { Component, OnInit} from '@angular/core';
import {DataService} from './data.service';
import { DomSanitizer } from '@angular/platform-browser';
import {Title} from "@angular/platform-browser";

@Component({
  selector: 'app-post-card',
  templateUrl: './post-card.component.html',
  styleUrls: ['./post-card.component.css']
})
export class PostCardComponent implements OnInit {

  constructor(private data: DataService,public sanitizer: DomSanitizer,private titleService:Title)
  {
    this.titleService.setTitle("Current Feed | Cosmos");
  }

  received = 'none';

  posts: any = [];

  ngOnInit()
  {
    this.data.getPostData().subscribe(data =>
      {
      this.posts.push(data);
      this.received='success';
      },
      error =>
      {
        this.received='error';
      });

    this.data.getValue().subscribe((value) => {
      this.data.getPostData().subscribe(data =>
      {
      this.posts.push(data);
      this.received='success';
      },
      error =>
      {
        this.received='error';
      });
    });
  }
}

data.service.ts

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

@Injectable({
  providedIn: 'root'
})
export class DataService {

  private reload: BehaviorSubject<boolean>;
  constructor(private http: HttpClient)
  {
    this.reload = new BehaviorSubject<boolean>(false);
  }

  fetchGap=5; // use this to set number of results wanted per fetch
  fetchEnd:number= 0;

  setValue(newValue): void {
    this.reload.next(newValue);
  }
  getValue(): Observable<boolean> {
    return this.reload.asObservable();
  }
  getPostData(){
    this.fetchEnd+=this.fetchGap;
    return this.http.get('http://localhost:1234/Server/getPosts.php?fetchEnd='+this.fetchEnd+'&fetchGap='+this.fetchGap);
  }
}

Body:
the problem is that you haven't set the value of reload to false after your treatment.
try to check inside post.component.ts. here is a portion of that code, the block which suscribe to reload.

post.component.ts reload block

   this.data.getValue().subscribe((value) => {
      if(value){
        this.data.getPostData().subscribe(data =>
          {
            this.posts.push(data);
            this.received='success';
          },
          error =>
          {
            this.received='error';
          });
          this.data.setValue(false);
       }
   });


问:
In Keras, why is the attribute decay in SGD considered to be left in only for backward compatibility?
Reading Keras-SGD I read the following.

..., decay is included for backward compatibility to allow time
inverse decay of learning rate. lr is included for backward
compatibility, recommended to use learning_rate instead.

Should decay no longer be used (doubtful) or is there another location to set it or is it replaced by another property? Why is Keras considering 'decay' only to be "included for backward compatibility."

答:
Learning rate decay is commonly handled using training callbacks like ReduceLROnPlateau and, more flexibly, LearningRateScheduler

The snippet in the documentation of LearningRateScheduler gives an example of how to implement exponential learning rate decay like in SGD:

```<code># This function keeps the learning rate at 0.001 for the first ten epochs
# and decreases it exponentially after that.
def scheduler(epoch):
  if epoch < 10:
    return 0.001
  else:
    return 0.001 * tf.math.exp(0.1 * (10 - epoch))

callback = tf.keras.callbacks.LearningRateScheduler(scheduler)
model.fit(data, labels, epochs=100, callbacks=[callback],
          validation_data=(val_data, val_labels))

</code>```

Properties like decay and lr are a leftover from the era of the first version of Keras. Keras 2.x introduced a much cleaner API while remaining backwards-compatible.

Body:
Learning rate decay is commonly handled using training callbacks like ReduceLROnPlateau and, more flexibly, LearningRateScheduler

The snippet in the documentation of LearningRateScheduler gives an example of how to implement exponential learning rate decay like in SGD:

# This function keeps the learning rate at 0.001 for the first ten epochs
# and decreases it exponentially after that.
def scheduler(epoch):
  if epoch < 10:
    return 0.001
  else:
    return 0.001 * tf.math.exp(0.1 * (10 - epoch))

callback = tf.keras.callbacks.LearningRateScheduler(scheduler)
model.fit(data, labels, epochs=100, callbacks=[callback],
          validation_data=(val_data, val_labels))

Properties like decay and lr are a leftover from the era of the first version of Keras. Keras 2.x introduced a much cleaner API while remaining backwards-compatible.


问:
jQuery $ function syntax
What is the difference between the following function definitions?

1:

$(function () {
    //stuff here
});
```

<p>2:</p>

<pre class="lang-js prettyprint-override"><code>function($){
    //stuff here
}
</code>```

答:
This code calls the function $ with anonymous function as the first argument. Usually it is used to do something when page is loaded (or better say DOM is ready). And yes it will do some stuff, but only when event will be fired.

This code is just a declaration of anonymous function with one argument $. You can often find such functions in the code of jQuery plugins. Such technique is useful to have $ variable locally. This will improve performance a bit and help not to pollute global scope.

So the first snippet will make some action being executed and the second will do nothing useful.

ContentLicense: CC BY-SA 3.0

Title: jQuery $ function syntax

Body:
What is the difference between the following function definitions?

1:

$(function () {
    //stuff here
});

2:

function($){
    //stuff here
}


问:
How can I remove an object from array in python?
How can I remove an object from array in python?

I want to select an msgID and want to delete that full object with username, msg, time_stamp (all of it).

```<code>room_msg =  [
 {
  'msgID': 1,
  'username': 'User1',
  'msg': 'msg1',
  'time_stamp': 'May-31 05:29PM'},
 {
  'msgID': 2,
  'username': 'User2',
  'msg': 'msg2',
  'time_stamp': 'May-31 05:29PM'},
{
  'msgID': 3,
  'username': 'User3',
  'msg': 'msg3',
  'time_stamp': 'May-31 05:29PM'} ]
</code>```

Like if I select 'msgID': 3
after deleting the 'msgID': 3 the array should like this

```<code>room_msg = [
 {
  'msgID': 1,
  'username': 'User1',
  'msg': 'msg1',
  'time_stamp': 'May-31 05:29PM'},
 {
  'msgID': 2,
  'username': 'User2',
  'msg': 'msg2',
  'time_stamp': 'May-31 05:29PM'}
]
</code>```

Is that possible?
I can't find x with that msgID room_msg[x].

答:
This simple code should do it:</p>

```<code>desired_id = 3  # example id

for i, msg in enumerate(room_msg):
    if msg['msgID'] == desired_id:
        del room_msg[i]
</code>```

Body:
How can I remove an object from array in python?

I want to select an msgID and want to delete that full object with username, msg, time_stamp (all of it).

room_msg =  [
 {
  'msgID': 1,
  'username': 'User1',
  'msg': 'msg1',
  'time_stamp': 'May-31 05:29PM'},
 {
  'msgID': 2,
  'username': 'User2',
  'msg': 'msg2',
  'time_stamp': 'May-31 05:29PM'},
{
  'msgID': 3,
  'username': 'User3',
  'msg': 'msg3',
  'time_stamp': 'May-31 05:29PM'} ]

Like if I select 'msgID': 3
after deleting the 'msgID': 3 the array should like this

room_msg = [
 {
  'msgID': 1,
  'username': 'User1',
  'msg': 'msg1',
  'time_stamp': 'May-31 05:29PM'},
 {
  'msgID': 2,
  'username': 'User2',
  'msg': 'msg2',
  'time_stamp': 'May-31 05:29PM'}
]

Is that possible?
I can't find x with that msgID room_msg[x].

Body:
This simple code should do it:

desired_id = 3  # example id

for i, msg in enumerate(room_msg):
    if msg['msgID'] == desired_id:
        del room_msg[i]


问:
tableView.tableHeaderView being set but not drawn
whenever I set my tableHeaderView I'm not seeing it in the Simulator.
If I add it as a subview, it ends up getting drawn underneath the section header. Any idea what I'm missing here?

I do have a XIB file. I didn't see any properties in IB to affect headerViews though.

```<code>- (void)viewDidLoad {
[super viewDidLoad];
MyTitleView *titleView = [[MyTitleView alloc] initWithFrame:CGRectMake(60,0,260,40)];
titleView.label.text = @"My Title";
self.navigationItem.titleView = titleView;
[titleView release];

StandardTableHeaderView *headerView = [[StandardTableHeaderView alloc] initWithFrame:CGRectMake(0,0,320,44)];
self.tableView.tableHeaderView = headerView;
//  [self.view addSubview:self.tableView.tableHeaderView];
//  [headerView release];

NSLog(@"Header: %@",self.tableView.tableHeaderView); //Logs ] Header:     <StandardTableHeaderView: 0x5a508b0; frame = (0 0; 320 44); layer = <CALayer: 0x5a51130>>
</code>```

Edit:
StandardTableHeaderView.m init method:

```<code>- (id)initWithFrame:(CGRect)frame {
if ((self = [super initWithFrame:frame])) {
    self.backgroundColor = [UIColor redColor];
    self.label = [[UILabel alloc] initWithFrame:CGRectMake(frame.origin.x,0,frame.size.width,frame.size.height)];
    self.label.backgroundColor = [UIColor clearColor];
    self.label.textColor = [UIColor whiteColor];
    self.label.font = [UIFont fontWithName:@"Helvetica" size:16];
    [self addSubview:self.label];
}
return self;
}
</code>```

答:
Just came across the same problem where I had it in viewDidLoad() it worked in the simulator for iPhone 11 Pro but not for iPhone 8. Moving it to viewDidAppear() solved the problem, but I ended up moving it to viewDidLayoutSubviews() which I felt was the most appropriate place for it - works perfectly in the simulator across all iPhone models.

```<code>override func viewDidLayoutSubviews() {

    let headerView = Bundle.main.loadNibNamed("HeaderView", owner: self, options: nil)?.first as? UIView
    headerView!.frame = CGRect(x: 0, y: 0, width: table_view!.frame.width, height: 160.0)
    tableView!.tableHeaderView = headerView
}
</code>```

Body:
whenever I set my tableHeaderView I'm not seeing it in the Simulator.
If I add it as a subview, it ends up getting drawn underneath the section header. Any idea what I'm missing here?

I do have a XIB file. I didn't see any properties in IB to affect headerViews though.

- (void)viewDidLoad {
[super viewDidLoad];
MyTitleView *titleView = [[MyTitleView alloc] initWithFrame:CGRectMake(60,0,260,40)];
titleView.label.text = @"My Title";
self.navigationItem.titleView = titleView;
[titleView release];

StandardTableHeaderView *headerView = [[StandardTableHeaderView alloc] initWithFrame:CGRectMake(0,0,320,44)];
self.tableView.tableHeaderView = headerView;
//  [self.view addSubview:self.tableView.tableHeaderView];
//  [headerView release];

NSLog(@"Header: %@",self.tableView.tableHeaderView); //Logs ] Header:     <StandardTableHeaderView: 0x5a508b0; frame = (0 0; 320 44); layer = <CALayer: 0x5a51130>>

Edit:
StandardTableHeaderView.m init method:

- (id)initWithFrame:(CGRect)frame {
if ((self = [super initWithFrame:frame])) {
    self.backgroundColor = [UIColor redColor];
    self.label = [[UILabel alloc] initWithFrame:CGRectMake(frame.origin.x,0,frame.size.width,frame.size.height)];
    self.label.backgroundColor = [UIColor clearColor];
    self.label.textColor = [UIColor whiteColor];
    self.label.font = [UIFont fontWithName:@"Helvetica" size:16];
    [self addSubview:self.label];
}
return self;
}

Body:
Just came across the same problem where I had it in viewDidLoad() it worked in the simulator for iPhone 11 Pro but not for iPhone 8. Moving it to viewDidAppear() solved the problem, but I ended up moving it to viewDidLayoutSubviews() which I felt was the most appropriate place for it - works perfectly in the simulator across all iPhone models.

override func viewDidLayoutSubviews() {

    let headerView = Bundle.main.loadNibNamed("HeaderView", owner: self, options: nil)?.first as? UIView
    headerView!.frame = CGRect(x: 0, y: 0, width: table_view!.frame.width, height: 160.0)
    tableView!.tableHeaderView = headerView
}


问:
How to run another function as async in rust?
as a JS dev i'm having a real hard time understanding error handling in rust. especially with asyncronisity. heres some code from another stackoverflow question using async-std to call an async scraper function:

```<code>use std::fs::File;
use std::io::{self, BufReader};
use std::io::BufRead;
//use async_std::task;

async fn scrape<R: BufRead>(reader: &mut R) -> io::Result<()> {
    reader.lines()
        .try_for_each(|line_result| line_result.and_then(|line| Ok(println!("{}", line))))?;
    Ok(())
}

fn main() {
    let file_result = File::open("wlist.txt");
    let file;
    match file_result {
       Ok(f) => file = f,
       Err(e) => { println!("File open error! {}", e); return; },
    }
    let mut reader = BufReader::new(file);

    match scrape(&mut reader) {
        Ok(_) => println!("done!"),
        Err(e) => println!("File read error! {}", e),
    }
}
</code>```

I'm trying to call scrape in an asyncronous way like:

```<code>    task::block_on(match scrape(&mut reader) {
        Ok(_) => println!("done!"),
        Err(e) => println!("File read error! {}", e),
    })
</code>```

but it errors with
the trait std::future::Future is not implemented for ()

What's wrong with the code snippet? how can I run scraper as async with as less modification to the rest of the code as possible?

答:
Usually you can only call async functions from async context, except when you use the block_on or spawn functions or similar from your executor.

The easiest way to create an async context is an async block. Then you need to use the .await operator to properly chain asyncs:

```<code>    task::block_on(async {
        match scrape(&mut reader).await {
            Ok(_) => println!("done!"),
            Err(e) => println!("File read error! {}", e),
        }
    })
</code>```

For more complex code you will have an async function that may fail that calls another async function that also may fail. In those cases it is idiomatic to write other_async_func().await? to await and forward the error at the same time.

Body:
as a JS dev i'm having a real hard time understanding error handling in rust. especially with asyncronisity. heres some code from another stackoverflow question using async-std to call an async scraper function:

use std::fs::File;
use std::io::{self, BufReader};
use std::io::BufRead;
//use async_std::task;

async fn scrape<R: BufRead>(reader: &mut R) -> io::Result<()> {
    reader.lines()
        .try_for_each(|line_result| line_result.and_then(|line| Ok(println!("{}", line))))?;
    Ok(())
}

fn main() {
    let file_result = File::open("wlist.txt");
    let file;
    match file_result {
       Ok(f) => file = f,
       Err(e) => { println!("File open error! {}", e); return; },
    }
    let mut reader = BufReader::new(file);

    match scrape(&mut reader) {
        Ok(_) => println!("done!"),
        Err(e) => println!("File read error! {}", e),
    }
}

I'm trying to call scrape in an asyncronous way like:

    task::block_on(match scrape(&mut reader) {
        Ok(_) => println!("done!"),
        Err(e) => println!("File read error! {}", e),
    })

but it errors with
the trait std::future::Future is not implemented for ()

What's wrong with the code snippet? how can I run scraper as async with as less modification to the rest of the code as possible?

Body:
Usually you can only call async functions from async context, except when you use the block_on or spawn functions or similar from your executor.

The easiest way to create an async context is an async block. Then you need to use the .await operator to properly chain asyncs:

    task::block_on(async {
        match scrape(&mut reader).await {
            Ok(_) => println!("done!"),
            Err(e) => println!("File read error! {}", e),
        }
    })

For more complex code you will have an async function that may fail that calls another async function that also may fail. In those cases it is idiomatic to write other_async_func().await? to await and forward the error at the same time.


问:
Can't get data from API on my Google Spreadsheet
I manage to get data from https://api.hitbtc.com/api/2/public/ticker to my Google Spreadsheet using this code script

```<code>    function ticker(){
  var rows=[],obj_array=null;
  try {obj_array=JSON.parse(UrlFetchApp.fetch("https://api.hitbtc.com/api/2/public/ticker").getContentText());} catch (e) {obj_array=null;}
  if (obj_array!=null){
    for (r in obj_array) {rows.push([obj_array[r].symbol,parseFloat(obj_array[r].last),parseFloat(obj_array[r].volume),parseFloat(obj_array[r].ask),parseFloat(obj_array[r].bid)]);}
    var ss=SpreadsheetApp.getActiveSpreadsheet(),sheet=ss.getSheetByName('Hitbtc');ss.getRange("Hitbtc!A1").setValue(new Date());
    try {var range=sheet.getRange(2,1,sheet.getLastRow(),6).clearContent();} catch(e) {Logger.log("error");}
    if (rows==null||rows=="") {Browser.msgBox("Oops, no data"); return false;}
    range=sheet.getRange(2,1,rows.length,5); range.setValues(rows);
  }
}
</code>```

Then I try another API from https://api.kucoin.com/api/v1/market/allTickers, I can't manage to get the data.Always show #NUM!. Can someone help me?

```<code>function kuticker(){
  var rows=[],obj_array=null;
  try {obj_array=JSON.parse(UrlFetchApp.fetch("https://api.kucoin.com/api/v1/market/allTickers").getContentText());} catch (e) {obj_array=null;}
  if (obj_array!=null){
    for (r in obj_array) {rows.push([obj_array[r].symbol,parseFloat(obj_array[r].last),parseFloat(obj_array[r].vol),parseFloat(obj_array[r].buy),parseFloat(obj_array[r].sell)]);}
    var ss=SpreadsheetApp.getActiveSpreadsheet(),sheet=ss.getSheetByName('Kucoin');ss.getRange("Kucoin!A1").setValue(new Date());
    try {var range=sheet.getRange(2,1,sheet.getLastRow(),6).clearContent();} catch(e) {Logger.log("error");}
    if (rows==null||rows=="") {Browser.msgBox("Oops, no data"); return false;}
    range=sheet.getRange(2,1,rows.length,5); range.setValues(rows);
  }
}
</code>```

Here the file
https://docs.google.com/spreadsheets/d/17lDKTVgqw99zqXYtuWHT3FgH7ahyyIqgGxgd4wld8cw/edit?usp=sharing

Thank you

答:
How about this answer?

Modification points:

I think that the reason of your issue is due to the difference structure between the object retrieved from https://api.hitbtc.com/api/2/public/ticker and the object retrieved from https://api.kucoin.com/api/v1/market/allTickers.

At the former, the data array can be directly from obj_array.

At the latter, the data array is included in obj_array.data.ticker.

When this is reflected to your script, please modify your function of kuticker() as follows.

Modified script:

From:

```<code>obj_array=JSON.parse(UrlFetchApp.fetch("https://api.kucoin.com/api/v1/market/allTickers").getContentText());
</code>```

To:

```<code>obj_array = JSON.parse(UrlFetchApp.fetch("https://api.kucoin.com/api/v1/market/allTickers").getContentText()).data.ticker;
</code>```

Result:

When above modified script is run, the following result can be obtained.

Body:
I manage to get data from https://api.hitbtc.com/api/2/public/ticker to my Google Spreadsheet using this code script

    function ticker(){
  var rows=[],obj_array=null;
  try {obj_array=JSON.parse(UrlFetchApp.fetch("https://api.hitbtc.com/api/2/public/ticker").getContentText());} catch (e) {obj_array=null;}
  if (obj_array!=null){
    for (r in obj_array) {rows.push([obj_array[r].symbol,parseFloat(obj_array[r].last),parseFloat(obj_array[r].volume),parseFloat(obj_array[r].ask),parseFloat(obj_array[r].bid)]);}
    var ss=SpreadsheetApp.getActiveSpreadsheet(),sheet=ss.getSheetByName('Hitbtc');ss.getRange("Hitbtc!A1").setValue(new Date());
    try {var range=sheet.getRange(2,1,sheet.getLastRow(),6).clearContent();} catch(e) {Logger.log("error");}
    if (rows==null||rows=="") {Browser.msgBox("Oops, no data"); return false;}
    range=sheet.getRange(2,1,rows.length,5); range.setValues(rows);
  }
}

Then I try another API from https://api.kucoin.com/api/v1/market/allTickers, I can't manage to get the data.Always show #NUM!. Can someone help me?

function kuticker(){
  var rows=[],obj_array=null;
  try {obj_array=JSON.parse(UrlFetchApp.fetch("https://api.kucoin.com/api/v1/market/allTickers").getContentText());} catch (e) {obj_array=null;}
  if (obj_array!=null){
    for (r in obj_array) {rows.push([obj_array[r].symbol,parseFloat(obj_array[r].last),parseFloat(obj_array[r].vol),parseFloat(obj_array[r].buy),parseFloat(obj_array[r].sell)]);}
    var ss=SpreadsheetApp.getActiveSpreadsheet(),sheet=ss.getSheetByName('Kucoin');ss.getRange("Kucoin!A1").setValue(new Date());
    try {var range=sheet.getRange(2,1,sheet.getLastRow(),6).clearContent();} catch(e) {Logger.log("error");}
    if (rows==null||rows=="") {Browser.msgBox("Oops, no data"); return false;}
    range=sheet.getRange(2,1,rows.length,5); range.setValues(rows);
  }
}

Here the file
https://docs.google.com/spreadsheets/d/17lDKTVgqw99zqXYtuWHT3FgH7ahyyIqgGxgd4wld8cw/edit?usp=sharing

Thank you

Body:
How about this answer?

Modification points:

I think that the reason of your issue is due to the difference structure between the object retrieved from https://api.hitbtc.com/api/2/public/ticker and the object retrieved from https://api.kucoin.com/api/v1/market/allTickers.

At the former, the data array can be directly from obj_array.

At the latter, the data array is included in obj_array.data.ticker.

When this is reflected to your script, please modify your function of kuticker() as follows.

Modified script:

From:

obj_array=JSON.parse(UrlFetchApp.fetch("https://api.kucoin.com/api/v1/market/allTickers").getContentText());

To:

obj_array = JSON.parse(UrlFetchApp.fetch("https://api.kucoin.com/api/v1/market/allTickers").getContentText()).data.ticker;

Result:

When above modified script is run, the following result can be obtained.


问:
Run spark-shell command in shell script
```<code>#!/bin/sh
spark-shell
import org.apache.spark.sql.SparkSession
val url="jdbc:mysql://localhost:3306/slow_and_tedious"
val prop = new java.util.Properties
prop.setProperty("user",”scalauser”)
prop.setProperty("password","scalauser123")
val people = spark.read.jdbc(url,"sat",prop)
</code>```

The above commands are used to make a connection between Mysql and Spark using JDBC.
But instead of writing these commands everytime I thought of make a script but when I run the above script it throws this error.

答:
Try this,

Write your code in a filex.txt

In your unix shell script include the following

```<code>cat filex.txt | spark-shell
</code>```

Seemingly, you cant push the script in Background (using &)

Title: Run spark-shell command in shell script

Body:
#!/bin/sh
spark-shell
import org.apache.spark.sql.SparkSession
val url="jdbc:mysql://localhost:3306/slow_and_tedious"
val prop = new java.util.Properties
prop.setProperty("user",”scalauser”)
prop.setProperty("password","scalauser123")
val people = spark.read.jdbc(url,"sat",prop)

The above commands are used to make a connection between Mysql and Spark using JDBC.
But instead of writing these commands everytime I thought of make a script but when I run the above script it throws this error.

Body:
Try this,

Write your code in a filex.txt

In your unix shell script include the following

cat filex.txt | spark-shell

Seemingly, you cant push the script in Background (using &)


问:
Why do I get the proper URL response from a browser, but empty within Android's "HttpGet"?
I am writing an android application which uses a REST-based API on the server. So far the login works perfectly using HttpGet = I send the credentials, it sends me back a JSON response object containing session id or failure. I then moved onto using another get api (this one is passed the sessionid) and the response I get back looks like a valid one "200 - Ok" but the response body contains nothing - 0 text.

If I take the same URL and drop it into a browser, I get all the JSON text I expect displayed in the browser window. So what is the difference between a browser request/response and that of HttpGet? Any clues as to why my HttpGet might return a 'valid' nothing?

答:
I had the same problem. Setting user agent solved my problem:</p>

```<code>HttpParams params = new BasicHttpParams();
...
params.setParameter(CoreProtocolPNames.USER_AGENT, "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.71");
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I had the same problem. Setting user agent solved my problem:

HttpParams params = new BasicHttpParams();
...
params.setParameter(CoreProtocolPNames.USER_AGENT, "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.71");


问:
How does mongoose's find() function hold on to its execution and wait for a later function in its chain to complete first?
I was going through some tutorial materials and I notice that in Mongoose, I could somehow defer the final execution of a promise in it but I wonder how that is done.

For example, I can call the find function and it returns the promise of the result likes so:

```<code>const blogs = await Blog.find({id : '123'});
</code>```

The find() function in mongoose calls the exec() function in the Query object to complete the query and return the result, like in the line of this file.

Then, let's say that I have the following modifications to the prototype of the Mongoose Query object to see whether I should retrieve data from cache or from Mongo:

```<code>mongoose.Query.prototype.cache = function() {
   this.useCache = true;
   return this;
}

mongoose.Query.prototype.exec = async function() {
   if (!this.useCache) {    // <-- Apparently, I don't understand how this.useCache can be true if this.cache() was called
      this.exec.apply(this, arguments);
    }
    return 'some cached value';
    return this;
}

// Somehow, the find() section of the chaining is capable of waiting for cache() which is called later to complete to know that useCache is true! But how is that done?
const blogs = await Blog.find({id : '123'}).cache();  // <-- how did this mange to return 'some cached value'?
</code>```

However, since exec() is already called and evaluated in find() which is executed before the cache() function in the chain, how could this.useCache still be eventually evaluated in the exec() function finally when it resolves?

Unless there are some ways to wait until everything else down the chain have finished executing, in this case find() waited for cache() to finish executing, I would have expected this.useCache to always be undefined, wouldn't it?

I thought it's pretty amazing and would actually like to know how to implement a similar kind of chaining that is capable of somehow deferring the final action until all the functions in the later part of the chain to complete before resolving a result.

Note:
The above examples are my simplified version of the actual code for readability sake. The links to their actual files can be seen here and here.

答:
The find() function in mongoose calls the exec() function in the Query object to complete the query and return the result, like in the line of this file.

Actually no, it doesn't, at least not in your case. See the comment from three lines above:

```<code>// if we don't have a callback, then just return the query object
</code>```

The .exec() method is only called by find(…, callback) if you pass a callback. When using promises, you don't.

Instead, the exec method is called by the then() method of the query which makes the query thenable, and which gets used when you await the query object.

Body:
I was going through some tutorial materials and I notice that in Mongoose, I could somehow defer the final execution of a promise in it but I wonder how that is done.

For example, I can call the find function and it returns the promise of the result likes so:

const blogs = await Blog.find({id : '123'});

The find() function in mongoose calls the exec() function in the Query object to complete the query and return the result, like in the line of this file.

Then, let's say that I have the following modifications to the prototype of the Mongoose Query object to see whether I should retrieve data from cache or from Mongo:

mongoose.Query.prototype.cache = function() {
   this.useCache = true;
   return this;
}

mongoose.Query.prototype.exec = async function() {
   if (!this.useCache) {    // <-- Apparently, I don't understand how this.useCache can be true if this.cache() was called
      this.exec.apply(this, arguments);
    }
    return 'some cached value';
    return this;
}

// Somehow, the find() section of the chaining is capable of waiting for cache() which is called later to complete to know that useCache is true! But how is that done?
const blogs = await Blog.find({id : '123'}).cache();  // <-- how did this mange to return 'some cached value'?

However, since exec() is already called and evaluated in find() which is executed before the cache() function in the chain, how could this.useCache still be eventually evaluated in the exec() function finally when it resolves?

Unless there are some ways to wait until everything else down the chain have finished executing, in this case find() waited for cache() to finish executing, I would have expected this.useCache to always be undefined, wouldn't it?

I thought it's pretty amazing and would actually like to know how to implement a similar kind of chaining that is capable of somehow deferring the final action until all the functions in the later part of the chain to complete before resolving a result.

Note:
The above examples are my simplified version of the actual code for readability sake. The links to their actual files can be seen here and here.

Body:
The find() function in mongoose calls the exec() function in the Query object to complete the query and return the result, like in the line of this file.

Actually no, it doesn't, at least not in your case. See the comment from three lines above:

// if we don't have a callback, then just return the query object

The .exec() method is only called by find(…, callback) if you pass a callback. When using promises, you don't.

Instead, the exec method is called by the then() method of the query which makes the query thenable, and which gets used when you await the query object.


问:
MVC get data from controller to view using AJAX what's wrong?
i'm trying to get data from controller to view and receiving it with ajax this my action :

```<code>public JsonResult addtocart(int id)
    {
        var Product = db.Product.SingleOrDefault(c => c.id == id);
        var Cart = new Cart();

        ProductCart pc = new ProductCart()
        {

            Product = Product,
            Cart = Cart

        };
        pc.Cart.added_at = DateTime.Now;

        pc.Cart.product_id = pc.Product.id;
        db.Cart.Add(pc.Cart);
        db.SaveChanges();
        return Json(pc.Product, JsonRequestBehavior.AllowGet);
    }
</code>```

when i press on "add to cart" button for one of the products and i want to add this to a modal contains a table it's class is "myjxT", Here's my ajax :

```<code>$('.addtocart').click(function () {
        var name = $(".item-name").text();
        var price = $(".item-price").text();
        $.ajax({
            method :'GET',
            url: "/Product/addtocart",
            dataType: JSON,
            cache: false,
            data: { "Name": name, "Price": price },
            success: function (data) {
                var content = "";
                for (var x in data) {
                    content = "<tr><td>" + data[x].Name + "</td><td>" + data[x].Price + "</td></tr>"

                }
                $(".myjxT").html(content);

            },
            error: function (msg) {
                alert("something wrong");
            }

        });

    });
</code>```

but it does nothing just when i click to "add to cart "it directs me to this url : "Product/addtocart/35" where 35 is the product id,And the page contains json object of the product :

```<code>{"Category":{"id":11,"name":"kikii","number_of_products":3},"id":35,"name":"Samsung Galaxy M31","price":8000,"image":"Samsung Galaxy M31.jpg","description":"t is a long established ","CategoryId":11}
</code>```

this is the "add to cart " button which is inside a foreach loop:

```<code> @Html.ActionLink("Add to cart", "addtocart", new { id = item.id }, new { @class = "btn btn-danger addtocart", @style = "width:90px;background-color:rgb(60, 60, 60)" })
</code>```

答:
The reason why you are receiving an AJAX error is because your parameters in your controller method does not match the parameters you have in your AJAX call.

```<code>public JsonResult addtocart(int id)

data: { "Name": name, "Price": price },
</code>```

You need to pass the product id in the AJAX call.

e.g.

```<code>data: { "id": productid },
</code>```

Body:
i'm trying to get data from controller to view and receiving it with ajax this my action :

public JsonResult addtocart(int id)
    {
        var Product = db.Product.SingleOrDefault(c => c.id == id);
        var Cart = new Cart();

        ProductCart pc = new ProductCart()
        {

            Product = Product,
            Cart = Cart

        };
        pc.Cart.added_at = DateTime.Now;

        pc.Cart.product_id = pc.Product.id;
        db.Cart.Add(pc.Cart);
        db.SaveChanges();
        return Json(pc.Product, JsonRequestBehavior.AllowGet);
    }

when i press on "add to cart" button for one of the products and i want to add this to a modal contains a table it's class is "myjxT", Here's my ajax :

$('.addtocart').click(function () {
        var name = $(".item-name").text();
        var price = $(".item-price").text();
        $.ajax({
            method :'GET',
            url: "/Product/addtocart",
            dataType: JSON,
            cache: false,
            data: { "Name": name, "Price": price },
            success: function (data) {
                var content = "";
                for (var x in data) {
                    content = "
" + data[x].Name + "	" + data[x].Price + "
"

                }
                $(".myjxT").html(content);

            },
            error: function (msg) {
                alert("something wrong");
            }

        });

    });

but it does nothing just when i click to "add to cart "it directs me to this url : "Product/addtocart/35" where 35 is the product id,And the page contains json object of the product :

{"Category":{"id":11,"name":"kikii","number_of_products":3},"id":35,"name":"Samsung Galaxy M31","price":8000,"image":"Samsung Galaxy M31.jpg","description":"t is a long established ","CategoryId":11}

this is the "add to cart " button which is inside a foreach loop:

 @Html.ActionLink("Add to cart", "addtocart", new { id = item.id }, new { @class = "btn btn-danger addtocart", @style = "width:90px;background-color:rgb(60, 60, 60)" })

Body:
The reason why you are receiving an AJAX error is because your parameters in your controller method does not match the parameters you have in your AJAX call.

public JsonResult addtocart(int id)

data: { "Name": name, "Price": price },

You need to pass the product id in the AJAX call.

e.g.

data: { "id": productid },


答:
This could be a way - or you use the msgID as Ident for nested - than you can erase with del room_msg[msg]</p>

```<code>def search_and_delete(msg):
    count = 0
    for x in room_msg:
        if x['msgID'] == msg:
            room_msg.pop(count)
        count+=1
</code>```

Title: How can I remove an object from array in python?

Body:
This could be a way - or you use the msgID as Ident for nested - than you can erase with del room_msg[msg]

def search_and_delete(msg):
    count = 0
    for x in room_msg:
        if x['msgID'] == msg:
            room_msg.pop(count)
        count+=1


问:
How to create an array for storing x and y coordinates in Python
I am trying to read the description of a polygon from a file and compute the area of the polygon according to the description.

So far my approach:

```<code>#Function for computing area of a polygen
def polygonArea(A):
    n = len(A)  # of corners
    area = 0.0
    j = n - 1
    for i in range(n):
        area += (A[0][j] + A[0][i]) * (A[1][j] - A[1][i])
    area = abs(area) / 2.0

#reading from the file and connecting the polygen in a vector array in terms of X and Y coordinates
file = input('Enter file name:')
with open(file, 'r') as f:
    file = f.read()
    fileContent =file
    A = [[],[]] #trying to create an vector of x and y ordinates
    xa = 0.0
    yb = 0.0
    data = ""
    if fileContent > data and data == "(":
        data.join(fileContent)
        if data == "N":
            data.join(fileContent)
            if data != ",":
                print("Description is wrong!")
            if file>temp:
                yb += temp
                A[1].append(yb) #Storing the value in y co ordinate of vector A
                A[0].append(xa) #Storing the value in x co ordinate of vector A
         if data == "W":
             data.join(fileContent)
             if data != ",":
                 print("Description is wrong!")
             if file > temp:
                 xa -= temp
                 A[1].append(yb)
                 A[0].append(xa)
        if data == "E":
            data.join(fileContent)
            if data != ",":
                print("Description is wrong!")
            if file > temp:
                xa += temp
                A[1].append(yb)
                A[0].append(xa)
        if data == "S":
            data.join(fileContent)
            if data != ",":
                print("Description is wrong!")
            if file > temp:
                xa -= temp
                A[1].append(yb)
                A[0].append(xa)

#If polygon is complete A CONDITION on completeion of polygen in c++ if(x.back()==0 && y.back()==0)
p= polygonArea(A)
print ("area = ",p)
</code>```

答:
Here is a complete solution.
First, we parse the data using a regex, finding the cardinal direction and step inside each pair of parentheses.

Then, we build the list of vertices. We start from [0, 0]. For each move, we calculate the coordinates of the new point by adding step * the direction vector corresponding to the cardinal direction. The last vertex should also be [0, 0].

To calculate the area, we zip the list of vertices with itself offset by one vertex to get pairs of adjacent vertices, and apply the traditionnal formula from there.

To recreate your sample data file:

```<code>data = '(N, 17.5), (E, 20.4), (S, 25), (E, 7.6), (S, 10), (W, 56), (N, 17.5), (E, 28)'
with open('data.txt', 'w') as f:
    f.write(data)
</code>```

```<code>import re

def vertices_from_data(data):
    directions = {'N': [0, 1], 'E': [1, 0], 'S': [0, -1], 'W': [-1, 0]}

    moves = re.findall(r'\(([NSEW]), ([\d.]+)\)', data)

    vertices = [[0, 0]]
    for card, step in moves:
        direction = directions[card]
        step = float(step)
        prev = vertices[-1]
        new = [prev[i] + step*direction[i] for i in [0, 1]]
        vertices.append(new)
    return vertices

def polygon_area(vertices):
    return 0.5 * abs(sum(v1[0]*v2[1]-v1[1]*v2[0] for v1, v2 in zip(vertices[1:], vertices[:-1])))

filename = 'data.txt'
with open(filename) as f:
    data = f.read()

vertices = vertices_from_data(data)
area = polygon_area(vertices)
print(area)
# 1280
</code>```

Body:
I am trying to read the description of a polygon from a file and compute the area of the polygon according to the description.

So far my approach:

#Function for computing area of a polygen
def polygonArea(A):
    n = len(A)  # of corners
    area = 0.0
    j = n - 1
    for i in range(n):
        area += (A[0][j] + A[0][i]) * (A[1][j] - A[1][i])
    area = abs(area) / 2.0

#reading from the file and connecting the polygen in a vector array in terms of X and Y coordinates
file = input('Enter file name:')
with open(file, 'r') as f:
    file = f.read()
    fileContent =file
    A = [[],[]] #trying to create an vector of x and y ordinates
    xa = 0.0
    yb = 0.0
    data = ""
    if fileContent > data and data == "(":
        data.join(fileContent)
        if data == "N":
            data.join(fileContent)
            if data != ",":
                print("Description is wrong!")
            if file>temp:
                yb += temp
                A[1].append(yb) #Storing the value in y co ordinate of vector A
                A[0].append(xa) #Storing the value in x co ordinate of vector A
         if data == "W":
             data.join(fileContent)
             if data != ",":
                 print("Description is wrong!")
             if file > temp:
                 xa -= temp
                 A[1].append(yb)
                 A[0].append(xa)
        if data == "E":
            data.join(fileContent)
            if data != ",":
                print("Description is wrong!")
            if file > temp:
                xa += temp
                A[1].append(yb)
                A[0].append(xa)
        if data == "S":
            data.join(fileContent)
            if data != ",":
                print("Description is wrong!")
            if file > temp:
                xa -= temp
                A[1].append(yb)
                A[0].append(xa)

#If polygon is complete A CONDITION on completeion of polygen in c++ if(x.back()==0 && y.back()==0)
p= polygonArea(A)
print ("area = ",p)

Body:
Here is a complete solution.
First, we parse the data using a regex, finding the cardinal direction and step inside each pair of parentheses.

Then, we build the list of vertices. We start from [0, 0]. For each move, we calculate the coordinates of the new point by adding step * the direction vector corresponding to the cardinal direction. The last vertex should also be [0, 0].

To calculate the area, we zip the list of vertices with itself offset by one vertex to get pairs of adjacent vertices, and apply the traditionnal formula from there.

To recreate your sample data file:

data = '(N, 17.5), (E, 20.4), (S, 25), (E, 7.6), (S, 10), (W, 56), (N, 17.5), (E, 28)'
with open('data.txt', 'w') as f:
    f.write(data)

import re

def vertices_from_data(data):
    directions = {'N': [0, 1], 'E': [1, 0], 'S': [0, -1], 'W': [-1, 0]}

    moves = re.findall(r'\(([NSEW]), ([\d.]+)\)', data)

    vertices = [[0, 0]]
    for card, step in moves:
        direction = directions[card]
        step = float(step)
        prev = vertices[-1]
        new = [prev[i] + step*direction[i] for i in [0, 1]]
        vertices.append(new)
    return vertices

def polygon_area(vertices):
    return 0.5 * abs(sum(v1[0]*v2[1]-v1[1]*v2[0] for v1, v2 in zip(vertices[1:], vertices[:-1])))

filename = 'data.txt'
with open(filename) as f:
    data = f.read()

vertices = vertices_from_data(data)
area = polygon_area(vertices)
print(area)
# 1280


问:
Is it absolutely necessary to load pointers to OpenGL functions
I started learning OpenGL from online tutorials and some of them have made use of glad and GLEW.
I read that it is necessary to load pointers to OpenGL functions either manually or with a loading library.

But some tutorials only use glut and no pointers are used to load the functions like glbegin

答:
There are two different parts of OpenGL you witnessed: The OpenGL legacy and modern api.
The tutorials you refer to as not using pointers are using the legacy functions, which are very simple, but also slow.

OpenGL legacy functions:

```<code>glBegin(GL_QUADS);
glVertex2d(-0.5, -0.5);
glVertex2d( 0.5, -0.5);
glVertex2d( 0.5,  0.5);
glVertex2d(-0.5,  0.5);
glEnd();
</code>```

Those functions are simple and slow: You basically send every single vertex to the GPU separately.

Modern pipeline: (Incomplete code sample from LearnOpenGL.com)

```<code>float vertices[] = {
    -0.5f, -0.5f, 0.0f, // left
     0.5f, -0.5f, 0.0f, // right
     0.0f,  0.5f, 0.0f  // top
};

unsigned int VBO, VAO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glBindVertexArray(VAO);

glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);

glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);

while(true) {

    glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);

    // draw our first triangle
    glUseProgram(shaderProgram);
    glBindVertexArray(VAO);
    glDrawArrays(GL_TRIANGLES, 0, 3);

    glfwSwapBuffers(window);
    glfwPollEvents();
}
</code>```

Using this modern pipeline you have all vertices already in an array and you send the whole array to the GPU with glBufferData(), which is what you meant with pointers - it's actually all just arrays.

This way all the data gets sent in one big chunk of data and all of those triangles are drawn with a single draw call: Using this method one can draw tens of thousands of triangles every frame!

But there is more: (Again, incomplete code sample from LearnOpenGL.com)

```<code>float vertices[] = {
     0.5f,  0.5f, 0.0f,  // top right
     0.5f, -0.5f, 0.0f,  // bottom right
    -0.5f, -0.5f, 0.0f,  // bottom left
    -0.5f,  0.5f, 0.0f   // top left
};
unsigned int indices[] = {  // note that we start from 0!
    0, 1, 3,  // first Triangle
    1, 2, 3   // second Triangle
};
unsigned int VBO, VAO, EBO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glGenBuffers(1, &EBO);
glBindVertexArray(VAO);

glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);

glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);

while (true) {

    glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);

    // draw our first triangle
    glUseProgram(shaderProgram);
    glBindVertexArray(VAO);
    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);

    glfwSwapBuffers(window);
    glfwPollEvents();
}
</code>```

This code is using vertex indexing, which is the commonly used method. Without this you would have to specify three vertices with all data for every triangle, meaning that if several faces use the same vertex, it is duplicated. But with this method you only specify all vertices once and in a separate index buffer you specify which faces should use which vertices, you basically say:
I want those vertices at those positions and then i want a triangle from vertex 1 to vertex 7 to vertex 89.

But back to the topic, the last method - index buffering - is the most widely used and probably the one you should also be using. Yes, it is a lot more complicated and you need vertex arrays, vertex buffers, index buffers, vertex shaders, fragment shaders and so on, but when taking a look at LearnOpenGL you can follow along these tutorials, they explain everything in detail and you can also take a look at the source code in the examples.

Also, you probably meant model loaders like for loading .obj files, but loading the model is independent from the rendering pipeline - you would also need that if you were using the legacy functions (which you shouldn't)

And there is no difference between glad and glut, theyre both headers providing the OpenGL functions - just different projects with the same functionality

Body:
There are two different parts of OpenGL you witnessed: The OpenGL legacy and modern api.
The tutorials you refer to as not using pointers are using the legacy functions, which are very simple, but also slow.

OpenGL legacy functions:

glBegin(GL_QUADS);
glVertex2d(-0.5, -0.5);
glVertex2d( 0.5, -0.5);
glVertex2d( 0.5,  0.5);
glVertex2d(-0.5,  0.5);
glEnd();

Those functions are simple and slow: You basically send every single vertex to the GPU separately.

Modern pipeline: (Incomplete code sample from LearnOpenGL.com)

float vertices[] = {
    -0.5f, -0.5f, 0.0f, // left
     0.5f, -0.5f, 0.0f, // right
     0.0f,  0.5f, 0.0f  // top
};

unsigned int VBO, VAO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glBindVertexArray(VAO);

glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);

glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);

while(true) {

    glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);

    // draw our first triangle
    glUseProgram(shaderProgram);
    glBindVertexArray(VAO);
    glDrawArrays(GL_TRIANGLES, 0, 3);

    glfwSwapBuffers(window);
    glfwPollEvents();
}

Using this modern pipeline you have all vertices already in an array and you send the whole array to the GPU with glBufferData(), which is what you meant with pointers - it's actually all just arrays.

This way all the data gets sent in one big chunk of data and all of those triangles are drawn with a single draw call: Using this method one can draw tens of thousands of triangles every frame!

But there is more: (Again, incomplete code sample from LearnOpenGL.com)

float vertices[] = {
     0.5f,  0.5f, 0.0f,  // top right
     0.5f, -0.5f, 0.0f,  // bottom right
    -0.5f, -0.5f, 0.0f,  // bottom left
    -0.5f,  0.5f, 0.0f   // top left
};
unsigned int indices[] = {  // note that we start from 0!
    0, 1, 3,  // first Triangle
    1, 2, 3   // second Triangle
};
unsigned int VBO, VAO, EBO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glGenBuffers(1, &EBO);
glBindVertexArray(VAO);

glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);

glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);

while (true) {

    glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);

    // draw our first triangle
    glUseProgram(shaderProgram);
    glBindVertexArray(VAO);
    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);

    glfwSwapBuffers(window);
    glfwPollEvents();
}

This code is using vertex indexing, which is the commonly used method. Without this you would have to specify three vertices with all data for every triangle, meaning that if several faces use the same vertex, it is duplicated. But with this method you only specify all vertices once and in a separate index buffer you specify which faces should use which vertices, you basically say:
I want those vertices at those positions and then i want a triangle from vertex 1 to vertex 7 to vertex 89.

But back to the topic, the last method - index buffering - is the most widely used and probably the one you should also be using. Yes, it is a lot more complicated and you need vertex arrays, vertex buffers, index buffers, vertex shaders, fragment shaders and so on, but when taking a look at LearnOpenGL you can follow along these tutorials, they explain everything in detail and you can also take a look at the source code in the examples.

Also, you probably meant model loaders like for loading .obj files, but loading the model is independent from the rendering pipeline - you would also need that if you were using the legacy functions (which you shouldn't)

And there is no difference between glad and glut, theyre both headers providing the OpenGL functions - just different projects with the same functionality


问:
getting output of multiple ec2 instances (tag name and Private ip) in Terraform
in my main.tf i am creating multiple ec2 instances with diff tags like this

```<code> `resource "aws_instance" "AMZ-TRN01-V-APP" {`
  `ami                     = var.linux_ami[var.region]`
  `instance_type           = var.app_instance_type`
  `key_name                = var.linux_key_name`
  `vpc_security_group_ids  = [var.vpc_security_group_ids[var.region]]`
  `subnet_id               = var.subnetid`
  `count                   = var.app_count`
  `tags = {`
  `Name        = "AMZ-TRN01-V-APP-${format("%02d", count.index + 1)}"`
  `Environment = var.env_tag`
  `}`
  `} `
 `resource "aws_instance" "AMZ-TRN01-V-DB" {`
 `ami                     = var.linux_ami[var.region]`
 `instance_type           = var.db.instance_type`
 `key_name                = var.linux_key_name`
 `vpc_security_group_ids  = [var.vpc_security_group_ids[var.region]]`
 `subnet_id               = var.subnetid`
 `count                   = var.db_count `
 `tags = {`
 `Name        = "AMZ-TRN01-V-DB-${format("%02d", count.index + 1)}"`
 `Environment = var.env_tag`
 ` }`
 `}`
</code>```

in my outputs.tf i have

```<code>`output "tags" {`
`description = "List of tags of instances"`
`value       = aws_instance.AMZ-TRN01-V-APP.*.tags.Name`
`}`
`output "private_ip" {`
`description = "List of private IP addresses assigned to the instances"`
`value       = aws_instance.AMZ-TRN01-V-APP.*.private_ip`
`}`
</code>```

How do i get the tag and private ip for AMZ-TRN01-V-DB servers in the same output?

Thanks

答:
You can combine the output from AMZ-TRN01-V-APP and AMZ-TRN01-V-DB into a list as follows for the ip addresses:

```<code>output "private_ips" {
description = "List of private IP addresses assigned to the DB and APP instances"
value       = [aws_instance.AMZ-TRN01-V-APP.*.private_ip,
               aws_instance.AMZ-TRN01-V-DB.*.private_ip]
}
</code>```

The same applies for the tags:

```<code>output "tags" {
description = "List of tags of the APP and DB instances"
value       = [aws_instance.AMZ-TRN01-V-APP.*.tags.Name,
               aws_instance.AMZ-TRN01-V-DB.*.tags.Name]
}
</code>```

Body:
in my main.tf i am creating multiple ec2 instances with diff tags like this

 `resource "aws_instance" "AMZ-TRN01-V-APP" {`
  `ami                     = var.linux_ami[var.region]`
  `instance_type           = var.app_instance_type`
  `key_name                = var.linux_key_name`
  `vpc_security_group_ids  = [var.vpc_security_group_ids[var.region]]`
  `subnet_id               = var.subnetid`
  `count                   = var.app_count`
  `tags = {`
  `Name        = "AMZ-TRN01-V-APP-${format("%02d", count.index + 1)}"`
  `Environment = var.env_tag`
  `}`
  `} `
 `resource "aws_instance" "AMZ-TRN01-V-DB" {`
 `ami                     = var.linux_ami[var.region]`
 `instance_type           = var.db.instance_type`
 `key_name                = var.linux_key_name`
 `vpc_security_group_ids  = [var.vpc_security_group_ids[var.region]]`
 `subnet_id               = var.subnetid`
 `count                   = var.db_count `
 `tags = {`
 `Name        = "AMZ-TRN01-V-DB-${format("%02d", count.index + 1)}"`
 `Environment = var.env_tag`
 ` }`
 `}`

in my outputs.tf i have

`output "tags" {`
`description = "List of tags of instances"`
`value       = aws_instance.AMZ-TRN01-V-APP.*.tags.Name`
`}`
`output "private_ip" {`
`description = "List of private IP addresses assigned to the instances"`
`value       = aws_instance.AMZ-TRN01-V-APP.*.private_ip`
`}`

How do i get the tag and private ip for AMZ-TRN01-V-DB servers in the same output?

Thanks

Body:
You can combine the output from AMZ-TRN01-V-APP and AMZ-TRN01-V-DB into a list as follows for the ip addresses:

output "private_ips" {
description = "List of private IP addresses assigned to the DB and APP instances"
value       = [aws_instance.AMZ-TRN01-V-APP.*.private_ip,
               aws_instance.AMZ-TRN01-V-DB.*.private_ip]
}

The same applies for the tags:

output "tags" {
description = "List of tags of the APP and DB instances"
value       = [aws_instance.AMZ-TRN01-V-APP.*.tags.Name,
               aws_instance.AMZ-TRN01-V-DB.*.tags.Name]
}


问:
Why do I get memory leaks while properly deallocating memory?
That's all the code with allocation and deallocation

Constructor

```<code> Event::Event(){
    setEmpty();
}
</code>```

Destructor

```<code>    Event::~Event(){
    delete [] event_description;
}
</code>```

Copy constructor

```<code>Event::Event(const Event& Event){
      if (Event.event_description == nullptr) {
          event_description = nullptr;

      } else {
           event_description = new char[strlen(Event.event_description)+1];
          strcpy(event_description, Event.event_description);

      }
    time_in_sec = Event.time_in_sec;
}
</code>```

Copy assignment operator

```<code>Event& Event::operator=(const Event& Event){
    delete [] event_description;
    if (Event.event_description == nullptr) {
        event_description = nullptr;

    } else {
         event_description = new char[strlen(Event.event_description)+1];
        strcpy(event_description, Event.event_description);
    }

 time_in_sec = Event.time_in_sec;

    return *this;
}
</code>```

Function that sets description in further development.
The main task is to dynamically allocate memory for the event description. I get memory leaks while checking through valgrind

```<code>void Event::setDescription(const char* new_desc){
    if (new_desc == nullptr || new_desc[0] == '\0') {

        event_description = nullptr;
        time_in_sec = 0;
    } else {
        event_description = new char[strlen(new_desc)+1];
        strcpy(event_description, new_desc);
        time_in_sec = g_sysClock;
    }
}
</code>```

答:
This function

```<code>void Event::setDescription(const char* new_desc){
    if (new_desc == nullptr || new_desc[0] == '\0') {

        event_description = nullptr;
        time_in_sec = 0;
    } else {
        event_description = new char[strlen(new_desc)+1];
        strcpy(event_description, new_desc);
        time_in_sec = g_sysClock;
    }
}
</code>```

produces memory leaks. It does not delete the previous allocated memory the address to which is stored in the data member event_description.

It should be defined at least like

```<code>void Event::setDescription(const char* new_desc){
    delete [] event_description;

    if (new_desc == nullptr || new_desc[0] == '\0') {
        event_description = nullptr;
        time_in_sec = 0;
    } else {
        event_description = new char[strlen(new_desc)+1];
        strcpy(event_description, new_desc);
        time_in_sec = g_sysClock;
    }
}
</code>```

A more safer approach can look like

```<code>void Event::setDescription(const char* new_desc){
    if (new_desc == nullptr || new_desc[0] == '\0') {
        delete [] event_description;
        event_description = nullptr;
        time_in_sec = 0;
    } else {
        char *tmp = new char[strlen(new_desc)+1];
        delete [] event_description;
        event_description = tmp;
        strcpy(event_description, new_desc);
        time_in_sec = g_sysClock;
    }
}
</code>```

Body:
That's all the code with allocation and deallocation

Constructor

 Event::Event(){
    setEmpty();
}

Destructor

    Event::~Event(){
    delete [] event_description;
}

Copy constructor

Event::Event(const Event& Event){
      if (Event.event_description == nullptr) {
          event_description = nullptr;

      } else {
           event_description = new char[strlen(Event.event_description)+1];
          strcpy(event_description, Event.event_description);

      }
    time_in_sec = Event.time_in_sec;
}

Copy assignment operator

Event& Event::operator=(const Event& Event){
    delete [] event_description;
    if (Event.event_description == nullptr) {
        event_description = nullptr;

    } else {
         event_description = new char[strlen(Event.event_description)+1];
        strcpy(event_description, Event.event_description);
    }

 time_in_sec = Event.time_in_sec;

    return *this;
}

Function that sets description in further development.
The main task is to dynamically allocate memory for the event description. I get memory leaks while checking through valgrind

void Event::setDescription(const char* new_desc){
    if (new_desc == nullptr || new_desc[0] == '\0') {

        event_description = nullptr;
        time_in_sec = 0;
    } else {
        event_description = new char[strlen(new_desc)+1];
        strcpy(event_description, new_desc);
        time_in_sec = g_sysClock;
    }
}

Body:
This function

void Event::setDescription(const char* new_desc){
    if (new_desc == nullptr || new_desc[0] == '\0') {

        event_description = nullptr;
        time_in_sec = 0;
    } else {
        event_description = new char[strlen(new_desc)+1];
        strcpy(event_description, new_desc);
        time_in_sec = g_sysClock;
    }
}

produces memory leaks. It does not delete the previous allocated memory the address to which is stored in the data member event_description.

It should be defined at least like

void Event::setDescription(const char* new_desc){
    delete [] event_description;

    if (new_desc == nullptr || new_desc[0] == '\0') {
        event_description = nullptr;
        time_in_sec = 0;
    } else {
        event_description = new char[strlen(new_desc)+1];
        strcpy(event_description, new_desc);
        time_in_sec = g_sysClock;
    }
}

A more safer approach can look like

void Event::setDescription(const char* new_desc){
    if (new_desc == nullptr || new_desc[0] == '\0') {
        delete [] event_description;
        event_description = nullptr;
        time_in_sec = 0;
    } else {
        char *tmp = new char[strlen(new_desc)+1];
        delete [] event_description;
        event_description = tmp;
        strcpy(event_description, new_desc);
        time_in_sec = g_sysClock;
    }
}


问:
Usage of Openlayers in Django
It's been few days i'm trying to make Openlayers work with my Django web site.
I'm totally a noob in Web, so I might miss straightforward stuff that I'm not able to understand, yet.

From what I understand, I need to load Openlayers, so for this in my index.html,  I've added in the  this :

```<code><script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.3.1/build/ol.js"></script>
</code>```

Then in the  I've added the index.js where I would like to work with openlayers:

```<code><script src="{% static 'index.js'%}"></script>
</code>```

I've copy paste a simple example in the index.js and it's been working correctly.

```<code>var map = new ol.Map({
    target: 'map',
    layers: [
      new ol.layer.Tile({
        source: new ol.source.OSM()
      })
    ],
    view: new ol.View({
      center: ol.proj.fromLonLat([2.333333, 48.866667]),
      zoom: 10

    })
});
</code>```

So I have a map centered on Paris. Now I would like to load a GeoJson file, thus I need to add a Layer containing the GeoJon. For this I've followed an example here.

Here is my first problem I tried to import like this : import GeoJSON from 'ol/format/GeoJSON';
or like this import Style from ol.style.Style bit I got this error : Uncaught SyntaxError: Cannot use import statement outside a module
The only solution I found was to new ol.style.Style(...) when I needed to use it. Ugly, but working.

So I've delete all the import and used the full path of each class to call the constructors. Until one of them would not work.

```<code>var vectorLayer = new ol.layer.Vector.VectorLayer({
  source: new ol.source.Vector.VectorSource({
    url: 'data/geojson/countries.geojson',
    format: new ol.format.GeoJSON()
  }),
  style: function(feature) {
    style.getText().setText(feature.get('name'));
    return style;
  }
});
</code>```

Uncaught TypeError: ol.source.Vector.VectorSource is not a constructor

https://openlayers.org/en/latest/apidoc/module-ol_source_Vector-VectorSource.html

So I'm asking my self why it is not working, and how is it possible to make it less ugly (to use the Imports)

答:
```<code>var vectorLayer = new ol.layer.Vector({
  source: new ol.source.Vector({
</code>```

<p>You can check the OpenLayers 4 examples https://openlayers.org/en/v4.6.5/examples/ for full build syntax </p>

Title: Usage of Openlayers in Django

Body:
It's been few days i'm trying to make Openlayers work with my Django web site.
I'm totally a noob in Web, so I might miss straightforward stuff that I'm not able to understand, yet.

From what I understand, I need to load Openlayers, so for this in my index.html,  I've added in the  this :

Then in the  I've added the index.js where I would like to work with openlayers:

I've copy paste a simple example in the index.js and it's been working correctly.

var map = new ol.Map({
    target: 'map',
    layers: [
      new ol.layer.Tile({
        source: new ol.source.OSM()
      })
    ],
    view: new ol.View({
      center: ol.proj.fromLonLat([2.333333, 48.866667]),
      zoom: 10

    })
});

So I have a map centered on Paris. Now I would like to load a GeoJson file, thus I need to add a Layer containing the GeoJon. For this I've followed an example here.

Here is my first problem I tried to import like this : import GeoJSON from 'ol/format/GeoJSON';
or like this import Style from ol.style.Style bit I got this error : Uncaught SyntaxError: Cannot use import statement outside a module
The only solution I found was to new ol.style.Style(...) when I needed to use it. Ugly, but working.

So I've delete all the import and used the full path of each class to call the constructors. Until one of them would not work.

var vectorLayer = new ol.layer.Vector.VectorLayer({
  source: new ol.source.Vector.VectorSource({
    url: 'data/geojson/countries.geojson',
    format: new ol.format.GeoJSON()
  }),
  style: function(feature) {
    style.getText().setText(feature.get('name'));
    return style;
  }
});

Uncaught TypeError: ol.source.Vector.VectorSource is not a constructor

https://openlayers.org/en/latest/apidoc/module-ol_source_Vector-VectorSource.html

So I'm asking my self why it is not working, and how is it possible to make it less ugly (to use the Imports)

Body:
var vectorLayer = new ol.layer.Vector({
  source: new ol.source.Vector({

You can check the OpenLayers 4 examples https://openlayers.org/en/v4.6.5/examples/ for full build syntax


问:
Count decimal numbers in a string using the standard library
I have white-space separeted integers inside a string, e.g.:

```<code>std::string s = "1 2 33 444 0 5";
</code>```

The string is well-formed: just white-space separated numbers without any letters, new-lines, etc.

How to count the number of integers in the above string in an STL way? I am looking for something "short" that will use e.g. iterators or <algorithm>.

答:
This solution uses only the STL, has no loops, and will handle arbitrary number of leading, trailing, and extra whitespace:

```<code>std::string s = "1 2 33 444 0 5";
std::stringstream ss(s);

int const count = std::distance(std::istream_iterator<int>{ss},
                                std::istream_iterator<int>{});
</code>```

Here's a demo.

Body:
I have white-space separeted integers inside a string, e.g.:

std::string s = "1 2 33 444 0 5";

The string is well-formed: just white-space separated numbers without any letters, new-lines, etc.

How to count the number of integers in the above string in an STL way? I am looking for something "short" that will use e.g. iterators or <algorithm>.

Body:
This solution uses only the STL, has no loops, and will handle arbitrary number of leading, trailing, and extra whitespace:

std::string s = "1 2 33 444 0 5";
std::stringstream ss(s);

int const count = std::distance(std::istream_iterator<int>{ss},
                                std::istream_iterator<int>{});

Here's a demo.


问:
How can I refresh a child component from a parent component multiple times from the same method?
Right now my child component only updates once the GetLeads() method in the parent component is finished. I never see the spinner or Searching text.

Parent Component:

```<code><SearchResultComponent  @ref="ChildComponent"></SearchResultComponent>
</code>```

Code:

```<code> protected SearchResultComponent ChildComponent;
 public int LeadsFound { get; set; }
 public void GetLeads()
 {
      ChildComponent.Refresh(true, 0);
      var leads  = _searchService.Search(searchRequest);
      LeadsFound = leads?.Count ?? 0;
      _writeFileService.WriteToFile(leads);
      ChildComponent.Refresh(false, LeadsFound);
  }
</code>```

Child Component:

```<code>@code {

    public bool Searching { get; set; } = false;
    public int LeadsFound { get; set; } = 0;
    public void Refresh(bool searching, int leadsFound)
    {
        Searching = searching;
        LeadsFound = leadsFound;
        StateHasChanged();
    }
}

@if (Searching)
{
    <div>Searching...</div>
    <div>
        <img src="~/Content/searching-spinner.gif" />
    </div>
}
else
{
    <div>Leads Found: @LeadsFound</div>
}
</code>```

答:
my child component only updates once

You can make the eventhandler async. That allows you then to call Task.Delay(1) or Task.Yield() and that will effectuate the StateHasChanged().

The call form @onclick="@GetLeads" can remain the same. Note that you don't need the 2nd @ in there.

If your searchService.Search() was async then you wouldn't need Task.Yield()

```<code> public async Task GetLeads()
 {
      ChildComponent.Refresh(true, 0);
      await Task.Yield();  // enable the render thread to run.
      var leads  = _searchService.Search(searchRequest);
      LeadsFound = leads?.Count ?? 0;
      _writeFileService.WriteToFile(leads);
      ChildComponent.Refresh(false, LeadsFound);
  }
</code>```

Body:
Right now my child component only updates once the GetLeads() method in the parent component is finished. I never see the spinner or Searching text.

Parent Component:

<SearchResultComponent  @ref="ChildComponent"></SearchResultComponent>

Code:

 protected SearchResultComponent ChildComponent;
 public int LeadsFound { get; set; }
 public void GetLeads()
 {
      ChildComponent.Refresh(true, 0);
      var leads  = _searchService.Search(searchRequest);
      LeadsFound = leads?.Count ?? 0;
      _writeFileService.WriteToFile(leads);
      ChildComponent.Refresh(false, LeadsFound);
  }

Child Component:

@code {

    public bool Searching { get; set; } = false;
    public int LeadsFound { get; set; } = 0;
    public void Refresh(bool searching, int leadsFound)
    {
        Searching = searching;
        LeadsFound = leadsFound;
        StateHasChanged();
    }
}

@if (Searching)
{

Searching...

}
else
{

Leads Found: @LeadsFound

}

Body:
my child component only updates once

You can make the eventhandler async. That allows you then to call Task.Delay(1) or Task.Yield() and that will effectuate the StateHasChanged().

The call form @onclick="@GetLeads" can remain the same. Note that you don't need the 2nd @ in there.

If your searchService.Search() was async then you wouldn't need Task.Yield()

 public async Task GetLeads()
 {
      ChildComponent.Refresh(true, 0);
      await Task.Yield();  // enable the render thread to run.
      var leads  = _searchService.Search(searchRequest);
      LeadsFound = leads?.Count ?? 0;
      _writeFileService.WriteToFile(leads);
      ChildComponent.Refresh(false, LeadsFound);
  }


问:
Training 1D CNN in Pytorch
I want to train the model given below. I am developing 1D CNN model in PyTorch. Usually we use dataloaders in PyTorch. But I am not using dataloaders for my implementation. I need guidance on how i can train my model in pytorch.

```<code>import torch
import torch.nn as nn
import torch.nn.functional as F

class  CharCNN(nn.Module):
def __init__(self,num_labels=11):
    super(CharCNN, self).__init__()

    self.conv1 = nn.Sequential(
        nn.Conv1d(num_channels, depth_1, kernel_size=kernel_size_1, stride=stride_size),
        nn.ReLU(),
        nn.MaxPool1d(kernel_size=kernel_size_1, stride=stride_size),
        nn.Dropout(0.1),
    )

    self.conv2 = nn.Sequential(
        nn.Conv1d(depth_1, depth_2, kernel_size=kernel_size_2, stride=stride_size),
        nn.ReLU(),
        nn.MaxPool1d(kernel_size=kernel_size_2, stride=stride_size),
        nn.Dropout(0.25)
    )

    self.fc1 = nn.Sequential(
        nn.Linear(depth_2*kernel_size_2, num_hidden),
        nn.ReLU(),
        nn.Dropout(0.5)
    )

    self.fc2 = nn.Sequential(
        nn.Linear(num_hidden, num_labels),
        nn.ReLU(),
        nn.Dropout(0.5)
    )

def forward(self, x):
    out = self.conv1(x)
    out = self.conv2(out)

    # collapse
    out = x.view(x.size(0), -1)
    # linear layer
    out = self.fc1(out)
    # output layer
    out = self.fc2(out)
    #out = self.log_softmax(x,dim=1)

    return out
</code>```

I am training my network like this:

```<code>criterion = nn.CrossEntropyLoss()
opt = torch.optim.Adam(model.parameters(),lr=learning_rate)

for e in range(training_epochs):
  if(train_on_gpu):
     net.cuda()
    train_losses = []

   for batch in iterate_minibatches(train_x, train_y, batch_size):
      x, y = batch
      inputs, targets = torch.from_numpy(x), torch.from_numpy(y)
      if(train_on_gpu):
        inputs, targets = inputs.cuda(), targets.cuda()
      opt.zero_grad()
      output = model(inputs, batch_size)

    loss = criterion(output, targets.long())
    train_losses.append(loss.item())
    loss.backward()
    opt.step()
val_losses = []
accuracy=0
f1score=0
print("Epoch: {}/{}...".format(e+1, training_epochs),
              "Train Loss: {:.4f}...".format(np.mean(train_losses)))
</code>```

But i am getting the following error

```<code>          TypeError                                 Traceback (most recent call last)
          <ipython-input-60-3a3df06ef2f8> in <module>
   14             inputs, targets = inputs.cuda(), targets.cuda()
   15         opt.zero_grad()
   ---> 16         output = model(inputs, batch_size)
   17
   18         loss = criterion(output, targets.long())

   ~\AppData\Local\Continuum\anaconda3\lib\site-packages\torch\nn\modules\module.py in __call__(self,
   * input, **kwargs)
   530             result = self._slow_forward(*input, **kwargs)
   531         else:
   --> 532             result = self.forward(*input, **kwargs)
   533         for hook in self._forward_hooks.values():
   534             hook_result = hook(self, input, result)

   TypeError: forward() takes 2 positional arguments but 3 were given
</code>```

Please guide me how i can resolve this issue.

答:
The forward method of your model only takes one argument, but you are calling it with two arguments:

output = model(inputs, batch_size)
```

<p>It should be:</p>

<pre class="lang-py prettyprint-override"><code>output = model(inputs)
</code>```

Title: Training 1D CNN in Pytorch

Body:
I want to train the model given below. I am developing 1D CNN model in PyTorch. Usually we use dataloaders in PyTorch. But I am not using dataloaders for my implementation. I need guidance on how i can train my model in pytorch.

import torch
import torch.nn as nn
import torch.nn.functional as F

class  CharCNN(nn.Module):
def __init__(self,num_labels=11):
    super(CharCNN, self).__init__()

    self.conv1 = nn.Sequential(
        nn.Conv1d(num_channels, depth_1, kernel_size=kernel_size_1, stride=stride_size),
        nn.ReLU(),
        nn.MaxPool1d(kernel_size=kernel_size_1, stride=stride_size),
        nn.Dropout(0.1),
    )

    self.conv2 = nn.Sequential(
        nn.Conv1d(depth_1, depth_2, kernel_size=kernel_size_2, stride=stride_size),
        nn.ReLU(),
        nn.MaxPool1d(kernel_size=kernel_size_2, stride=stride_size),
        nn.Dropout(0.25)
    )

    self.fc1 = nn.Sequential(
        nn.Linear(depth_2*kernel_size_2, num_hidden),
        nn.ReLU(),
        nn.Dropout(0.5)
    )

    self.fc2 = nn.Sequential(
        nn.Linear(num_hidden, num_labels),
        nn.ReLU(),
        nn.Dropout(0.5)
    )

def forward(self, x):
    out = self.conv1(x)
    out = self.conv2(out)

    # collapse
    out = x.view(x.size(0), -1)
    # linear layer
    out = self.fc1(out)
    # output layer
    out = self.fc2(out)
    #out = self.log_softmax(x,dim=1)

    return out

I am training my network like this:

criterion = nn.CrossEntropyLoss()
opt = torch.optim.Adam(model.parameters(),lr=learning_rate)

for e in range(training_epochs):
  if(train_on_gpu):
     net.cuda()
    train_losses = []

   for batch in iterate_minibatches(train_x, train_y, batch_size):
      x, y = batch
      inputs, targets = torch.from_numpy(x), torch.from_numpy(y)
      if(train_on_gpu):
        inputs, targets = inputs.cuda(), targets.cuda()
      opt.zero_grad()
      output = model(inputs, batch_size)

    loss = criterion(output, targets.long())
    train_losses.append(loss.item())
    loss.backward()
    opt.step()
val_losses = []
accuracy=0
f1score=0
print("Epoch: {}/{}...".format(e+1, training_epochs),
              "Train Loss: {:.4f}...".format(np.mean(train_losses)))

But i am getting the following error

          TypeError                                 Traceback (most recent call last)
          <ipython-input-60-3a3df06ef2f8> in <module>
   14             inputs, targets = inputs.cuda(), targets.cuda()
   15         opt.zero_grad()
   ---> 16         output = model(inputs, batch_size)
   17
   18         loss = criterion(output, targets.long())

   ~\AppData\Local\Continuum\anaconda3\lib\site-packages\torch\nn\modules\module.py in __call__(self,
   * input, **kwargs)
   530             result = self._slow_forward(*input, **kwargs)
   531         else:
   --> 532             result = self.forward(*input, **kwargs)
   533         for hook in self._forward_hooks.values():
   534             hook_result = hook(self, input, result)

   TypeError: forward() takes 2 positional arguments but 3 were given

Please guide me how i can resolve this issue.

Body:
The forward method of your model only takes one argument, but you are calling it with two arguments:

output = model(inputs, batch_size)

It should be:

output = model(inputs)


问:
Multiple group_concat ordering one of them wrong order of the others
i have 3 columns a, b and c.

I need as output:

a

b as group_concat

c as group_concat (order ASC)

I can do a order by inside of the group_concat but the issue is that the order of b is not correct order for c them.

I never had that situation so i dont now how i can solve that.

答:
Is this what you are looking for:</p>

```<code>select a, group_concat(b order by c), group_concat(c order by c)
from t
group by a;
</code>```

Body:
Is this what you are looking for:

select a, group_concat(b order by c), group_concat(c order by c)
from t
group by a;