Shape is a tuple that may contain integers, shape symbols (tf, keras, theano) and UnknownSize (keras, mxnet)
        known axes can be integers or symbols, but not Nones
430190
def reconstruct_from_shape(self, shape, optimize=False):
        
        axes_lengths = list(self.elementary_axes_lengths)
        if self.ellipsis_positions != (math.inf, math.inf):
            if len(shape) < len(self.input_composite_axes) - 1:
                raise EinopsError('Expected at least {} dimensions, got {}'.format(
                    len(self.input_composite_axes) - 1, len(shape)))
        else:
            if len(shape) != len(self.input_composite_axes):
                raise EinopsError('Expected {} dimensions, got {}'.format(len(self.input_composite_axes), len(shape)))
        for input_axis, (known_axes, unknown_axes) in enumerate(self.input_composite_axes):
            before_ellipsis = input_axis
            after_ellipsis = input_axis + len(shape) - len(self.input_composite_axes)
            if input_axis == self.ellipsis_positions[0]:
                assert len(known_axes) == 0 and len(unknown_axes) == 1
                unknown_axis, = unknown_axes
                ellipsis_shape = shape[before_ellipsis:after_ellipsis + 1]
                if any(d is None for d in ellipsis_shape):
                    raise EinopsError("Couldn't infer shape for one or more axes represented by ellipsis")
                axes_lengths[unknown_axis] = _product(ellipsis_shape)
            else:
                if input_axis < self.ellipsis_positions[0]:
                    length = shape[before_ellipsis]
                else:
                    length = shape[after_ellipsis]
                known_product = 1
                for axis in known_axes:
                    known_product *= axes_lengths[axis]

                if len(unknown_axes) == 0:
                    if isinstance(length, int) and isinstance(known_product, int) and length != known_product:
                        raise EinopsError('Shape mismatch, {} != {}'.format(length, known_product))
                else:
                    if isinstance(length, int) and isinstance(known_product, int) and length % known_product != 0:
                        raise EinopsError("Shape mismatch, can't divide axis of length {} in chunks of {}".format(
                            length, known_product))

                    unknown_axis, = unknown_axes
                    axes_lengths[unknown_axis] = length // known_product

        init_shapes = axes_lengths
        reduced_axes_lengths = [dim for i, dim in enumerate(axes_lengths) if i not in self.reduced_elementary_axes]
        final_shapes = []
        for output_axis, grouping in enumerate(self.output_composite_axes):
            if output_axis == self.ellipsis_positions[1]:
                final_shapes.extend(ellipsis_shape)
            else:
                lengths = [reduced_axes_lengths[elementary_axis] for elementary_axis in grouping]
                if any(l is None for l in lengths):
                    final_shapes.append(None)
                else:
                    final_shapes.append(_product(lengths))
        reduced_axes = self.reduced_elementary_axes
        axes_reordering = self.final_axes_grouping_flat
        if optimize:
            return _optimize_transformation(init_shapes, reduced_axes, axes_reordering, final_shapes)
        else:
            return init_shapes, reduced_axes, axes_reordering, final_shapes
288039
def get_nn_classifier(X, y):
    
    assert type(X) is numpy.ndarray
    assert type(y) is numpy.ndarray
    assert len(X) == len(y)
    assert X.dtype == 'float32'
    assert y.dtype == 'int32'

    nn_pickled_filename = 'is_one_symbol_classifier.pickle'
    if os.path.isfile(nn_pickled_filename):
        with open(nn_pickled_filename, 'rb') as handle:
            get_output = pickle.load(handle)
    else:
        get_output = train_nn_segmentation_classifier(X, y)
        with open(nn_pickled_filename, 'wb') as handle:
            pickle.dump(get_output, handle, protocol=pickle.HIGHEST_PROTOCOL)
    return get_output
