Converts the layer from KAF to NAF
967178
def to_kaf(self):
        
        if self.type == 'NAF':
            for node in self.__get_entity_nodes():
                node.set('eid',node.get('id'))
                del node.attrib['id']
1193483
def from_top_left(from_layer=nil, f=nil)
      if from_layer.is_a?(Hash)
        f = from_layer
        from_layer = nil
      end
      f ||= {}
      from_layer ||= target.superlayer
      _calculate_frame(f, from: from_layer, relative_to: { x: :min, y: :min })
    end
914455
def convert_separable_convolution(builder, layer, input_names, output_names, keras_layer):
    
    _check_data_format(keras_layer)

    # Get input and output names
    input_name, output_name = (input_names[0], output_names[0])

    has_bias = keras_layer.use_bias

    # Get the weights from _keras.
    weight_list = keras_layer.get_weights()
    output_blob_shape = list(filter(None, keras_layer.output_shape))
    output_channels = output_blob_shape[-1]

    # D: depth mutliplier
    # w[0] is (H,W,Cin,D)
    # w[1] is (1,1,Cin * D, Cout)
    W0 = weight_list[0]
    W1 = weight_list[1]
    height, width, input_channels, depth_mult = W0.shape
    b = weight_list[2] if has_bias else None

    W0 = _np.reshape(W0, (height, width, 1, input_channels * depth_mult))

    stride_height, stride_width = keras_layer.strides

    # Dilations
    if (type(keras_layer.dilation_rate) is list) or (type(keras_layer.dilation_rate) is tuple):
        dilations = [keras_layer.dilation_rate[0], keras_layer.dilation_rate[1]]
    else:
        dilations = [keras_layer.dilation_rate, keras_layer.dilation_rate]

    intermediate_name = output_name + '_intermin_'

    builder.add_convolution(name = layer + '_step_1',
             kernel_channels = 1,
             output_channels = input_channels * depth_mult,
             height = height,
             width = width,
             stride_height = stride_height,
             stride_width = stride_width,
             border_mode = keras_layer.padding,
             groups = input_channels,
             W = W0,
             b = None,
             has_bias = False,
             is_deconv = False,
             output_shape = None,
             input_name = input_name,
             output_name = intermediate_name,
             dilation_factors = dilations)

    builder.add_convolution(name = layer + '_step_2',
             kernel_channels = input_channels * depth_mult,
             output_channels = output_channels,
             height = 1,
             width = 1,
             stride_height = 1,
             stride_width = 1,
             border_mode = keras_layer.padding,
             groups = 1,
             W = W1,
             b = b,
             has_bias = has_bias,
             is_deconv = False,
             output_shape = None,
             input_name = intermediate_name,
             output_name = output_name,
             dilation_factors = [1,1])
554948
private void RGBtoHSV(float red, float green, float blue) {

        float min = 0;
        float max = 0;
        float delta = 0;

        min = MIN(red, green, blue);
        max = MAX(red, green, blue);

        m_bri = max; // v

        delta = max - min;

        if (max != 0) {
            m_sat = delta / max; // s
        } else {
            m_sat = 0;
            m_hue = 0;
            return;
        }

        if (delta == 0) {
            m_hue = 0;
            return;
        }

        if (red == max) {
            m_hue = (green - blue) / delta;
        } else if (green == max) {
            m_hue = 2 + ((blue - red) / delta);
        } else {
            m_hue = 4 + ((red - green) / delta);
        }

        m_hue *= 60;

        if (m_hue < 0) {
            m_hue += 360;
        }
    }
703706
def tan(cls, x: 'TensorFluent') -> 'TensorFluent':
        '''
        '''
        return cls._unary_op(x, tf.tan, tf.float32)
