问:
Tensorflow: ValueError: Can't load save_path when it is None in single shot detection
I have just started working with tensorflow in python. I am trying to train Single shot detection using tensorflow for pascalvoc dataset. While creating tfrecords and during evaluation using VGG_VOC0712_SSD_300x300_ft_iter_120000.ckpt trained model there was no error. Whereas, when I am trying to train pascalvoc 2007 or 2012 datasets using ssd_300_vgg.ckpt pre-trained model I am getting following error.

```<code>2017-08-25 20:03:03.001268: I tensorflow/core/common_runtime gpu/gpu_device.cc:1045] Creating TensorFlow device (/gpu:0) -> (device: 0, name: Quadro M5000M, pci bus id: 0000:01:00.0)
INFO:tensorflow:Error reported to Coordinator: <type 'exceptions.ValueError'>, Can't load save_path when it is None.
Traceback (most recent call last):
  File "train_ssd_network.py", line 391, in <module>
    tf.app.run()
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/platform/app.py", line 48, in run
    _sys.exit(main(_sys.argv[:1] + flags_passthrough))
  File "train_ssd_network.py", line 387, in main
    sync_optimizer=None)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/slim/python/slim/learning.py", line 738, in train
    master, start_standard_services=False, config=session_config) as sess:
  File "/usr/lib/python2.7/contextlib.py", line 17, in __enter__
    return self.gen.next()
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/supervisor.py", line 965, in managed_session
    self.stop(close_summary_writer=close_summary_writer)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/supervisor.py", line 793, in stop
    stop_grace_period_secs=self._stop_grace_secs)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/coordinator.py", line 389, in join
    six.reraise(*self._exc_info_to_raise)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/supervisor.py", line 954, in managed_session
    start_standard_services=start_standard_services)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/supervisor.py", line 709, in prepare_or_wait_for_session
    init_feed_dict=self._init_feed_dict, init_fn=self._init_fn)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/session_manager.py", line 281, in prepare_session
    init_fn(sess)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/framework/python/ops/variables.py", line 660, in callback
    saver.restore(session, model_path)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/saver.py", line 1558, in restore
    raise ValueError("Can't load save_path when it is None.")
ValueError: Can't load save_path when it is None.
</code>```

I am using following script to fine-tune the model

```<code>DATASET_DIR=./tfrecords
TRAIN_DIR=./logs/
CHECKPOINT_PATH=./checkpoints/ssd_300_vgg.ckpt
python train_ssd_network.py \
    --train_dir=${TRAIN_DIR} \
    --dataset_dir=${DATASET_DIR} \
    --dataset_name=pascalvoc_2012 \
    --dataset_split_name=train \
    --model_name=ssd_300_vgg \
    --checkpoint_path=${CHECKPOINT_PATH} \
    --save_summaries_secs=60 \
    --save_interval_secs=600 \
    --weight_decay=0.0005 \
    --optimizer=adam \
    --learning_rate=0.001 \
    --batch_size=10
</code>```

The model ssd_300_vgg.ckpt is stored at the location ./checkpoints

Please let me know if anyone has the solution.

答:
Three suggestions:

Check the path when restoring the model

saver = tf.train.import_meta_graph(model_path)

Check the path when restoring the checkpoint

saver.restore(sess, tf.train.latest_checkpoint(cur_dir))

Check the parameters when saving the model

```<code>saver = tf.train.Saver(save_relative_paths=True)
</code>```

Body:
I have just started working with tensorflow in python. I am trying to train Single shot detection using tensorflow for pascalvoc dataset. While creating tfrecords and during evaluation using VGG_VOC0712_SSD_300x300_ft_iter_120000.ckpt trained model there was no error. Whereas, when I am trying to train pascalvoc 2007 or 2012 datasets using ssd_300_vgg.ckpt pre-trained model I am getting following error.

2017-08-25 20:03:03.001268: I tensorflow/core/common_runtime gpu/gpu_device.cc:1045] Creating TensorFlow device (/gpu:0) -> (device: 0, name: Quadro M5000M, pci bus id: 0000:01:00.0)
INFO:tensorflow:Error reported to Coordinator: <type 'exceptions.ValueError'>, Can't load save_path when it is None.
Traceback (most recent call last):
  File "train_ssd_network.py", line 391, in <module>
    tf.app.run()
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/platform/app.py", line 48, in run
    _sys.exit(main(_sys.argv[:1] + flags_passthrough))
  File "train_ssd_network.py", line 387, in main
    sync_optimizer=None)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/slim/python/slim/learning.py", line 738, in train
    master, start_standard_services=False, config=session_config) as sess:
  File "/usr/lib/python2.7/contextlib.py", line 17, in __enter__
    return self.gen.next()
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/supervisor.py", line 965, in managed_session
    self.stop(close_summary_writer=close_summary_writer)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/supervisor.py", line 793, in stop
    stop_grace_period_secs=self._stop_grace_secs)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/coordinator.py", line 389, in join
    six.reraise(*self._exc_info_to_raise)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/supervisor.py", line 954, in managed_session
    start_standard_services=start_standard_services)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/supervisor.py", line 709, in prepare_or_wait_for_session
    init_feed_dict=self._init_feed_dict, init_fn=self._init_fn)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/session_manager.py", line 281, in prepare_session
    init_fn(sess)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/framework/python/ops/variables.py", line 660, in callback
    saver.restore(session, model_path)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/saver.py", line 1558, in restore
    raise ValueError("Can't load save_path when it is None.")
ValueError: Can't load save_path when it is None.

I am using following script to fine-tune the model

DATASET_DIR=./tfrecords
TRAIN_DIR=./logs/
CHECKPOINT_PATH=./checkpoints/ssd_300_vgg.ckpt
python train_ssd_network.py \
    --train_dir=${TRAIN_DIR} \
    --dataset_dir=${DATASET_DIR} \
    --dataset_name=pascalvoc_2012 \
    --dataset_split_name=train \
    --model_name=ssd_300_vgg \
    --checkpoint_path=${CHECKPOINT_PATH} \
    --save_summaries_secs=60 \
    --save_interval_secs=600 \
    --weight_decay=0.0005 \
    --optimizer=adam \
    --learning_rate=0.001 \
    --batch_size=10

The model ssd_300_vgg.ckpt is stored at the location ./checkpoints

Please let me know if anyone has the solution.

Body:
Three suggestions:

Check the path when restoring the model

saver = tf.train.import_meta_graph(model_path)

Check the path when restoring the checkpoint

saver.restore(sess, tf.train.latest_checkpoint(cur_dir))

Check the parameters when saving the model

saver = tf.train.Saver(save_relative_paths=True)


来源: stackexchange

问:
DROP TRIGGER with ON ALL SERVER
I have a trigger to prevent someone using Management Studio:

```<code>CREATE TRIGGER [TR_LOGON_APP]
ON ALL SERVER
FOR LOGON
AS
BEGIN
   DECLARE @program_name NVARCHAR(128)
   DECLARE @host_name NVARCHAR(128)

   SELECT
       @program_name = program_name,
       @host_name = host_name
   FROM
       sys.dm_exec_sessions AS c
   WHERE
       c.session_id = @@spid

   IF @program_name LIKE '%Management%Studio%'
   BEGIN
       RAISERROR('Access Denied.',16,1)
       ROLLBACK;
   END
END;
</code>```

How to check that if it already exists, the trigger will be dropped first?

I have tried using :

```<code>IF EXISTS (SELECT * FROM sys.objects WHERE [name] = N'TR_LOGON_APP' AND [type] = 'TR')
BEGIN
      DROP TRIGGER [TR_LOGON_APP];
END;
</code>```

and

```<code>IF EXISTS (SELECT * FROM sys.objects WHERE [name] = N'TR_LOGON_APP' AND [type] = 'TR')
BEGIN
      DROP TRIGGER [TR_LOGON_APP] ON ALL SERVER;
END;
</code>```

But both return an error :

System.Data.OleDb.OleDbException (0x80040E14): There is already an object named 'TR_LOGON_APP' in the database.

答:
The sys.objects catalog view contains database objects, not server-level objects. Use sys.server_triggers instead:

```<code>IF EXISTS(SELECT 1 FROM sys.server_triggers WHERE name = N'TR_LOGON_APP')
BEGIN
    DROP TRIGGER TR_LOGON_APP ON ALL SERVER;
END;
</code>```

ContentLicense: CC BY-SA 3.0

Title: DROP TRIGGER with ON ALL SERVER

Body:
I have a trigger to prevent someone using Management Studio:

CREATE TRIGGER [TR_LOGON_APP]
ON ALL SERVER
FOR LOGON
AS
BEGIN
   DECLARE @program_name NVARCHAR(128)
   DECLARE @host_name NVARCHAR(128)

   SELECT
       @program_name = program_name,
       @host_name = host_name
   FROM
       sys.dm_exec_sessions AS c
   WHERE
       c.session_id = @@spid

   IF @program_name LIKE '%Management%Studio%'
   BEGIN
       RAISERROR('Access Denied.',16,1)
       ROLLBACK;
   END
END;

How to check that if it already exists, the trigger will be dropped first?

I have tried using :

IF EXISTS (SELECT * FROM sys.objects WHERE [name] = N'TR_LOGON_APP' AND [type] = 'TR')
BEGIN
      DROP TRIGGER [TR_LOGON_APP];
END;

and

IF EXISTS (SELECT * FROM sys.objects WHERE [name] = N'TR_LOGON_APP' AND [type] = 'TR')
BEGIN
      DROP TRIGGER [TR_LOGON_APP] ON ALL SERVER;
END;

But both return an error :

System.Data.OleDb.OleDbException (0x80040E14): There is already an object named 'TR_LOGON_APP' in the database.

Body:
The sys.objects catalog view contains database objects, not server-level objects. Use sys.server_triggers instead:

IF EXISTS(SELECT 1 FROM sys.server_triggers WHERE name = N'TR_LOGON_APP')
BEGIN
    DROP TRIGGER TR_LOGON_APP ON ALL SERVER;
END;


问:
Is React bootstrap table provide header TextFilter with clear button?
I am using react-bootstrap-table to display data in table row-column format.

I have one requirement to filter data using header filter option with clear button.

like this

```<code><TableHeaderColumn dataField='member' filter={ { type: 'TextFilter', delay:1000, condition:'like'} }>Member Name</TableHeaderColumn>
</code>```

But this filter display only Textbox. I want to add clear button also.

Is there any way to display clear button by enabling property in the filter? Or Do I need to write a custom filter for that?

```<code><TableHeaderColumn dataField='member' filter={ { type: 'CustomFilter', getElement: getCustomFilter, delay:1000, condition:'like'} }>Member Name</TableHeaderColumn>
</code>```

答:
I have developed the custom filter for Textbox with the clear button.