733603
def _broadcast_shapes(s1, s2):
    """"""

    n1 = len(s1)
    n2 = len(s2)
    n = max(n1, n2)
    res = [1] * n

    for i in range(n):
        if i >= n1:
            c1 = 1
        else:
            c1 = s1[n1-1-i]

        if i >= n2:
            c2 = 1
        else:
            c2 = s2[n2-1-i]

        if c1 == 1:
            rc = c2
        elif c2 == 1 or c1 == c2:
            rc = c1
        else:
            raise ValueError('array shapes %r and %r are not compatible' % (s1, s2))

        res[n-1-i] = rc

    return tuple(res)
795355
def set_input_shape(self, input_shape):
    batch_size, rows, cols, input_channels = input_shape
    # assert self.mode == 'train' or self.mode == 'eval'
    """"""
    input_shape = list(input_shape)
    input_shape[0] = 1
    dummy_batch = tf.zeros(input_shape)
    dummy_output = self.fprop(dummy_batch)
    output_shape = [int(e) for e in dummy_output.get_shape()]
    output_shape[0] = batch_size
    self.output_shape = tuple(output_shape)
907572
def generate(self, x, **kwargs):
    
    self.parse_params(**kwargs)
    shape = [int(i) for i in x.get_shape().as_list()[1:]]

    assert self.sess is not None, \
        'Cannot use `generate` when no `sess` was provided'
    _check_first_dimension(x, 'input')
    if self.y_target is not None:
      _check_first_dimension(self.y_target, 'y_target')
      assert self.image_target is not None, \
          'Require a target image for targeted attack.'
      _check_first_dimension(self.image_target, 'image_target')

    # Set shape and d.
    self.shape = shape
    self.d = int(np.prod(shape))

    # Set binary search threshold.
    if self.constraint == 'l2':
      self.theta = self.gamma / np.sqrt(self.d)
    else:
      self.theta = self.gamma / self.d

    # Construct input placeholder and output for decision function.
    self.input_ph = tf.placeholder(
        tf_dtype, [None] + list(self.shape), name='input_image')
    self.logits = self.model.get_logits(self.input_ph)

    def bapp_wrap(x, target_label, target_image):
      """ Wrapper to use tensors as input and output. """
      return np.array(self._bapp(x, target_label, target_image),
                      dtype=self.np_dtype)

    if self.y_target is not None:
      # targeted attack that requires target label and image.
      wrap = tf.py_func(bapp_wrap,
                        [x[0], self.y_target[0], self.image_target[0]],
                        self.tf_dtype)
    else:
      if self.image_target is not None:
        # untargeted attack with an initialized image.
        wrap = tf.py_func(lambda x, target_image: bapp_wrap(x,
                                                            None, target_image),
                          [x[0], self.image_target[0]],
                          self.tf_dtype)
      else:
        # untargeted attack without an initialized image.
        wrap = tf.py_func(lambda x: bapp_wrap(x, None, None),
                          [x[0]],
                          self.tf_dtype)

    wrap.set_shape(x.get_shape())

    return wrap
203678
def get_output_shape(sym, **input_shapes):
        """"""
        _, s_outputs, _ = sym.infer_shape(**input_shapes)
        return dict(zip(sym.list_outputs(), s_outputs))
1005526
def is_valid_shape(value):
    """"""
    if is_int_positive(value):
        return True, value
    elif isinstance(value, tuple) or isinstance(value, list):
        for v in value:
            if not is_int_positive(v):
                return False, value
        return True, value
    else:
        return False, value
770649
def _conv_shape_tuple(self, lhs_shape, rhs_shape, strides, pads):
    """"""
    if isinstance(pads, str):
      pads = padtype_to_pads(lhs_shape[2:], rhs_shape[2:], strides, pads)
    if len(pads) != len(lhs_shape) - 2:
      msg = 'Wrong number of explicit pads for conv: expected {}, got {}.'
      raise TypeError(msg.format(len(lhs_shape) - 2, len(pads)))
    lhs_padded = onp.add(lhs_shape[2:], onp.add(*zip(*pads)))
    out_space = onp.floor_divide(
        onp.subtract(lhs_padded, rhs_shape[2:]), strides) + 1
    out_space = onp.maximum(0, out_space)
    out_shape = (lhs_shape[0], rhs_shape[0]) + tuple(out_space)
    return tuple(out_shape)