943203
def nan_maximum_filter(arr, ksize):
    '''
    
    '''
    out = np.empty_like(arr)
    _calc(arr, out, ksize//2)
    return out
315173
def to_kaf(self):
        

        if self.type == 'NAF':
            self.root.tag = 'KAF'
            self.type = 'KAF'

        ## Convert the header
        if self.header is not None:
            self.header.to_kaf()

        ## Convert the token layer
        if self.text_layer is not None:
            self.text_layer.to_kaf()

        ## Convert the term layer
        if self.term_layer is not None:
            self.term_layer.to_kaf()


        ## Convert the chunk layer
        if self.chunk_layer is not None:
            self.chunk_layer.to_kaf()

        ## Convert the entity layer
        if self.entity_layer is not None:
            self.entity_layer.to_kaf()

        ## Convert the features layer
        ## There is no feature layer defined in NAF, but we assumed
        ## that is defined will be followin the same rules
        if self.features_layer is not None:
            self.features_layer.to_kaf()


        ##Convert the opinion layer
        if self.opinion_layer is not None:
            self.opinion_layer.to_kaf()

        ## Convert the constituency layer
        ## This layer is exactly the same in KAF/NAF
        if self.constituency_layer is not None:
            self.constituency_layer.to_kaf()    #Does nothing...


        ## Convert the dedepency layer
        ## It is not defined on KAF so we assme both will be similar
        if self.dependency_layer is not None:
            self.dependency_layer.to_kaf()

        if self.coreference_layer is not None:
            self.coreference_layer.to_kaf()


        ## Convert the temporalRelations layer
        ## It is not defined on KAF so we assme both will be similar
        if self.temporalRelations_layer is not None:
            self.temporalRelations_layer.to_kaf()

        ## Convert the causalRelations layer
        ## It is not defined on KAF so we assme both will be similar
        if self.causalRelations_layer is not None:
            self.causalRelations_layer.to_kaf()

        ## Convert the factualitylayer
        ## It is not defined on KAF so we assme both will be similar
        if self.factuality_layer is not None:
            self.factuality_layer.to_kaf()


        ## Convert the attribution_layer
        ## It is not defined on KAF so we assme both will be similar
        if self.attribution_layer is not None:
            self.attribution_layer.to_kaf()
1354469
def convert_upsample(builder, layer, input_names, output_names, keras_layer):
    
    _check_data_format(keras_layer)
    # Get input and output names
    input_name, output_name = (input_names[0], output_names[0])

    is_1d = isinstance(keras_layer, _keras.layers.UpSampling1D)

    # Currently, we only support upsample of same dims
    fh = fw = 1
    if is_1d:
        if type(keras_layer.size) is tuple and len(keras_layer.size) == 1:
            fh, fw = 1, keras_layer.size[0]
        elif type(keras_layer.size) is int:
            fh, fw = 1, keras_layer.size
        else:
            raise ValueError("Unrecognized upsample factor format %s" % (str(keras_layer.size)))
    else:
        if type(keras_layer.size) is int:
            fh = fw = keras_layer.size
        elif len(keras_layer.size) == 2:
            if keras_layer.size[0] != keras_layer.size[1]:
                raise ValueError("Upsample with different rows and columns not supported.")
            else:
                fh = keras_layer.size[0]
                fw = keras_layer.size[1]
        else:
            raise ValueError("Unrecognized upsample factor format %s" % (str(keras_layer.size)))

    builder.add_upsample(name = layer,
             scaling_factor_h = fh,
             scaling_factor_w = fw,
             input_name = input_name,
             output_name = output_name)
1091467
def convert_lstm(builder, layer, input_names, output_names, keras_layer):
    

    hidden_size = keras_layer.output_dim
    input_size = keras_layer.input_shape[-1]
    if keras_layer.consume_less not in ['cpu', 'gpu']:
        raise ValueError('Cannot convert Keras layer with consume_less = %s' % keras_layer.consume_less)

    output_all = keras_layer.return_sequences
    reverse_input = keras_layer.go_backwards

    # Keras: I C F O; W_x, W_h, b
    # CoreML: I F O G; W_h and W_x are separated
    W_h, W_x, b = ([], [], [])
    if keras_layer.consume_less == 'cpu':
        W_h.append(keras_layer.get_weights()[1].T)
        W_h.append(keras_layer.get_weights()[7].T)
        W_h.append(keras_layer.get_weights()[10].T)
        W_h.append(keras_layer.get_weights()[4].T)

        W_x.append(keras_layer.get_weights()[0].T)
        W_x.append(keras_layer.get_weights()[6].T)
        W_x.append(keras_layer.get_weights()[9].T)
        W_x.append(keras_layer.get_weights()[3].T)

        b.append(keras_layer.get_weights()[2])
        b.append(keras_layer.get_weights()[8])
        b.append(keras_layer.get_weights()[11])
        b.append(keras_layer.get_weights()[5])
    else:
        keras_W_h = keras_layer.get_weights()[1].T
        W_h.append(keras_W_h[0 * hidden_size:][:hidden_size])
        W_h.append(keras_W_h[1 * hidden_size:][:hidden_size])
        W_h.append(keras_W_h[3 * hidden_size:][:hidden_size])
        W_h.append(keras_W_h[2 * hidden_size:][:hidden_size])

        keras_W_x = keras_layer.get_weights()[0].T
        W_x.append(keras_W_x[0 * hidden_size:][:hidden_size])
        W_x.append(keras_W_x[1 * hidden_size:][:hidden_size])
        W_x.append(keras_W_x[3 * hidden_size:][:hidden_size])
        W_x.append(keras_W_x[2 * hidden_size:][:hidden_size])

        keras_b = keras_layer.get_weights()[2]
        b.append(keras_b[0 * hidden_size:][:hidden_size])
        b.append(keras_b[1 * hidden_size:][:hidden_size])
        b.append(keras_b[3 * hidden_size:][:hidden_size])
        b.append(keras_b[2 * hidden_size:][:hidden_size])

    # Set activation type
    inner_activation_str = _get_recurrent_activation_name_from_keras(keras_layer.inner_activation)
    activation_str = _get_recurrent_activation_name_from_keras(keras_layer.activation)

    # Add to the network
    builder.add_unilstm(
        name = layer,
        W_h = W_h, W_x = W_x, b = b,
        hidden_size = hidden_size,
        input_size = input_size,
        input_names = input_names,
        output_names = output_names,
        inner_activation = inner_activation_str,
        cell_state_update_activation = activation_str,
        output_activation = activation_str,
        output_all = output_all,
        reverse_input = reverse_input)
399936
def convert(self, values, nan_rep, encoding, errors):
        

        self.values = Int64Index(np.arange(self.table.nrows))
        return self
120755
def share_nans(self):
        

        def f(_, s, channels):
            outs = wt_kit.share_nans(*[c[s] for c in channels])
            for c, o in zip(channels, outs):
                c[s] = o

        self.channels[0].chunkwise(f, self.channels)
907265
def to_kaf(self):
        
        if self.type == 'NAF':
            for node in self.__get_opinion_nodes():
                node.set('oid',node.get('id'))
                del node.attrib['id']
1321308
def to_rgba(colors, dtype=np.uint8):
    
    if not util.is_sequence(colors):
        return

    # colors as numpy array
    colors = np.asanyarray(colors)

    # integer value for opaque alpha given our datatype
    opaque = np.iinfo(dtype).max

    if (colors.dtype.kind == 'f' and colors.max() < (1.0 + 1e-8)):
        colors = (colors * opaque).astype(dtype)
    elif (colors.max() <= opaque):
        colors = colors.astype(dtype)
    else:
        raise ValueError('colors non- convertible!')

    if util.is_shape(colors, (-1, 3)):
        # add an opaque alpha for RGB colors
        colors = np.column_stack((
            colors,
            opaque * np.ones(len(colors)))).astype(dtype)
    elif util.is_shape(colors, (3,)):
        # if passed a single RGB color add an alpha
        colors = np.append(colors, opaque)

    if not (util.is_shape(colors, (4,)) or
            util.is_shape(colors, (-1, 4))):
        raise ValueError('Colors not of appropriate shape!')

    return colors
1225049
def da2cf(dataarray, epoch=EPOCH):
        """"""
        new_data = dataarray.copy()

        # Remove the area
        new_data.attrs.pop('area', None)

        anc = [ds.attrs['name']
               for ds in new_data.attrs.get('ancillary_variables', [])]
        if anc:
            new_data.attrs['ancillary_variables'] = ' '.join(anc)
        # TODO: make this a grid mapping or lon/lats
        # new_data.attrs['area'] = str(new_data.attrs.get('area'))
        for key, val in new_data.attrs.copy().items():
            if val is None:
                new_data.attrs.pop(key)
        new_data.attrs.pop('_last_resampler', None)

        if 'time' in new_data.coords:
            new_data['time'].encoding['units'] = epoch
            new_data['time'].attrs['standard_name'] = 'time'
            new_data['time'].attrs.pop('bounds', None)
            if 'time' not in new_data.dims:
                new_data = new_data.expand_dims('time')

        if 'x' in new_data.coords:
            new_data['x'].attrs['standard_name'] = 'projection_x_coordinate'
            new_data['x'].attrs['units'] = 'm'

        if 'y' in new_data.coords:
            new_data['y'].attrs['standard_name'] = 'projection_y_coordinate'
            new_data['y'].attrs['units'] = 'm'

        new_data.attrs.setdefault('long_name', new_data.attrs.pop('name'))
        if 'prerequisites' in new_data.attrs:
            new_data.attrs['prerequisites'] = [np.string_(str(prereq)) for prereq in new_data.attrs['prerequisites']]
        return new_data
351431
def _to_array(self, alpha, normalization='4pi', csphase=1):
        
        if self.coeffs is None:
            coeffs = _np.copy(self._taper2coeffs(alpha))
        else:
            if alpha > self.nrot - 1:
                raise ValueError('alpha must be less than or equal to ' +
                                 'nrot - 1. alpha = {:d}, nrot = {:d}'
                                 .format(alpha, self.nrot))
            coeffs = _shtools.SHVectorToCilm(self.coeffs[:, alpha])

        if normalization == 'schmidt':
            for l in range(self.lmax + 1):
                coeffs[:, l, :l+1] *= _np.sqrt(2.0 * l + 1.0)
        elif normalization == 'ortho':
            coeffs *= _np.sqrt(4.0 * _np.pi)

        if csphase == -1:
            for m in range(self.lmax + 1):
                if m % 2 == 1:
                    coeffs[:, :, m] = - coeffs[:, :, m]

        return coeffs
569797
def convert_flatten(builder, layer, input_names, output_names, keras_layer):
    
    input_name, output_name = (input_names[0], output_names[0])

    # blob_order == 0 if the input blob needs not be rearranged
    # blob_order == 1 if the input blob needs to be rearranged
    blob_order = 0

    # using keras_layer.input.shape have a "?" (Dimension[None] at the front),
    # making a 3D tensor with unknown batch size 4D
    if len(keras_layer.input.shape) == 4:
        blob_order = 1

    builder.add_flatten(name=layer, mode=blob_order, input_name=input_name, output_name=output_name)
1325301
def float_to_knx2(floatval):
    """"""

    if floatval < -671088.64 or floatval > 670760.96:
        raise KNXException("float {} out of valid range".format(floatval))

    floatval = floatval * 100

    i = 0
    for i in range(0, 15):
        exp = pow(2, i)
        if ((floatval / exp) >= -2048) and ((floatval / exp) < 2047):
            break

    if floatval < 0:
        sign = 1
        mantisse = int(2048 + (floatval / exp))
    else:
        sign = 0
        mantisse = int(floatval / exp)

    return [(sign << 7) + (i << 3) + (mantisse >> 8),
            mantisse & 0xff]