```<code>import React from "react";
import PropTypes from 'prop-types';
import {Form, InputGroup, FormControl, Glyphicon} from "react-bootstrap";

export default class TextWithClearButtonFilter extends React.Component {

  constructor(props) {
    super(props);
    this.filter = this.filter.bind(this);
    this.cleanFiltered = this.cleanFiltered.bind(this);

    this.state = {
      value: this.props.defaultValue || ''
    };

  }

 cleanFiltered() {

    if (this.state.value) {

        var value = this.props.defaultValue ? this.props.defaultValue : '';
        this.setState(function () {
            return { value: value };
        });

        this.props.filterHandler(value);
    }

  }

 filter(event) {

      var _this2 = this;

      if (this.timeout) {

        clearTimeout(this.timeout);
      }

      var filterValue = event.target.value;

      this.setState(function () {
        return { value: filterValue };
      });

      this.timeout = setTimeout(function () {
        if(filterValue){
            _this2.props.filterHandler(filterValue);
        } else {
            _this2.props.filterHandler(_this2.props.defaultValue);
        }
      }, _this2.props.delay);

  }

  render() {
    return (
      <div>
            <InputGroup bsSize="small">
                <FormControl
                    type="text"
                    placeholder="Search"
                    style={{width:90}}
                    onChange={this.filter}
                    value={this.state.value}
                />
                <InputGroup.Addon className="hoverHand" onClick={this.cleanFiltered}>
                    <Glyphicon glyph="remove" />
                </InputGroup.Addon>
            </InputGroup>
      </div>
    );
  }
}

TextWithClearButtonFilter.propTypes = {
  filterHandler: PropTypes.func.isRequired,
  defaultValue: PropTypes.string,
  delay: PropTypes.number
};

TextWithClearButtonFilter.defaultProps = {
  delay: 2000
};

export function getTextWithClearButtonFilter(filterHandler, customFilterParameters) {
  return (
    <TextWithClearButtonFilter filterHandler={filterHandler} />
  );
}
</code>```

And Use this way

```<code><TableHeaderColumn dataField='member' filter={ { type: 'CustomFilter', getElement: getTextWithClearButtonFilter, delay:1000, condition:'like'} }>Member Name</TableHeaderColumn>
</code>```

Body:
I am using react-bootstrap-table to display data in table row-column format.

I have one requirement to filter data using header filter option with clear button.

like this

<TableHeaderColumn dataField='member' filter={ { type: 'TextFilter', delay:1000, condition:'like'} }>Member Name</TableHeaderColumn>

But this filter display only Textbox. I want to add clear button also.

Is there any way to display clear button by enabling property in the filter? Or Do I need to write a custom filter for that?

<TableHeaderColumn dataField='member' filter={ { type: 'CustomFilter', getElement: getCustomFilter, delay:1000, condition:'like'} }>Member Name</TableHeaderColumn>

Body:
I have developed the custom filter for Textbox with the clear button.

import React from "react";
import PropTypes from 'prop-types';
import {Form, InputGroup, FormControl, Glyphicon} from "react-bootstrap";

export default class TextWithClearButtonFilter extends React.Component {

  constructor(props) {
    super(props);
    this.filter = this.filter.bind(this);
    this.cleanFiltered = this.cleanFiltered.bind(this);

    this.state = {
      value: this.props.defaultValue || ''
    };

  }

 cleanFiltered() {

    if (this.state.value) {

        var value = this.props.defaultValue ? this.props.defaultValue : '';
        this.setState(function () {
            return { value: value };
        });

        this.props.filterHandler(value);
    }

  }

 filter(event) {

      var _this2 = this;

      if (this.timeout) {

        clearTimeout(this.timeout);
      }

      var filterValue = event.target.value;

      this.setState(function () {
        return { value: filterValue };
      });

      this.timeout = setTimeout(function () {
        if(filterValue){
            _this2.props.filterHandler(filterValue);
        } else {
            _this2.props.filterHandler(_this2.props.defaultValue);
        }
      }, _this2.props.delay);

  }

  render() {
    return (
      <div>
            <InputGroup bsSize="small">
                <FormControl
                    type="text"
                    placeholder="Search"
                    style={{width:90}}
                    onChange={this.filter}
                    value={this.state.value}
                />
                <InputGroup.Addon className="hoverHand" onClick={this.cleanFiltered}>
                    <Glyphicon glyph="remove" />
                </InputGroup.Addon>
            </InputGroup>
      </div>
    );
  }
}

TextWithClearButtonFilter.propTypes = {
  filterHandler: PropTypes.func.isRequired,
  defaultValue: PropTypes.string,
  delay: PropTypes.number
};

TextWithClearButtonFilter.defaultProps = {
  delay: 2000
};

export function getTextWithClearButtonFilter(filterHandler, customFilterParameters) {
  return (
    <TextWithClearButtonFilter filterHandler={filterHandler} />
  );
}

And Use this way

<TableHeaderColumn dataField='member' filter={ { type: 'CustomFilter', getElement: getTextWithClearButtonFilter, delay:1000, condition:'like'} }>Member Name</TableHeaderColumn>


问:
Sampling a log-concave distribution using the adaptive rejection sampling method (R)
I am not very familiar with R. I have been trying to use the implementation of the adaptive rejection sampling method in R, in order to sample from the following distribution:

here is my R code:

```<code>library(ars)
g1 <- function(x,r){(1./r)*((1-x)^r)}
f1 <- function(x,a,k) {
  add<-0
  for(i in 1:k) {
  add<- add+g1(x,i)
  }
  res <- (a* add)+(a-1)*log(x)+k*log(1-x)
  return(res)
}

g2 <- function(x,r){(1-x)^(r-1)}
f1prima <- function(x,a,k) {
  add<-0
  for(i in 1:k) {
  add<- add-g2(x,i)
  }
  res <- (a* add)+(a-1)/x-k/(1-x)
  return(res)
}
mysample1<-ars(20,f1,f1prima,x=c(0.001,0.09),m=2,emax=128,lb=TRUE,xlb=0.0, ub=TRUE, xub=1,a=0.5,k=100)
</code>```

The function is a log-concave, but I get different error messages when I run ars and fiddling around with the input parameters won't help here. Any suggestion would be appreciated.

答:
First thing, which you already noticed is that your log-concave function is not very well defined at x=0 and x=1.0. So useful interval would be something like 0.01...0.99, not 0.0...1.0

Second, I don't like the idea to compute hundreds of terms in your summation term.
So, good idea might be to express it in following way, starting with derivative

S1N-1 qi is obviously geometric series and could be replaced with
(1-qN)/(1-q), where q=1-x.

This is derivative, so to get to similar term in function itself, just integrate it.

http://www.wolframalpha.com/input/?i=integrate+(1-q%5EN)%2F(1-q)+dq will return Gauss Hypergeometric function 2F1 plus logarithm

-qN+1 2F1(1, N+1; N+2; q)/(N+1) - log(1-q)

NB: It is the same integral as Beta before, but dealing with it was a bit more cumbersome
So, code to compute those terms:

```<code>library(gsl)
library(ars)
library(ggplot2)

Gauss2F1 <- function(a, b, c, x) {
    ifelse(x >= 0.0 & x < 1.0, hyperg_2F1(a, b, c, x), hyperg_2F1(c - a, b, c, 1.0 - 1.0/(1.0 - x))/(1.0 - x)^b)
}

f1sum <- function(x, N) {
    q <- 1.0 - x
    - q^(N+1) * Gauss2F1(1, N+1, N+2, q)/(N+1) - log(1.0 - q)
}

f1sum.1 <- function(x, N) {
    q <- 1.0 - x
    res <- rep(0.0, length.out = length(x))
    s <- rep(1.0, length.out = length(x))
    for(k in 1:N) {
        s <- s * q / as.numeric(k)
        res <- res + s
    }
    res
}

f1 <- function(x, a, N) {
    a * f1sum(x, N) + (a - 1.0)*log(x) + N*log(1.0 - x)
}

f1.1 <- function(x, a, N) {
    a * f1sum.1(x, N) + (a - 1.0)*log(x) + N*log(1.0 - x)
}

f1primesum <- function(x, N) {
    q <- 1.0 - x
    (1.0 - q^N)/(1.0 - q)
}

f1primesum.1 <- function(x, N) {
    res <- rep(0.0, length.out = length(x))
    s <- rep(1.0, length.out = length(x))
    for(k in 1:N) {
        res <- res + s
        s <- s * q
    }
    -res
}

f1prime <- function(x, a, N) {
    a* f1primesum(x, N) + (a - 1.0)/x - N/(1.0 - x)
}

f1prime.1 <- function(x, a, N) {
    a* f1primesum.1(x, N) + (a - 1.0)/x - N/(1.0 - x)
}

p <- ggplot(data.frame(x = c(0, 1)), aes(x = x)) +
    stat_function(fun = f1, args = list(0.5, 100), colour = "#4271AE") +
    stat_function(fun = f1.1, args = list(0.5, 100), colour = "#1F3552") +
    scale_x_continuous(name = "X", breaks = seq(0, 1, 0.2), limits=c(0.001, 0.5)) +
    scale_y_continuous(name = "F") +
    ggtitle("Log-concave function")
p
</code>```

As you can see, I've implemented both versions - one using summation and another using analytical form of sums. Computed data for a=0.5, N=100.

First, there is a bit of a difference between direct sum and 2F1 - I attribute it to precision loss in summation.

Second, more important result - function is NOT log-concave. No questions why ars() if failing left and right. See graph below

Body:
I am not very familiar with R. I have been trying to use the implementation of the adaptive rejection sampling method in R, in order to sample from the following distribution:

here is my R code:

library(ars)
g1 <- function(x,r){(1./r)*((1-x)^r)}
f1 <- function(x,a,k) {
  add<-0
  for(i in 1:k) {
  add<- add+g1(x,i)
  }
  res <- (a* add)+(a-1)*log(x)+k*log(1-x)
  return(res)
}

g2 <- function(x,r){(1-x)^(r-1)}
f1prima <- function(x,a,k) {
  add<-0
  for(i in 1:k) {
  add<- add-g2(x,i)
  }
  res <- (a* add)+(a-1)/x-k/(1-x)
  return(res)
}
mysample1<-ars(20,f1,f1prima,x=c(0.001,0.09),m=2,emax=128,lb=TRUE,xlb=0.0, ub=TRUE, xub=1,a=0.5,k=100)

The function is a log-concave, but I get different error messages when I run ars and fiddling around with the input parameters won't help here. Any suggestion would be appreciated.

Body:
First thing, which you already noticed is that your log-concave function is not very well defined at x=0 and x=1.0. So useful interval would be something like 0.01...0.99, not 0.0...1.0

Second, I don't like the idea to compute hundreds of terms in your summation term.
So, good idea might be to express it in following way, starting with derivative

S1N-1 qi is obviously geometric series and could be replaced with
(1-qN)/(1-q), where q=1-x.

This is derivative, so to get to similar term in function itself, just integrate it.

http://www.wolframalpha.com/input/?i=integrate+(1-q%5EN)%2F(1-q)+dq will return Gauss Hypergeometric function 2F1 plus logarithm

-qN+1 2F1(1, N+1; N+2; q)/(N+1) - log(1-q)

NB: It is the same integral as Beta before, but dealing with it was a bit more cumbersome
So, code to compute those terms:

library(gsl)
library(ars)
library(ggplot2)

Gauss2F1 <- function(a, b, c, x) {
    ifelse(x >= 0.0 & x < 1.0, hyperg_2F1(a, b, c, x), hyperg_2F1(c - a, b, c, 1.0 - 1.0/(1.0 - x))/(1.0 - x)^b)
}

f1sum <- function(x, N) {
    q <- 1.0 - x
    - q^(N+1) * Gauss2F1(1, N+1, N+2, q)/(N+1) - log(1.0 - q)
}

f1sum.1 <- function(x, N) {
    q <- 1.0 - x
    res <- rep(0.0, length.out = length(x))
    s <- rep(1.0, length.out = length(x))
    for(k in 1:N) {
        s <- s * q / as.numeric(k)
        res <- res + s
    }
    res
}

f1 <- function(x, a, N) {
    a * f1sum(x, N) + (a - 1.0)*log(x) + N*log(1.0 - x)
}

