(origin_t, new_length, padding_token=0)
return new_t
If too long, cut the tensor; else pad the tensor.
  origin_t: [batch_size, time_steps_1] or [time_steps_1]
  new_t: [batch_size, time_steps_2] or [time_steps_2]
If too long, cut the tensor; else pad the tensor.
  origin_t: [batch_size, time_steps_1] or [time_steps_1]
  new_t: [batch_size, time_steps_2] or [time_steps_2]
If too long cut the tensor ; else pad the tensor . origin_t : [ batch_size time_steps_1 ] or [ time_steps_1 ] new_t : [ batch_size time_steps_2 ] or [ time_steps_2 ]
def cut_or_padding(origin_t, new_length, padding_token=0):
  """
  If too long, cut the tensor; else pad the tensor.
  origin_t: [batch_size, time_steps_1] or [time_steps_1]
  new_t: [batch_size, time_steps_2] or [time_steps_2]
  """

  if len(origin_t.get_shape()) == 1:
    dim = 1
    cur_length = tf.shape(origin_t)[0]
  elif len(origin_t.get_shape()) == 2:
    dim = 2
    cur_length = tf.shape(origin_t)[1]
  else:
    raise ValueError("origin_t should be a tensor with rank 1 or 2.")

  def cut_tensor():
    if dim == 1:
      new_t = origin_t[:new_length]
    else:
      new_t = origin_t[:, :new_length]
    return new_t

  def pad_tail_tensor():
    if dim == 1:
      shape = tf.constant([1, 2])
      indices = tf.constant([[0, 1]])
    else:
      shape = tf.constant([2, 2])
      indices = tf.constant([[1, 1]])
    updates = [new_length - cur_length]
    paddings = tf.scatter_nd(indices, updates, shape)
    new_t = tf.pad(
        origin_t, paddings, "CONSTANT", constant_values=padding_token)
    return new_t

  new_t = tf.cond(
      cur_length < new_length, true_fn=pad_tail_tensor, false_fn=cut_tensor)

  if dim == 1:
    new_t.set_shape([new_length])
  else:
    new_t.set_shape([origin_t.get_shape()[0], new_length])

  return new_t
def cut_or_padding ( origin_t , new_length , padding_token = 0 ) : if len ( origin_t . get_shape ( ) ) == 1 : dim = 1 cur_length = tf . shape ( origin_t ) [ 0 ] elif len ( origin_t . get_shape ( ) ) == 2 : dim = 2 cur_length = tf . shape ( origin_t ) [ 1 ] else : raise ValueError ( "origin_t should be a tensor with rank 1 or 2." ) def cut_tensor ( ) : if dim == 1 : new_t = origin_t [ : new_length ] else : new_t = origin_t [ : , : new_length ] return new_t def pad_tail_tensor ( ) : if dim == 1 : shape = tf . constant ( [ 1 , 2 ] ) indices = tf . constant ( [ [ 0 , 1 ] ] ) else : shape = tf . constant ( [ 2 , 2 ] ) indices = tf . constant ( [ [ 1 , 1 ] ] ) updates = [ new_length - cur_length ] paddings = tf . scatter_nd ( indices , updates , shape ) new_t = tf . pad ( origin_t , paddings , "CONSTANT" , constant_values = padding_token ) return new_t new_t = tf . cond ( cur_length < new_length , true_fn = pad_tail_tensor , false_fn = cut_tensor ) if dim == 1 : new_t . set_shape ( [ new_length ] ) else : new_t . set_shape ( [ origin_t . get_shape ( ) [ 0 ] , new_length ] ) return new_t