1077115
def _verify_shape_compatibility(self, img, img_type):
        """"""

        if self.input_image.shape[:-1] != img.shape:
            raise ValueError('Shape of the {} ({}) is not compatible '
                             'with input image shape: {} '
                             ''.format(img_type, img.shape, self.input_image.shape[:-1]))
992216
def calculate_flatten_output_shapes(operator):
    '''
    
    '''
    check_input_and_output_numbers(operator, input_count_range=1, output_count_range=1)
    check_input_and_output_types(operator, good_input_types=[FloatTensorType])

    input = operator.inputs[0]
    output = operator.outputs[0]

    if len(input.type.shape) not in [2, 4]:
        raise RuntimeError('Input must be 2-D or 4-D float tensor')

    input_shape = input.type.shape
    output_shape = [input_shape[0], 1]

    # Calculate the multiplication of C, H, and W.
    for i in input_shape[1:]:
        if i != 'None':
            output_shape[1] *= i
        else:
            # If any of C, H, W-dimensions is unknown, the flatten C-dimension is unknown
            output_shape[1] = 'None'
            break

    output.type.shape = output_shape
333007
def get_input_shape(sym, proto_obj):
    """"""
    arg_params = proto_obj.arg_dict
    aux_params = proto_obj.aux_dict

    model_input_shape = [data[1] for data  in proto_obj.model_metadata.get('input_tensor_data')]
    data_names = [data[0] for data  in proto_obj.model_metadata.get('input_tensor_data')]

    # creating dummy inputs
    inputs = []
    for  in_shape in model_input_shape:
        inputs.append(nd.ones(shape=in_shape))

    data_shapes = []
    for idx, input_name in enumerate(data_names):
        data_shapes.append((input_name, inputs[idx].shape))

    ctx = context.cpu()
    # create a module
    mod = module.Module(symbol=sym, data_names=data_names, context=ctx, label_names=None)
    mod.bind(for_training=False, data_shapes=data_shapes, label_shapes=None)
    mod.set_params(arg_params=arg_params, aux_params=aux_params)

    data_forward = []
    for idx, input_name in enumerate(data_names):
        val = inputs[idx]
        data_forward.append(val)

    mod.forward(io.DataBatch(data_forward))
    result = mod.get_outputs()[0].asnumpy()

    return result.shape
126420
def shape(self):
        
        if self.__x is not None:
            if self.isdiagonal:
                return (max(self.__x.shape), max(self.__x.shape))
            if len(self.__x.shape) == 1:
                raise Exception("Matrix.shape: Matrix objects must be 2D")
            return self.__x.shape
        return None
1092479
def fluent_shape(self) -> Sequence[int]:
        ''''''
        return tuple(self._shape.as_list()[1:] if self._batch else self._shape.as_list()[:])
467416
def shape_list(x):
  """"""
  x = tf.convert_to_tensor(x)

  # If unknown rank, return dynamic shape
  if x.get_shape().dims is None:
    return tf.shape(x)

  static = x.get_shape().as_list()
  shape = tf.shape(x)

  ret = []
  for i, dim in enumerate(static):
    if dim is None:
      dim = shape[i]
    ret.append(dim)
  return ret
713407
def _check_2d_shape(X):
    
    if X.dtype.names is None and len(X.shape) != 2:
        raise ValueError('X needs to be 2-dimensional, not '
                         '{}-dimensional.'.format(len(X.shape)))
77517
def ensure_shape(core, shape, shape_):
    """"""
    core = core.copy()
    if shape is None:
        shape = shape_
    elif isinstance(shape, int):
        shape = (shape,)

    if tuple(shape) == tuple(shape_):
        return core, shape

    ones = np.ones(shape, dtype=int)
    for key, val in core.items():
        core[key] = val*ones

    return core, shape
1081181
def _shape_list(tensor):
  """"""
  # Get statically known shape (may contain None's for unknown dimensions)
  shape = tensor.get_shape().as_list()

  # Ensure that the shape values are not None
  dynamic_shape = tf.shape(tensor)
  for i in range(len(shape)):
    if shape[i] is None:
      shape[i] = dynamic_shape[i]
  return shape