f1.1 <- function(x, a, N) {
    a * f1sum.1(x, N) + (a - 1.0)*log(x) + N*log(1.0 - x)
}

f1primesum <- function(x, N) {
    q <- 1.0 - x
    (1.0 - q^N)/(1.0 - q)
}

f1primesum.1 <- function(x, N) {
    res <- rep(0.0, length.out = length(x))
    s <- rep(1.0, length.out = length(x))
    for(k in 1:N) {
        res <- res + s
        s <- s * q
    }
    -res
}

f1prime <- function(x, a, N) {
    a* f1primesum(x, N) + (a - 1.0)/x - N/(1.0 - x)
}

f1prime.1 <- function(x, a, N) {
    a* f1primesum.1(x, N) + (a - 1.0)/x - N/(1.0 - x)
}

p <- ggplot(data.frame(x = c(0, 1)), aes(x = x)) +
    stat_function(fun = f1, args = list(0.5, 100), colour = "#4271AE") +
    stat_function(fun = f1.1, args = list(0.5, 100), colour = "#1F3552") +
    scale_x_continuous(name = "X", breaks = seq(0, 1, 0.2), limits=c(0.001, 0.5)) +
    scale_y_continuous(name = "F") +
    ggtitle("Log-concave function")
p

As you can see, I've implemented both versions - one using summation and another using analytical form of sums. Computed data for a=0.5, N=100.

First, there is a bit of a difference between direct sum and 2F1 - I attribute it to precision loss in summation.

Second, more important result - function is NOT log-concave. No questions why ars() if failing left and right. See graph below


问:
How to use datasoure in ng2-ya-table?
In the documentation of ng2-ya-table the datasource function is written in this way :

```<code>public datasource: any = (request: any): Observable<any> => {
return this.service.getUsers(request);
}
</code>```

And used like this :

```<code><ng2-ya-table [options]="options" [columns]="columns" [datasource]="datasource" [paging]="paging">
</ng2-ya-table>
</code>```

I don't want to use this function in this way because I have static

```<code>data = [
    {
        name: 'Patricia',
        email: 'Julianne.OConner@kory.org',
        username: 'Yes',
    },
    {
        name: 'Chelsey Dietrich',
        email: 'Lucio_Hettinger@annie.ca',
        username: 'No',
    }
]
</code>```

Is that possible or I am obliged to render observable type?
I tried a lot using static data but in vain

```<code>public datasource: any = {
    return this.data ;
}
</code>```

why this function is not working?

答:
I tried:

```<code>public datasource: any = (request: any): Observable<any> => {
  return Observable.of(this.data);
}
</code>```

but it causes a cascade of errors starting with:

Ng2YaTableComponent.html:53 ERROR TypeError: Cannot read property
  'length' of undefined

If someone can improve this answer perhaps we can find an solution

Title: How to use datasoure in ng2-ya-table?

Body:
In the documentation of ng2-ya-table the datasource function is written in this way :

public datasource: any = (request: any): Observable<any> => {
return this.service.getUsers(request);
}

And used like this :

<ng2-ya-table [options]="options" [columns]="columns" [datasource]="datasource" [paging]="paging">
</ng2-ya-table>

I don't want to use this function in this way because I have static

data = [
    {
        name: 'Patricia',
        email: 'Julianne.OConner@kory.org',
        username: 'Yes',
    },
    {
        name: 'Chelsey Dietrich',
        email: 'Lucio_Hettinger@annie.ca',
        username: 'No',
    }
]

Is that possible or I am obliged to render observable type?
I tried a lot using static data but in vain

public datasource: any = {
    return this.data ;
}

why this function is not working?

Body:
I tried:

public datasource: any = (request: any): Observable<any> => {
  return Observable.of(this.data);
}

but it causes a cascade of errors starting with:

Ng2YaTableComponent.html:53 ERROR TypeError: Cannot read property
  'length' of undefined

If someone can improve this answer perhaps we can find an solution


问:
How to check the difference of two dates greater than some value using java
I'm creating equation to check if the current date greater than the end date or the current date less than the end date with more than 15 days and this's my code and doesn't work for the second part of equation .
what would be the error??</p>

```<code>if (cal.compareTo(gndr1) >= 0 || cal.compareTo(gndr1) > 15) {
    if (gndr2 == 0) {
        new check2().setVisible(true);
    } else {
        new themainwindow().setVisible(true);
    }
} else {
    new themainwindow().setVisible(true);
}
</code>```

答: Unless you’ve implemented your own compareTo it’s only ever going to return -1, 0 or 1 based on whether the object is less than, equal or greater than the other. Hence you’ll never pass the >=15 condition.</p>

Body:
I'm creating equation to check if the current date greater than the end date or the current date less than the end date with more than 15 days and this's my code and doesn't work for the second part of equation .
what would be the error??

if (cal.compareTo(gndr1) >= 0 || cal.compareTo(gndr1) > 15) {
    if (gndr2 == 0) {
        new check2().setVisible(true);
    } else {
        new themainwindow().setVisible(true);
    }
} else {
    new themainwindow().setVisible(true);
}


问:
How to monitor and automatically restart mysql?
I'm running mysql on Debian.

Is there a way to monitor mysql and restart it automatically if it locks up? For example sometimes the server starts to take 100% of cpu and starts running very slowly. If I restart mysql, things clear up and the server starts working fine, but I'm not always present to restart it manually.

Is there a way to monitor mysql and if the cpu is above 95% for more than 10 minutes straight then then mysql will automatically be restarted

答:
You can write a cronjob to use

```<code>show processlist;
</code>```

show processlist will return column Time and Id,

you can add more logic to check,

like query stuck for more than 600 seconds and the query is SELECT,

you can use Id value to perform kill $id;

This is safer than blindly restarting your server.

And if you have segregate between read/write (meaning read only SQL will use user with read privileges only), this can even simpler.

ContentLicense: CC BY-SA 2.5

Body:
You can write a cronjob to use

show processlist;

show processlist will return column Time and Id,

you can add more logic to check,

like query stuck for more than 600 seconds and the query is SELECT,

you can use Id value to perform kill $id;

This is safer than blindly restarting your server.

And if you have segregate between read/write (meaning read only SQL will use user with read privileges only), this can even simpler.


问:
setPaint() not working when trying to use Gradient Paint
I am very new to Java and working on a GUI that draws shapes. This is an example of my class for drawing Circles. I need to add the ability for it to draw shapes with a color gradient. It seems like the only way to call setPaint() is in the paint method. It will not recognize the method in my drawShape(Graphics g) method. Is there a way to work around this? I want to be able to call it in the class.</p>

```<code>    import java.awt.BasicStroke;
    import java.awt.Color;
    import java.awt.GradientPaint;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Paint;
    import java.io.Serializable;

public class Oval extends Shape implements Serializable {

    //Default constructor
    public Oval() {

    }

    //Constructor
    public Oval(int c1, int c2, int c3, int c4, int c5, int c6, int c7, boolean d, boolean f, int tran, int s, String ss, boolean g, Color ccc1, Color ccc2) {
        component1 = c1;
        component2 = c2;
        component3 = c3;
        component4 = c4;
        red = c5;
        green = c6;
        blue = c7;
        dashed = d;
        thick = false;
        fill = f;
        trans = tran;
        stroke = s;
        textBox = ss;
        gFlag = g;
        cc1 = ccc1;
        cc2 = ccc2;

    }

    @Override
    public void drawShape(Graphics g) {
        g.setColor(new Color(red, green, blue, trans));

        if (gFlag == true) {

            Graphics g2d = (Graphics2D) g;
            GradientPaint gp2 = new GradientPaint(0, 0, cc1, 10, 10, cc2);
            //Error
            g2d.setPaint(gp2);

        } else if (dashed == true && fill != true) {
            Graphics2D g2d = (Graphics2D) g;
            float[] fa = {10, 10, 10};
            BasicStroke bs = new BasicStroke(stroke, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 10, fa, 10);

            g2d.setStroke(bs);
            g2d.drawOval(component1, component2, component3, component4);

        } else if (dashed != true && fill != true) {

            Graphics2D g2d = (Graphics2D) g;
            BasicStroke bs = new BasicStroke(stroke);
            g2d.setStroke(bs);
            g2d.drawOval(component1, component2, component3, component4);

        } else if (fill == true) {
            g.fillOval(component1, component2, component3, component4);
            System.out.println("FILLED OVAL DRAWN");
        }

        System.out.println("Oval Drawn.");
    }

    Shape copy() {

        return new Oval();

    }

}
</code>```

答: The Graphics2D.setPaint(Paint) method is part of the Graphics2D class, not the Graphics class. The drawing instance passed to a paint method for Swing components will typically be a Graphics2D object. I.E. It can be cast to a Graphics2D instance.

Body:
I am very new to Java and working on a GUI that draws shapes. This is an example of my class for drawing Circles. I need to add the ability for it to draw shapes with a color gradient. It seems like the only way to call setPaint() is in the paint method. It will not recognize the method in my drawShape(Graphics g) method. Is there a way to work around this? I want to be able to call it in the class.

    import java.awt.BasicStroke;
    import java.awt.Color;
    import java.awt.GradientPaint;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Paint;
    import java.io.Serializable;

public class Oval extends Shape implements Serializable {

    //Default constructor
    public Oval() {

    }

    //Constructor
    public Oval(int c1, int c2, int c3, int c4, int c5, int c6, int c7, boolean d, boolean f, int tran, int s, String ss, boolean g, Color ccc1, Color ccc2) {
        component1 = c1;
        component2 = c2;
        component3 = c3;
        component4 = c4;
        red = c5;
        green = c6;
        blue = c7;
        dashed = d;
        thick = false;
        fill = f;
        trans = tran;
        stroke = s;
        textBox = ss;
        gFlag = g;
        cc1 = ccc1;
        cc2 = ccc2;

    }

    @Override
    public void drawShape(Graphics g) {
        g.setColor(new Color(red, green, blue, trans));

        if (gFlag == true) {

            Graphics g2d = (Graphics2D) g;
            GradientPaint gp2 = new GradientPaint(0, 0, cc1, 10, 10, cc2);
            //Error
            g2d.setPaint(gp2);

        } else if (dashed == true && fill != true) {
            Graphics2D g2d = (Graphics2D) g;
            float[] fa = {10, 10, 10};
            BasicStroke bs = new BasicStroke(stroke, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 10, fa, 10);

            g2d.setStroke(bs);
            g2d.drawOval(component1, component2, component3, component4);

        } else if (dashed != true && fill != true) {

            Graphics2D g2d = (Graphics2D) g;
            BasicStroke bs = new BasicStroke(stroke);
            g2d.setStroke(bs);
            g2d.drawOval(component1, component2, component3, component4);

        } else if (fill == true) {
            g.fillOval(component1, component2, component3, component4);
            System.out.println("FILLED OVAL DRAWN");
        }

        System.out.println("Oval Drawn.");
    }

    Shape copy() {

        return new Oval();

    }

}


问:
Can a PHP class property be equal to another class property?
I want to do this:

```<code>class MyClass {
   var $array1 = array(3,4);
   var $array2 = self::$array1;
}
</code>```

and $array2 doesn't work.

Do you have a solution/trick to make a class property equal to another class property?

答:
According to the PHP Manual:

The default value must be a constant expression, not (for example) a variable, a class member or a function call.

What you COULD do is:

```<code>class MyClass {
    var $array1 = array(3,4);
    var $array2 = array();

    function MyClass() {
        $this->array2 = $this->array1;
    }
}
</code>```

The function MyClass (or __construct if you are in PHP5) will be called every time a new object is created, so any instances of MyClass would have an array2 property that has the same value as its array1 property.

```<code>$myclass = new MyClass();
print_r($myclass->array1); // outputs Array ( [0] => 3 [1] => 4 )
print_r($myclass->array2); // outputs Array ( [0] => 3 [1] => 4 )
</code>```

OwnerDisplayName: Stemar

LastEditorDisplayName: Stemar

ContentLicense: CC BY-SA 4.0

Body:
I want to do this:

class MyClass {
   var $array1 = array(3,4);
   var $array2 = self::$array1;
}

and $array2 doesn't work.

Do you have a solution/trick to make a class property equal to another class property?

Body:
According to the PHP Manual:

The default value must be a constant expression, not (for example) a variable, a class member or a function call.

What you COULD do is:

class MyClass {
    var $array1 = array(3,4);
    var $array2 = array();

    function MyClass() {
        $this->array2 = $this->array1;
    }
}

The function MyClass (or __construct if you are in PHP5) will be called every time a new object is created, so any instances of MyClass would have an array2 property that has the same value as its array1 property.

$myclass = new MyClass();
print_r($myclass->array1); // outputs Array ( [0] => 3 [1] => 4 )
print_r($myclass->array2); // outputs Array ( [0] => 3 [1] => 4 )

OwnerDisplayName: Paolo Bergantino

LastEditorDisplayName: Paolo Bergantino


问:
Odoo restrict regular user
Im having troubles restricting the analytic timesheet so that employees only can see and edit their own hours.

I tried restricting it with the rule [('user_id','=',user.id)] but I guess I entered the rule to the wrong place.

How exactly do I do this?

Thank you!

答:
Your rule looks fine, but it needs to be "Apply on Read" also.

Currently, it's not applied on read, so users would be able to view all other employees' hours, but not create/edit/delete.

Additionally, the Object may need to be changed. Currently your record rule is applying on the Users object, when it sounds like you want to apply it on the account.analytic.line object so that your rule applies to the Timesheets.

Record Rules Documentation

Title: Odoo restrict regular user


问:
Hold down key to constantly move tank
I'm currently trying to make the tanks move(whhich they already do) but I want to make it so that you can just hold down WASD or the 4 arrow keys to have it contantly moving. Right now, you have to click the arrow key over and over again for it to move.

```<code>import pygame, assetloader
from pygame.locals import *
import random, time, math
import pygame

GRAD = math.pi/180
blue = (0, 0, 255)

wallRects = []

maze = [[] for i in range(25)]

assetloader.set_asset_path("assets/")

class Player(pygame.sprite.Sprite):
    def __init__(self, x, y, pos):
        pygame.sprite.Sprite.__init__(self)

        self.image, self.rect = assetloader.load_image("Tank.png", -1)
        self.rect.x = x
        self.rect.y = y
        self.rect.clamp_ip(screen.get_rect())
        self.dir = 0
        self.vel_y = 0
        self.vel_x = 0
        self.rows = pos[0]
        self.cols = pos[1]
        self.x = self.cols * gsize
        self.y = self.rows * gsize
        self.orig_image, self.orig_rect = assetloader.load_image("Tank.png", -1)
        self.orig_rect.x = self.x
        self.orig_rect.y = self.y
        self.orig_gun_pos = self.orig_rect.midtop
        self.ammo = 5
        self.vel = [0, 0]
        self.dead = False

    def draw(self, screen):
        image = pygame.transform.rotate(self.image, self.dir)
        screen.blit(image, self.rect)

    def update(self):
        oldCenter = self.rect.center

        self.rect = self.image.get_rect()
        self.rect.center = oldCenter
        screen_rect = screen.get_rect()
        keys = pygame.key.get_pressed()

        if keys[K_UP]:

            if (0 < self.dir and self.dir < 90) or (-360 < self.dir and self.dir < -270):
               self.vel_x = -1

               self.vel_y = -1
            elif (270 < self.dir and self.dir < 360) or (-90 < self.dir and self.dir < 0):
                self.vel_x = 1
                self.vel_y = -1
            if (90 < self.dir and self.dir < 180) or (-270 < self.dir and self.dir < -180):
                self.vel_x = -1
                self.vel_y = 1

            elif (180 < self.dir and self.dir < 270) or (-180 < self.dir and self.dir < -90):
                self.vel_x = 1
                self.vel_y = 1

            if self.dir == 0 :
                self.vel_x = 0
                self.vel_y = -1
            if self.dir == 90 :
                self.vel_x = -1
                self.vel_y = 0
            if self.dir == 180:
                self.vel_x = 0
                self.vel_y = 1
            if self.dir == 270:
                self.vel_x = 1
                self.vel_y = 0

            self.rect.move_ip(self.vel_x, self.vel_y)

        elif keys[K_DOWN]:

            if (0 < self.dir and self.dir < 90) or (-360 < self.dir and self.dir < -270):
               self.vel_x = 1

               self.vel_y = 1
            elif (270 < self.dir and self.dir < 360) or (-90 < self.dir and self.dir < 0):
                self.vel_x = -1
                self.vel_y = 1
            if (90 < self.dir and self.dir < 180) or (-270 < self.dir and self.dir < -180):
                self.vel_x = 1
                self.vel_y = -1

            elif (180 < self.dir and self.dir < 270) or (-180 < self.dir and self.dir < -90):
                self.vel_x = -1
                self.vel_y = -1

            if self.dir == 0 :
                self.vel_x = 0
                self.vel_y = 1
            if self.dir == 90 :
                self.vel_x = 1
                self.vel_y = 0
            if self.dir == 180:
                self.vel_x = 0
                self.vel_y = -1
            if self.dir == 270:
                self.vel_x = -1
                self.vel_y = 0

            self.rect.move_ip(self.vel_x, self.vel_y)

        if keys[K_LEFT]:
            self.dir += 5
            if self.dir > 360:
                self.dir = 0
        elif keys[K_RIGHT]:
            self.dir -= 5
            if self.dir < -360:
                self.dir = 0

        if not screen_rect.contains(self.rect):
            self.rect.clamp_ip(screen_rect)

class Enemy(pygame.sprite.Sprite):
    def __init__(self, x, y):
        pygame.sprite.Sprite.__init__(self)

        self.image, self.rect = assetloader.load_image("New Piskel.png", -1)
        self.rect.x = x
        self.rect.y = y
        self.dir = 0
        self.rect.clamp_ip(screen.get_rect())

    def draw(self, screen):

        image = pygame.transform.rotate(self.image, self.dir)
        screen.blit(image, self.rect)

    def update(self):
        screen_rect = screen.get_rect()
        keys = pygame.key.get_pressed()
        if keys[K_w]:

            if (0 < self.dir and self.dir < 90) or (-360 < self.dir and self.dir < -270):
               self.vel_x = -1

               self.vel_y = -1
            elif (270 < self.dir and self.dir < 360) or (-90 < self.dir and self.dir < 0):
                self.vel_x = 1
                self.vel_y = -1
            if (90 < self.dir and self.dir < 180) or (-270 < self.dir and self.dir < -180):
                self.vel_x = -1
                self.vel_y = 1

            elif (180 < self.dir and self.dir < 270) or (-180 < self.dir and self.dir < -90):
                self.vel_x = 1
                self.vel_y = 1

            if self.dir == 0 :
                self.vel_x = 0
                self.vel_y = -1
            if self.dir == 90 :
                self.vel_x = -1
                self.vel_y = 0
            if self.dir == 180:
                self.vel_x = 0
                self.vel_y = 1
            if self.dir == 270:
                self.vel_x = 1
                self.vel_y = 0

            self.rect.move_ip(self.vel_x, self.vel_y)

        elif keys[K_s]:

            if (0 < self.dir and self.dir < 90) or (-360 < self.dir and self.dir < -270):
               self.vel_x = 1

               self.vel_y = 1
            elif (270 < self.dir and self.dir < 360) or (-90 < self.dir and self.dir < 0):
                self.vel_x = -1
                self.vel_y = 1
            if (90 < self.dir and self.dir < 180) or (-270 < self.dir and self.dir < -180):
                self.vel_x = 1
                self.vel_y = -1

            elif (180 < self.dir and self.dir < 270) or (-180 < self.dir and self.dir < -90):
                self.vel_x = -1
                self.vel_y = -1

            if self.dir == 0 :
                self.vel_x = 0
                self.vel_y = 1
            if self.dir == 90 :
                self.vel_x = 1
                self.vel_y = 0
            if self.dir == 180:
                self.vel_x = 0
                self.vel_y = -1
            if self.dir == 270:
                self.vel_x = -1
                self.vel_y = 0

            self.rect.move_ip(self.vel_x, self.vel_y)

        if keys[K_a]:
            self.dir += 5
            if self.dir > 360:
                self.dir = 0
        elif keys[K_d]:
            self.dir -= 5
            if self.dir < -360:
                self.dir = 0

        if not screen_rect.contains(self.rect):
            self.rect.clamp_ip(screen_rect)

size = width, height = 500, 400
gsize = 25
start_x, start_y = 0, 0
bgColor = 255, 255, 255

pygame.init()
screen = pygame.display.set_mode(size)#, pygame.FULLSCREEN)
pygame.display.set_caption("Sample Sprite")
clock = pygame.time.Clock()

p = Player(width/2, height/4, (3,4))
e = Enemy(width/2, height/4)

coll_font = pygame.font.Font(None, 30)

going = True
while going:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == QUIT:
            going = False
        elif event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                going = False

        p.update()
        e.update()

        screen.fill(bgColor)

        p.draw(screen)
        e.draw(screen)

        pygame.display.flip()

pygame.quit()
</code>```

There are no errors right now, but I want to have constant movement instead of re-pressing the keys over and over. Can someone explain to me how?

答:
I think your problem are wrong indentions in while going

Functions update() are inside for event loop so they are executed only when you move mouse, press/release mouse button or press/release key (when key change state from not-pressed to pressed or from pressed to not-pressed), but not when you keep key pressed.

```<code>going = True
while going:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == QUIT:
            going = False
        elif event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                going = False

    # correct indentions - all outside of `for event` loop

    p.update()
    e.update()

    screen.fill(bgColor)

    p.draw(screen)
    e.draw(screen)

    pygame.display.flip()

pygame.quit()
</code>```

Title: Hold down key to constantly move tank

Body:
I'm currently trying to make the tanks move(whhich they already do) but I want to make it so that you can just hold down WASD or the 4 arrow keys to have it contantly moving. Right now, you have to click the arrow key over and over again for it to move.

import pygame, assetloader
from pygame.locals import *
import random, time, math
import pygame

GRAD = math.pi/180
blue = (0, 0, 255)

wallRects = []

maze = [[] for i in range(25)]

assetloader.set_asset_path("assets/")

class Player(pygame.sprite.Sprite):
    def __init__(self, x, y, pos):
        pygame.sprite.Sprite.__init__(self)

        self.image, self.rect = assetloader.load_image("Tank.png", -1)
        self.rect.x = x
        self.rect.y = y
        self.rect.clamp_ip(screen.get_rect())
        self.dir = 0
        self.vel_y = 0
        self.vel_x = 0
        self.rows = pos[0]
        self.cols = pos[1]
        self.x = self.cols * gsize
        self.y = self.rows * gsize
        self.orig_image, self.orig_rect = assetloader.load_image("Tank.png", -1)
        self.orig_rect.x = self.x
        self.orig_rect.y = self.y
        self.orig_gun_pos = self.orig_rect.midtop
        self.ammo = 5
        self.vel = [0, 0]
        self.dead = False

    def draw(self, screen):
        image = pygame.transform.rotate(self.image, self.dir)
        screen.blit(image, self.rect)

    def update(self):
        oldCenter = self.rect.center

        self.rect = self.image.get_rect()
        self.rect.center = oldCenter
        screen_rect = screen.get_rect()
        keys = pygame.key.get_pressed()

        if keys[K_UP]:

            if (0 < self.dir and self.dir < 90) or (-360 < self.dir and self.dir < -270):
               self.vel_x = -1

               self.vel_y = -1
            elif (270 < self.dir and self.dir < 360) or (-90 < self.dir and self.dir < 0):
                self.vel_x = 1
                self.vel_y = -1
            if (90 < self.dir and self.dir < 180) or (-270 < self.dir and self.dir < -180):
                self.vel_x = -1
                self.vel_y = 1

            elif (180 < self.dir and self.dir < 270) or (-180 < self.dir and self.dir < -90):
                self.vel_x = 1
                self.vel_y = 1

            if self.dir == 0 :
                self.vel_x = 0
                self.vel_y = -1
            if self.dir == 90 :
                self.vel_x = -1
                self.vel_y = 0
            if self.dir == 180:
                self.vel_x = 0
                self.vel_y = 1
            if self.dir == 270:
                self.vel_x = 1
                self.vel_y = 0

            self.rect.move_ip(self.vel_x, self.vel_y)

        elif keys[K_DOWN]:

            if (0 < self.dir and self.dir < 90) or (-360 < self.dir and self.dir < -270):
               self.vel_x = 1

               self.vel_y = 1
            elif (270 < self.dir and self.dir < 360) or (-90 < self.dir and self.dir < 0):
                self.vel_x = -1
                self.vel_y = 1
            if (90 < self.dir and self.dir < 180) or (-270 < self.dir and self.dir < -180):
                self.vel_x = 1
                self.vel_y = -1

            elif (180 < self.dir and self.dir < 270) or (-180 < self.dir and self.dir < -90):
                self.vel_x = -1
                self.vel_y = -1

            if self.dir == 0 :
                self.vel_x = 0
                self.vel_y = 1
            if self.dir == 90 :
                self.vel_x = 1
                self.vel_y = 0
            if self.dir == 180:
                self.vel_x = 0
                self.vel_y = -1
            if self.dir == 270:
                self.vel_x = -1
                self.vel_y = 0

            self.rect.move_ip(self.vel_x, self.vel_y)

        if keys[K_LEFT]:
            self.dir += 5
            if self.dir > 360:
                self.dir = 0
        elif keys[K_RIGHT]:
            self.dir -= 5
            if self.dir < -360:
                self.dir = 0

        if not screen_rect.contains(self.rect):
            self.rect.clamp_ip(screen_rect)

class Enemy(pygame.sprite.Sprite):
    def __init__(self, x, y):
        pygame.sprite.Sprite.__init__(self)

        self.image, self.rect = assetloader.load_image("New Piskel.png", -1)
        self.rect.x = x
        self.rect.y = y
        self.dir = 0
        self.rect.clamp_ip(screen.get_rect())

    def draw(self, screen):

        image = pygame.transform.rotate(self.image, self.dir)
        screen.blit(image, self.rect)

    def update(self):
        screen_rect = screen.get_rect()
        keys = pygame.key.get_pressed()
        if keys[K_w]:

            if (0 < self.dir and self.dir < 90) or (-360 < self.dir and self.dir < -270):
               self.vel_x = -1

               self.vel_y = -1
            elif (270 < self.dir and self.dir < 360) or (-90 < self.dir and self.dir < 0):
                self.vel_x = 1
                self.vel_y = -1
            if (90 < self.dir and self.dir < 180) or (-270 < self.dir and self.dir < -180):
                self.vel_x = -1
                self.vel_y = 1

            elif (180 < self.dir and self.dir < 270) or (-180 < self.dir and self.dir < -90):
                self.vel_x = 1
                self.vel_y = 1

            if self.dir == 0 :
                self.vel_x = 0
                self.vel_y = -1
            if self.dir == 90 :
                self.vel_x = -1
                self.vel_y = 0
            if self.dir == 180:
                self.vel_x = 0
                self.vel_y = 1
            if self.dir == 270:
                self.vel_x = 1
                self.vel_y = 0

            self.rect.move_ip(self.vel_x, self.vel_y)

        elif keys[K_s]:

            if (0 < self.dir and self.dir < 90) or (-360 < self.dir and self.dir < -270):
               self.vel_x = 1

               self.vel_y = 1
            elif (270 < self.dir and self.dir < 360) or (-90 < self.dir and self.dir < 0):
                self.vel_x = -1
                self.vel_y = 1
            if (90 < self.dir and self.dir < 180) or (-270 < self.dir and self.dir < -180):
                self.vel_x = 1
                self.vel_y = -1

            elif (180 < self.dir and self.dir < 270) or (-180 < self.dir and self.dir < -90):
                self.vel_x = -1
                self.vel_y = -1

            if self.dir == 0 :
                self.vel_x = 0
                self.vel_y = 1
            if self.dir == 90 :
                self.vel_x = 1
                self.vel_y = 0
            if self.dir == 180:
                self.vel_x = 0
                self.vel_y = -1
            if self.dir == 270:
                self.vel_x = -1
                self.vel_y = 0

            self.rect.move_ip(self.vel_x, self.vel_y)

        if keys[K_a]:
            self.dir += 5
            if self.dir > 360:
                self.dir = 0
        elif keys[K_d]:
            self.dir -= 5
            if self.dir < -360:
                self.dir = 0

        if not screen_rect.contains(self.rect):
            self.rect.clamp_ip(screen_rect)

size = width, height = 500, 400
gsize = 25
start_x, start_y = 0, 0
bgColor = 255, 255, 255

pygame.init()
screen = pygame.display.set_mode(size)#, pygame.FULLSCREEN)
pygame.display.set_caption("Sample Sprite")
clock = pygame.time.Clock()

p = Player(width/2, height/4, (3,4))
e = Enemy(width/2, height/4)

coll_font = pygame.font.Font(None, 30)

going = True
while going:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == QUIT:
            going = False
        elif event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                going = False

        p.update()
        e.update()

        screen.fill(bgColor)

        p.draw(screen)
        e.draw(screen)

        pygame.display.flip()

pygame.quit()

There are no errors right now, but I want to have constant movement instead of re-pressing the keys over and over. Can someone explain to me how?

Body:
I think your problem are wrong indentions in while going

Functions update() are inside for event loop so they are executed only when you move mouse, press/release mouse button or press/release key (when key change state from not-pressed to pressed or from pressed to not-pressed), but not when you keep key pressed.

going = True
while going:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == QUIT:
            going = False
        elif event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                going = False

    # correct indentions - all outside of `for event` loop

    p.update()
    e.update()

    screen.fill(bgColor)

    p.draw(screen)
    e.draw(screen)

    pygame.display.flip()

pygame.quit()


问:
Using the asterisk (*) to specify width and precision in Go
The official fmt pacakge documentation at golang.org says this in respect to specifying width and precision -

Either or both of the flags may be replaced with the character '*', causing their values to be obtained from the next operand, which must be of type int.

How will the asterisk (*) be used, say, for example, in the following scenario -

```<code> var f float32 = 12.3456789
 fmt.Printf("%6.3f", f)
</code>```

答:
It would be

```<code>var f float32 = 12.3456789
fmt.Printf("%*.*f", 20, 1, f)
</code>```

See more at:

https://github.com/golang/go/blob/8f4f1f63e9d5d171a669d0a9c4594bbaaf9ea6f7/src/fmt/fmt_test.go#L1590

Body:
The official fmt pacakge documentation at golang.org says this in respect to specifying width and precision -

Either or both of the flags may be replaced with the character '*', causing their values to be obtained from the next operand, which must be of type int.

How will the asterisk (*) be used, say, for example, in the following scenario -

 var f float32 = 12.3456789
 fmt.Printf("%6.3f", f)

Body:
It would be

var f float32 = 12.3456789
fmt.Printf("%*.*f", 20, 1, f)

See more at:

https://github.com/golang/go/blob/8f4f1f63e9d5d171a669d0a9c4594bbaaf9ea6f7/src/fmt/fmt_test.go#L1590


问:
Can methods be added to an object?
So we have a class, Customer. I don't have any choice but to use Customer to represent any Customer I have, including in the signature of any methods, etc I write. But my data is slightly different; I still want much of the functionality inside Customer, but some fields I need to sorta bastardize for my special case. Example:

```<code>class Customer
{
public:
  string GetName();
  void SetName(string _name);

  string GetAge();
  void SetAge(string _age);

protected:
  string name;
  string age;
};

class SpecialCustomer : public Customer
{
public:
  string GetAddress();
  void SetAddress(string _address);
}
</code>```

So this all seems rather simple, but the problem I have is I am forced to pass around Customers. But as luck would  have it, in my special case, I don't need age at all! So what I need to do is re-use the age data member to hold my address. Yes, I know it's bad. No, I can't change the requirements - my special data has to fit into a Customer object.

So to do this, I could of course just construct a SpecialCustomer from a Customer, but I'd like to avoid the copy. (edit: Also, many data members are exposed directly publicly, so I can't use composition and support their use) Instead, I considered making SpecialCustomer a wrapper, exposing the pieces of functionality I want. The problem is the real implementation of Customer is not trivial - it's be a bit of work to re-implement the whole interface, minus the fields I don't want.

The only way that jumps to mind to achieve this is with something like this:

```<code>void foo (Customer & _c)
{
  SpecialCustomer & sc = reinterpret_cast<SpecialCustomer &>(_c);
}
</code>```

Obviously if SpecialCustomer has any virtual methods or data members, this won't work. But what if it is just a set of methods I want available on the object? Is there a better alternative to achieve this functionality?

答:
Seems like your hands are tied from using OO techniques. How about using plain old non-member functions of the form

```<code>string getSpecialCustomerAddress (Customer & _c)
{
  return _c.GetAge();
}
</code>```

You still have the problem of determining whether or not a customer is special

Title: Can methods be added to an object?

Body:
So we have a class, Customer. I don't have any choice but to use Customer to represent any Customer I have, including in the signature of any methods, etc I write. But my data is slightly different; I still want much of the functionality inside Customer, but some fields I need to sorta bastardize for my special case. Example:

class Customer
{
public:
  string GetName();
  void SetName(string _name);

  string GetAge();
  void SetAge(string _age);

protected:
  string name;
  string age;
};

class SpecialCustomer : public Customer
{
public:
  string GetAddress();
  void SetAddress(string _address);
}

So this all seems rather simple, but the problem I have is I am forced to pass around Customers. But as luck would  have it, in my special case, I don't need age at all! So what I need to do is re-use the age data member to hold my address. Yes, I know it's bad. No, I can't change the requirements - my special data has to fit into a Customer object.

So to do this, I could of course just construct a SpecialCustomer from a Customer, but I'd like to avoid the copy. (edit: Also, many data members are exposed directly publicly, so I can't use composition and support their use) Instead, I considered making SpecialCustomer a wrapper, exposing the pieces of functionality I want. The problem is the real implementation of Customer is not trivial - it's be a bit of work to re-implement the whole interface, minus the fields I don't want.

The only way that jumps to mind to achieve this is with something like this:

void foo (Customer & _c)
{
  SpecialCustomer & sc = reinterpret_cast<SpecialCustomer &>(_c);
}

Obviously if SpecialCustomer has any virtual methods or data members, this won't work. But what if it is just a set of methods I want available on the object? Is there a better alternative to achieve this functionality?

Body:
Seems like your hands are tied from using OO techniques. How about using plain old non-member functions of the form

string getSpecialCustomerAddress (Customer & _c)
{
  return _c.GetAge();
}

You still have the problem of determining whether or not a customer is special


问:
\n not working in UIlabel
I've seen similar questions here, but still can figure out why it's not working.

How to add line break (in other words add new paragraph) in multiline UIlabel?

I have a label with a lot of text,

```<code>lbl.numberOfLines = 0;
lbl.sizeToFit;
</code>```

but I'm still getting something like this:
"Some text here\nAnd here I want new line"

Thank you

答: UILabel use \n to made new line. \n need a space in the back.</p>

Title: \n not working in UIlabel

Body:
I've seen similar questions here, but still can figure out why it's not working.

How to add line break (in other words add new paragraph) in multiline UIlabel?

I have a label with a lot of text,

lbl.numberOfLines = 0;
lbl.sizeToFit;

but I'm still getting something like this:
"Some text here\nAnd here I want new line"

Thank you


问:
How to use DateDiff in calculated field in access
I am trying to get "No of days late" in a particular table in MS access. I am trying to use calculated data type.

I have [ActualReturnDate] and [ReturnDate] in the same table (both are Date/Time) and I want to save difference between two columns in a calculated field.

I am using following expression:

```<code>DateDiff("d", [ActualReturnDate] , [ReturnDate] )
</code>```

But no matter what i do I get error saying "The expression X cannot be used in a calculated column."

So does that mean I cannot use DateDiff in Calculated field? If not how should I do it?

答:
You indeed can't do this in a calculated field.
Use a query instead, add a column and do the calculation in that column.</p>

Body:
I am trying to get "No of days late" in a particular table in MS access. I am trying to use calculated data type.

I have [ActualReturnDate] and [ReturnDate] in the same table (both are Date/Time) and I want to save difference between two columns in a calculated field.

I am using following expression:

DateDiff("d", [ActualReturnDate] , [ReturnDate] )

But no matter what i do I get error saying "The expression X cannot be used in a calculated column."

So does that mean I cannot use DateDiff in Calculated field? If not how should I do it?


问:
How to clear buffer after reading an input in c?
```<code>#include<stdio.h>
#include<stdlib.h>
#include<string.h>

void generarDimension(int, void **, int);
void reallocarDimensiones(int, void **, int);
void preguntarValor(int *);
char *generarCadena(char *);

typedef struct listaAlu{//this is a list of students
    char cedula[7];//this means id
    char *nombreApellido;//this means name and lastname
    short curso;//this means the year of the student in college/school
    unsigned short anho;//and this means year-E.g: 2017
};

int main(void){
    struct listaAlu *alu = NULL;
    int salir=1;
    char c;
    unsigned int cont = 0;
    unsigned int i;
    size_t size = 0;
    struct listaAlu *temp = NULL;
    while(salir!=0){//Condition until user press exit option
        printf("Agregar Alumno?Ingrese 1 para Agregar, y 0 para salir\n");//This means "Add student?Press 1 to add, and 0 to exit
        preguntarValor(&salir);//this verifies user input
        if(salir==1){//if user adds then it asks info of the student
            cont++;
            if ( NULL == ( temp = realloc ( alu, size + 2))) {//realloc for each character input and '\0'
                fprintf ( stderr, "realloc problem\n");
            }//this is for increasing the number of students
            alu = temp;
            printf("Ingrese Cedula:\n");//This means "Enter id"
            scanf("%s", &(alu+(size))->cedula);
            printf("Ingrese Nombre y Apellido:\n");//This means "Enter name and lastname"
            (alu+(size))->nombreApellido = generarCadena((alu+(size))->nombreApellido);
            printf("Ingrese Curso:\n");//This means enter college/school year
            scanf("%hd", &(alu+(size))->curso);
            printf("Ingrese Anho:\n");//and this means "Enter year"
            scanf("%hd", &(alu+(size))->anho);
            size++;
        }
    }
    for(i=0;i<cont;i++){
        printf("\tAlumno %d\n", i+1);
        printf("Nombre:\t%s\n", (alu+i)->nombreApellido);
        printf("Cedula:\t%s\n", (alu+i)->cedula);
        printf("Curso:\t%d\n", (alu+i)->curso);
        printf("Anho:\t%d\n", (alu+i)->anho);
    }//This prints Everything the user entered
    free(alu);
    return 0;
}//Sorry for writing my program entirely on the main >.<

void generarDimension(int bloques, void **ptr, int tamanho){
    void **ptrAux;
    *ptrAux = malloc(bloques * tamanho);
    if(*ptrAux==NULL){
        printf("No se pudo almacenar memoria\n");
    }else{
            *ptr = *ptrAux;
            free(ptrAux);
        }
}//this I didn't use, but it is for generating an array through a pointer
void reallocarDimensiones(int bloques, void **ptr, int tamanho){
    void **ptrAux;
    *ptrAux = realloc(*ptr,bloques * tamanho);
    if(*ptrAux==NULL){
        printf("No se pudo almacenar memoria\n");
    }else{
            *ptr = *ptrAux;
            free(ptrAux);
        }
}//This I didn't either, but it is for reallocating any given pointer

void preguntarValor(int *n){
    long entero, lector;
    *n=-2;
    do{
        printf("\nSi ingresa otro numero o caracter, vuelva a ingresar opcion\n");
        while(!scanf("%d", &entero)){
            while((lector=getchar()) !='\n' && lector !=EOF );
        }
        *n=entero;
    }while(*n>1 || *n<0);//You can change this parameters according to the numbers you want
}//This subrutine scans only integers between 1 and 0

char *generarCadena(char *scaneado){
    char *temp = NULL;
    int in = 0;
    size_t size = 0;

    while ( '\n' != ( in = getchar ( ))) {//loop until newline
        if ( NULL == ( temp = realloc ( scaneado, size + 2))) {//realloc for each character input and '\0'
            fprintf ( stderr, "realloc problem\n");
            return scaneado;
        }
        scaneado = temp;
        scaneado[size] = in;//set input
        scaneado[size + 1] = '\0';//terminate
        size++;
    }
    return scaneado;
}//This subrutine is for geting an input of chars of any given length
</code>```

This is a program to store a college/school student list, I want to know how to improve this code, however in the part where I ask the user to enter strings, on the second one I can't enter anything. And if I try to enter more than 2 students, my code doesn't print all the info of the students I entered

答:
```<code>struct listaAlu *temp = NULL;
temp = realloc ( alu, size + 2);//<- wrong size
</code>```

realloc(alu, size + 2) will allocate only 2 bytes in the first run. But you need much more than that. The total size needed is number of elements in the array multiply by the size of the structure. That is sizeof(struct listaAlu) which is about 15 bytes.

```<code>realloc( alu, sizeof(struct listaAlu) * (size + 1) );
</code>```

You don't need to increment the size by 2.

Make sure to check the input at the right places. Clear the input when scanf fails.

To get first name and last name, you can use fgets and strdup

There are major problems with generarDimension and reallocarDimensiones. You may want to leave those out.

```<code>struct listaAlu{
    char cedula[7];//this means id
    char *nombreApellido;//this means name and lastname
    short curso;//this means the year of the student in college/school
    unsigned short anho;//and this means year-E.g: 2017
};

void clear()
{
    int c;
    while((c = getchar()) != '\n' && c != EOF);
}

int main(void)
{
    struct listaAlu *alu = NULL;
    size_t size = 0;
    while(1)
    {
        alu = realloc( alu, sizeof(struct listaAlu) * (size + 1) );
        if (!alu)
        {
            fprintf(stderr, "realloc problem\n");
            break;
        }

        char buf[256] = { 0 };

        printf("Enter id:\n");
        fgets(buf, sizeof(buf), stdin);
        buf[strcspn(buf, "\r\n")] = 0;
        buf[sizeof(alu[size].cedula) - 1] = 0;
        strcpy(alu[size].cedula, buf);

        printf("Enter name and lastname:\n");
        fgets(buf, sizeof(buf), stdin);
        buf[strcspn(buf, "\r\n")] = 0;
        alu[size].nombreApellido = _strdup(buf);

        for(;;)
        {
            printf("Enter college/school year:\n");
            if (scanf("%hd", &alu[size].curso) == 1)
                break;

            printf("input error\n");
            clear();
        }

        for(;;)
        {
            printf("Enter year:\n");
            if (scanf("%hd", &alu[size].anho) == 1)
                break;

            printf("input error\n");
            clear();
        }

        size++;

        printf("Press 1 to continue\n");
        char input;
        scanf(" %c", &input);
        if(input != '1')
            break;
        clear();
    }

    for(size_t i = 0; i < size; i++)
    {
        printf("Alumno %d\n", i);
        printf("Nombre:\t%s\n", alu[i].nombreApellido);
        printf("Cedula:\t%s\n", alu[i].cedula);
        printf("Curso:\t%hd\n", alu[i].curso);
        printf("Anho:\t%hd\n", alu[i].anho);
    }

    for(size_t i = 0; i < size; i++)
        free(alu[i].nombreApellido);
    free(alu);
    return 0;
}
</code>```

Edit

realloc does not need to be wrapped in a different function. But for fun purposes, you can do the following:

```<code>void* my_realloc1(void *ptr, int size)
{
    ptr = realloc(ptr, size);
    if (!ptr) printf("error\n");
    return ptr;
}

//usage:
alu = my_realloc1(alu, sizeof(struct listaAlu) * (size + 1));
if (!alu) printf("error\n");
</code>```

my_realloc1 will work here, however nothing is gained. This is just extra lines of code. It's easier and more clear to use realloc directly and do the necessary error handling.

Another method is to pass a reference:

```<code>void my_realloc2(void **ptr, int size)
{
    *ptr = realloc(*ptr, size);
}

//usage: (*** Note the address `&` operator ***)
my_realloc2(&alu, sizeof(struct listaAlu) * (size + 1));
if (!alu) printf("error\n");
</code>```

Again this will work, but it just adds more code.

The function generarCadena seems okay. You could simplify as follows:

```<code>char *my_getline()
{
    char *buf = NULL;
    int in = 0;
    size_t size = 0;
    while('\n' != (in = getchar()))
    {
        size++;
        buf = realloc(buf, size);
        buf[size - 1] = (char)in;
    }

    size++;
    buf = realloc(buf, size);
    buf[size - 1] = 0;

    return buf;
}

//usage:
printf("Enter name and lastname:\n");
alu[size].nombreApellido = my_getline();
</code>```

And use scanf for to read 6 characters (because size of cedula is 7)

```<code>printf("Enter 6 characters:\n");
scanf("%6s", alu[size].cedula);
alu[size].cedula[6] = '\0';
clear();
</code>```

To be safe, make sure the input is null terminated, and clear the buffer.

Or you can use fgets as I used in the example. This will read up to 256 characters:

```<code>char buf[256];
fgets(buf, sizeof(buf), stdin);
</code>```

fgets is sometimes easier because you don't need to clear the buffer. But buf includes end of line character \n, you have to remove \n in this case.

Body:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

void generarDimension(int, void **, int);
void reallocarDimensiones(int, void **, int);
void preguntarValor(int *);
char *generarCadena(char *);

typedef struct listaAlu{//this is a list of students
    char cedula[7];//this means id
    char *nombreApellido;//this means name and lastname
    short curso;//this means the year of the student in college/school
    unsigned short anho;//and this means year-E.g: 2017
};

int main(void){
    struct listaAlu *alu = NULL;
    int salir=1;
    char c;
    unsigned int cont = 0;
    unsigned int i;
    size_t size = 0;
    struct listaAlu *temp = NULL;
    while(salir!=0){//Condition until user press exit option
        printf("Agregar Alumno?Ingrese 1 para Agregar, y 0 para salir\n");//This means "Add student?Press 1 to add, and 0 to exit
        preguntarValor(&salir);//this verifies user input
        if(salir==1){//if user adds then it asks info of the student
            cont++;
            if ( NULL == ( temp = realloc ( alu, size + 2))) {//realloc for each character input and '\0'
                fprintf ( stderr, "realloc problem\n");
            }//this is for increasing the number of students
            alu = temp;
            printf("Ingrese Cedula:\n");//This means "Enter id"
            scanf("%s", &(alu+(size))->cedula);
            printf("Ingrese Nombre y Apellido:\n");//This means "Enter name and lastname"
            (alu+(size))->nombreApellido = generarCadena((alu+(size))->nombreApellido);
            printf("Ingrese Curso:\n");//This means enter college/school year
            scanf("%hd", &(alu+(size))->curso);
            printf("Ingrese Anho:\n");//and this means "Enter year"
            scanf("%hd", &(alu+(size))->anho);
            size++;
        }
    }
    for(i=0;i<cont;i++){
        printf("\tAlumno %d\n", i+1);
        printf("Nombre:\t%s\n", (alu+i)->nombreApellido);
        printf("Cedula:\t%s\n", (alu+i)->cedula);
        printf("Curso:\t%d\n", (alu+i)->curso);
        printf("Anho:\t%d\n", (alu+i)->anho);
    }//This prints Everything the user entered
    free(alu);
    return 0;
}//Sorry for writing my program entirely on the main >.<

void generarDimension(int bloques, void **ptr, int tamanho){
    void **ptrAux;
    *ptrAux = malloc(bloques * tamanho);
    if(*ptrAux==NULL){
        printf("No se pudo almacenar memoria\n");
    }else{
            *ptr = *ptrAux;
            free(ptrAux);
        }
}//this I didn't use, but it is for generating an array through a pointer
void reallocarDimensiones(int bloques, void **ptr, int tamanho){
    void **ptrAux;
    *ptrAux = realloc(*ptr,bloques * tamanho);
    if(*ptrAux==NULL){
        printf("No se pudo almacenar memoria\n");
    }else{
            *ptr = *ptrAux;
            free(ptrAux);
        }
}//This I didn't either, but it is for reallocating any given pointer

void preguntarValor(int *n){
    long entero, lector;
    *n=-2;
    do{
        printf("\nSi ingresa otro numero o caracter, vuelva a ingresar opcion\n");
        while(!scanf("%d", &entero)){
            while((lector=getchar()) !='\n' && lector !=EOF );
        }
        *n=entero;
    }while(*n>1 || *n<0);//You can change this parameters according to the numbers you want
}//This subrutine scans only integers between 1 and 0

char *generarCadena(char *scaneado){
    char *temp = NULL;
    int in = 0;
    size_t size = 0;

    while ( '\n' != ( in = getchar ( ))) {//loop until newline
        if ( NULL == ( temp = realloc ( scaneado, size + 2))) {//realloc for each character input and '\0'
            fprintf ( stderr, "realloc problem\n");
            return scaneado;
        }
        scaneado = temp;
        scaneado[size] = in;//set input
        scaneado[size + 1] = '\0';//terminate
        size++;
    }
    return scaneado;
}//This subrutine is for geting an input of chars of any given length

This is a program to store a college/school student list, I want to know how to improve this code, however in the part where I ask the user to enter strings, on the second one I can't enter anything. And if I try to enter more than 2 students, my code doesn't print all the info of the students I entered

Body:
struct listaAlu *temp = NULL;
temp = realloc ( alu, size + 2);//<- wrong size

realloc(alu, size + 2) will allocate only 2 bytes in the first run. But you need much more than that. The total size needed is number of elements in the array multiply by the size of the structure. That is sizeof(struct listaAlu) which is about 15 bytes.

realloc( alu, sizeof(struct listaAlu) * (size + 1) );

You don't need to increment the size by 2.

Make sure to check the input at the right places. Clear the input when scanf fails.

To get first name and last name, you can use fgets and strdup

There are major problems with generarDimension and reallocarDimensiones. You may want to leave those out.

struct listaAlu{
    char cedula[7];//this means id
    char *nombreApellido;//this means name and lastname
    short curso;//this means the year of the student in college/school
    unsigned short anho;//and this means year-E.g: 2017
};

void clear()
{
    int c;
    while((c = getchar()) != '\n' && c != EOF);
}

int main(void)
{
    struct listaAlu *alu = NULL;
    size_t size = 0;
    while(1)
    {
        alu = realloc( alu, sizeof(struct listaAlu) * (size + 1) );
        if (!alu)
        {
            fprintf(stderr, "realloc problem\n");
            break;
        }

        char buf[256] = { 0 };

        printf("Enter id:\n");
        fgets(buf, sizeof(buf), stdin);
        buf[strcspn(buf, "\r\n")] = 0;
        buf[sizeof(alu[size].cedula) - 1] = 0;
        strcpy(alu[size].cedula, buf);

        printf("Enter name and lastname:\n");
        fgets(buf, sizeof(buf), stdin);
        buf[strcspn(buf, "\r\n")] = 0;
        alu[size].nombreApellido = _strdup(buf);

        for(;;)
        {
            printf("Enter college/school year:\n");
            if (scanf("%hd", &alu[size].curso) == 1)
                break;

            printf("input error\n");
            clear();
        }

        for(;;)
        {
            printf("Enter year:\n");
            if (scanf("%hd", &alu[size].anho) == 1)
                break;

            printf("input error\n");
            clear();
        }

        size++;

        printf("Press 1 to continue\n");
        char input;
        scanf(" %c", &input);
        if(input != '1')
            break;
        clear();
    }

    for(size_t i = 0; i < size; i++)
    {
        printf("Alumno %d\n", i);
        printf("Nombre:\t%s\n", alu[i].nombreApellido);
        printf("Cedula:\t%s\n", alu[i].cedula);
        printf("Curso:\t%hd\n", alu[i].curso);
        printf("Anho:\t%hd\n", alu[i].anho);
    }

    for(size_t i = 0; i < size; i++)
        free(alu[i].nombreApellido);
    free(alu);
    return 0;
}

Edit

realloc does not need to be wrapped in a different function. But for fun purposes, you can do the following:

void* my_realloc1(void *ptr, int size)
{
    ptr = realloc(ptr, size);
    if (!ptr) printf("error\n");
    return ptr;
}

//usage:
alu = my_realloc1(alu, sizeof(struct listaAlu) * (size + 1));
if (!alu) printf("error\n");

my_realloc1 will work here, however nothing is gained. This is just extra lines of code. It's easier and more clear to use realloc directly and do the necessary error handling.

Another method is to pass a reference:

void my_realloc2(void **ptr, int size)
{
    *ptr = realloc(*ptr, size);
}

//usage: (*** Note the address `&` operator ***)
my_realloc2(&alu, sizeof(struct listaAlu) * (size + 1));
if (!alu) printf("error\n");

Again this will work, but it just adds more code.

The function generarCadena seems okay. You could simplify as follows:

char *my_getline()
{
    char *buf = NULL;
    int in = 0;
    size_t size = 0;
    while('\n' != (in = getchar()))
    {
        size++;
        buf = realloc(buf, size);
        buf[size - 1] = (char)in;
    }

    size++;
    buf = realloc(buf, size);
    buf[size - 1] = 0;

    return buf;
}

//usage:
printf("Enter name and lastname:\n");
alu[size].nombreApellido = my_getline();

And use scanf for to read 6 characters (because size of cedula is 7)

printf("Enter 6 characters:\n");
scanf("%6s", alu[size].cedula);
alu[size].cedula[6] = '\0';
clear();

To be safe, make sure the input is null terminated, and clear the buffer.

Or you can use fgets as I used in the example. This will read up to 256 characters:

char buf[256];
fgets(buf, sizeof(buf), stdin);

fgets is sometimes easier because you don't need to clear the buffer. But buf includes end of line character \n, you have to remove \n in this case.


Title: Using the asterisk (*) to specify width and precision in Go

Body:
fmt.Sprintf("%[3]*.[2]*[1]f", 12.0, 2, 6)

equivalent to

fmt.Sprintf("%6.2f", 12.0)


问:
Hide and Show angular 4 component depending on route
Hi there Im not sure if this is possible... basically I want to be able to show a component but only if the route matches and hide a component if the route matches Ive tried this app-header-home shows when the route is '/'which is good but app-header doesnt show at all even when the route inst '/' how can I fix this?

app.component.html

```<code><app-header *ngIf="router.url == '/'"><app-header>
<app-header-home *ngIf="router.url != '/'"></app-header-home> //component I want hidden unless url '/'
<router-outlet></router-outlet>
<app-footer></app-footer>
</code>```

app.component.ts

```<code>import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'app';

  constructor(
    private router: Router
  ) {

  }
}
</code>```

Thanks

答:
check the router.url in the template:

```<code><app-header><app-header>
<app-header-home *ngIf="router != '/ur_route'"></app-header-home> //component I want hidden unless url /home
<router-outlet></router-outlet>
<app-footer></app-footer>
</code>```

in app.component.ts inject the router.

```<code>export class AppComponent {
  title = 'app';
  router: string;

  constructor(private _router: Router){

          this.router = _router.url;
    }
}
</code>```

Body:
Hi there Im not sure if this is possible... basically I want to be able to show a component but only if the route matches and hide a component if the route matches Ive tried this app-header-home shows when the route is '/'which is good but app-header doesnt show at all even when the route inst '/' how can I fix this?

app.component.html

<app-header *ngIf="router.url == '/'"><app-header>
<app-header-home *ngIf="router.url != '/'"></app-header-home> //component I want hidden unless url '/'
<router-outlet></router-outlet>
<app-footer></app-footer>

app.component.ts

import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'app';

  constructor(
    private router: Router
  ) {

  }
}

Thanks

Body:
check the router.url in the template:

<app-header><app-header>
<app-header-home *ngIf="router != '/ur_route'"></app-header-home> //component I want hidden unless url /home
<router-outlet></router-outlet>
<app-footer></app-footer>

in app.component.ts inject the router.

export class AppComponent {
  title = 'app';
  router: string;

  constructor(private _router: Router){

          this.router = _router.url;
    }
}


问:
Inconsistent TitleBar Height returns
Long story short, I tried to run this particular code

```<code>CoreApplicationViewTitleBar coreTitleBar = CoreApplication.GetCurrentView().TitleBar;
coreTitleBar.ExtendViewIntoTitleBar = true;
dragarea.Height = coreTitleBar.Height;
HamBut.Margin = new Thickness(0, dragarea.Height, 0, 0);
Window.Current.SetTitleBar(dragarea);
</code>```

When I run it on the first time, coreTitleBar.Height returns 32. But, when I tried to re-run it, It returns 0.

Is this supposed to be a bug, or am I doing it wrong?

Currently using Visual Studio 2017 RC.

答:
It depends on when the code is run, and yes UWP isn't very consistent about it.

What the docs don't explicitly mention is that you need to subscribe to the coreTitleBar.LayoutMetricsChanged event and then update the height in the callback.  This will account for situations where the size of the title bar changed for some reason.

```<code>coreTitleBar.LayoutMetricsChanged += delegate
{
  dragarea.Height = coreTitleBar.Height;
  HamBut.Margin = new Thickness(0, dragarea.Height, 0, 0);
};
</code>```

And it also eliminates the "but it's zero sometimes" problem.

Title: Inconsistent TitleBar Height returns

Body:
Long story short, I tried to run this particular code

CoreApplicationViewTitleBar coreTitleBar = CoreApplication.GetCurrentView().TitleBar;
coreTitleBar.ExtendViewIntoTitleBar = true;
dragarea.Height = coreTitleBar.Height;
HamBut.Margin = new Thickness(0, dragarea.Height, 0, 0);
Window.Current.SetTitleBar(dragarea);

When I run it on the first time, coreTitleBar.Height returns 32. But, when I tried to re-run it, It returns 0.

Is this supposed to be a bug, or am I doing it wrong?

Currently using Visual Studio 2017 RC.

Body:
It depends on when the code is run, and yes UWP isn't very consistent about it.

What the docs don't explicitly mention is that you need to subscribe to the coreTitleBar.LayoutMetricsChanged event and then update the height in the callback.  This will account for situations where the size of the title bar changed for some reason.

coreTitleBar.LayoutMetricsChanged += delegate
{
  dragarea.Height = coreTitleBar.Height;
  HamBut.Margin = new Thickness(0, dragarea.Height, 0, 0);
};

And it also eliminates the "but it's zero sometimes" problem.


问:
java cannot return my variable from inherated class to super class
I have a superclass and an inherited class that's inheriting a variable called "answer"... I modify that variable in my inherted class but when i try to display it back in my super class it does not work! tried multiple ways, now i am losing my mind!

```<code>  class RightTriangle{
  public double answer;

  public RightTriangle(){} ;

  public double getAnswer(){return answer;}

  public double returnAnswer(){
     this.answer = answer;
     return answer;
  }
  public String toString(){
     return ("Answer: " + answer);
  }

 }

class sideAngle extends RightTriangle{
  public double nintyDegree = 90;
  private double sideA;
  private double angleB;
  private double answerUpdate;

  public sideAngle(double sideA, double angleB){
     this.sideA = sideA;
     this.angleB = angleB;
  }

  public void solveEquation(){
     angleB = Math.toRadians(angleB);
     answerUpdate = Math.tan(angleB);
     answer = sideA * answerUpdate;
     System.out.println(answer);
  }
 }
</code>```

I get a 0, instead of lets say a number that prints out right in my testing statement in solve Equation constructor !

also here is how I called/initialized them in my main(don't think i called wrong!).

```<code>sideAngle angleSide = new sideAngle(firstNum, secondNum);
angleSide.solveEquation();
RightTriangle getAnswer = new RightTriangle();
System.out.println(getAnswer.toString()); <<<<<<<<
</code>```

prints out a 0 !

答:
The two instance that you created, getAnswer and angleSide are two completely different objects. They do not interact in any way. In your case, angleSide calculated the answer, but there is no way, a new instance, getAnswer will know that.

Instead, I think what you want to do is to call toString() directly on the angleSide object. Since sideAngle is a child of RightTriangle, all instances of sideAngle knows about this toString() implementation. So calling angleSide.toString() will return you the answer.

Body:
I have a superclass and an inherited class that's inheriting a variable called "answer"... I modify that variable in my inherted class but when i try to display it back in my super class it does not work! tried multiple ways, now i am losing my mind!

  class RightTriangle{
  public double answer;

  public RightTriangle(){} ;

  public double getAnswer(){return answer;}

  public double returnAnswer(){
     this.answer = answer;
     return answer;
  }
  public String toString(){
     return ("Answer: " + answer);
  }

 }

class sideAngle extends RightTriangle{
  public double nintyDegree = 90;
  private double sideA;
  private double angleB;
  private double answerUpdate;

  public sideAngle(double sideA, double angleB){
     this.sideA = sideA;
     this.angleB = angleB;
  }

  public void solveEquation(){
     angleB = Math.toRadians(angleB);
     answerUpdate = Math.tan(angleB);
     answer = sideA * answerUpdate;
     System.out.println(answer);
  }
 }

I get a 0, instead of lets say a number that prints out right in my testing statement in solve Equation constructor !

also here is how I called/initialized them in my main(don't think i called wrong!).

sideAngle angleSide = new sideAngle(firstNum, secondNum);
angleSide.solveEquation();
RightTriangle getAnswer = new RightTriangle();
System.out.println(getAnswer.toString()); <<<<<<<<

prints out a 0 !


问:
Junit with maven program is not working
When i run this i am getting Initialization error and there is no console error.
I have attached my junit test code and pom.xml code. please help me with the solution. And its a Maven project.

Junit program:

```<code>import static org.junit.Assert.*;

import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;

public class JunitTest {

    @Test
    public void test() {
        // fail("Not yet implemented");
        System.out.println("Junit code");
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.amazon.in/");
        Select s = new Select(driver.findElement(By.id("searchDropdownBox")));
        s.selectByVisibleText("Books");
        driver.findElement(By.id("twotabsearchtextbox")).sendKeys("harry potter");
    }

}
</code>```

Pom.xml:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.testmaven</groupId>
  <artifactId>mavenDemo</artifactId>
  <version>0.0.1-SNAPSHOT</version>

  <dependencies>
 <!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-server -->
<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-server</artifactId>
    <version>3.5.2</version>
</dependency>
  </dependencies>
</project>
</code>```

答:
You need to define a build phase in POM for doing the compilation of integrated unit tests.

add this code snippet in pom.xml for running the test classes.

```<code><build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-failsafe-plugin</artifactId>
        <version>2.19.1</version>
        <executions>
          <execution>
            <goals>
              <goal>integration-test</goal>
              <goal>verify</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</code>```

You can find more information on:

http://maven.apache.org/surefire/maven-failsafe-plugin/usage.html

Title: Junit with maven program is not working

Body:
When i run this i am getting Initialization error and there is no console error.
I have attached my junit test code and pom.xml code. please help me with the solution. And its a Maven project.

Junit program:

import static org.junit.Assert.*;

import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;

public class JunitTest {

    @Test
    public void test() {
        // fail("Not yet implemented");
        System.out.println("Junit code");
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.amazon.in/");
        Select s = new Select(driver.findElement(By.id("searchDropdownBox")));
        s.selectByVisibleText("Books");
        driver.findElement(By.id("twotabsearchtextbox")).sendKeys("harry potter");
    }

}

Pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.testmaven</groupId>
  <artifactId>mavenDemo</artifactId>
  <version>0.0.1-SNAPSHOT</version>

  <dependencies>

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-server</artifactId>
    <version>3.5.2</version>
</dependency>
  </dependencies>
</project>

Body:
You need to define a build phase in POM for doing the compilation of integrated unit tests.

add this code snippet in pom.xml for running the test classes.

<build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-failsafe-plugin</artifactId>
        <version>2.19.1</version>
        <executions>
          <execution>
            <goals>
              <goal>integration-test</goal>
              <goal>verify</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

You can find more information on:

http://maven.apache.org/surefire/maven-failsafe-plugin/usage.html


问:
jquery selector doesn't work when html is replaced!
Please, help me with following problem:

```<code><!-- this is the visible code -->
<div id="divid">{some default content}<img class="img" src="GoNextArrow.jpg" alt=""></div>

<!-- this is a hidden list of contents -->
<div style="display: none;">
    <div id="divid1">{some content 1}<img class="img" src="GoNextArrow.jpg" alt=""></div>
    <div id="divid2">{some content 2}<img class="img" src="GoNextArrow.jpg" alt=""></div>
    <div id="divid3">{some content 3}<img class="img" src="GoNextArrow.jpg" alt=""></div>
    <div id="divid4">{some content 4}<img class="img" src="GoNextArrow.jpg" alt=""></div>
    <div id="divid5">{some content 5}<img class="img" src="GoNextArrow.jpg" alt=""></div>
</div>

<!-- this is an jquery script which replace the #divid with any of divid1-divid5 -->
$('#divid').hide().html(elem.html()).fadeIn();
<!-- elem is a variable, divid1 to divid5, e.g. var elem = $j('#divid'+id);  -->

<!-- I need a rollover effect, I made it so: -->
$('img.img').hover(function () {
    $(this).attr('src', 'GoNextArrowHover.jpg');
}, function () {
    $(this).attr('src', 'GoNextArrow.jpg');
});
</code>```

This works well for the first div divid, but doesn't for divid1-divid5 when these are loaded instead of divid.
Where is my mistake??

Thanks!

答:
Use jQuery live to bind the hover attempt. Live mens that the function will apply to all future elements that match the selector too.

http://api.jquery.com/live/

$(selector).live('hover', function() {});

Body:
Please, help me with following problem:

{some default content}

{some content 1}

{some content 2}

{some content 3}

{some content 4}

{some content 5}

$('#divid').hide().html(elem.html()).fadeIn();

$('img.img').hover(function () {
    $(this).attr('src', 'GoNextArrowHover.jpg');
}, function () {
    $(this).attr('src', 'GoNextArrow.jpg');
});

This works well for the first div divid, but doesn't for divid1-divid5 when these are loaded instead of divid.
Where is my mistake??

Thanks!


问:
What is the best way to avoid keyError when using python dictionary?
```<code>    for target, source ,in zip(self.tCorpus, self.fCorpus):
        #print(target, source)
        self.pairLength[len(target), len(source)] += 1
</code>```

It's obvious that this will give me a key error since I did not initialize the key len(target), len(source) before using this. I know I could use default dict to avoid this kind of error, but I am not sure how to avoid it in this particular case. Is there a way to prevent keyerror and increment values for len(target), len(source) ?

答:
Use a collections.defaultdict or collections.Counter. Any of these three will work:

```<code>self.pairLength = collections.defaultdict(int)
self.pairLength = collections.defaultdict(lambda: 0)
self.pairLength = collections.Counter()
</code>```

collections.Counter has the added advantage of giving you self.pairLength.most_common(10), which may be useful for your particular application.

If for whatever reason you can't use a new container, just make sure the key exists before doing anything:

```<code>for target, source ,in zip(self.tCorpus, self.fCorpus):
    key = (len(target), len(source))

    if key not in self.pairLength:
        self.pairLength[key] = 0

    self.pairLength[key] += 1
</code>```

Body:
    for target, source ,in zip(self.tCorpus, self.fCorpus):
        #print(target, source)
        self.pairLength[len(target), len(source)] += 1

It's obvious that this will give me a key error since I did not initialize the key len(target), len(source) before using this. I know I could use default dict to avoid this kind of error, but I am not sure how to avoid it in this particular case. Is there a way to prevent keyerror and increment values for len(target), len(source) ?

Body:
Use a collections.defaultdict or collections.Counter. Any of these three will work:

self.pairLength = collections.defaultdict(int)
self.pairLength = collections.defaultdict(lambda: 0)
self.pairLength = collections.Counter()

collections.Counter has the added advantage of giving you self.pairLength.most_common(10), which may be useful for your particular application.

If for whatever reason you can't use a new container, just make sure the key exists before doing anything:

for target, source ,in zip(self.tCorpus, self.fCorpus):
    key = (len(target), len(source))

    if key not in self.pairLength:
        self.pairLength[key] = 0

    self.pairLength[key] += 1