Allowed input/output patterns are
        1. [N, C, H, W] ---> [N, C * B * B , H / B, W / B]
        2. [N, C, H, W] ---> [N, C / B / B , H * B, W * B]

    Note taht B is the block size specified in this operator.
766812
def calculate_reorganize_data_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])

    output_shape = copy.deepcopy(operator.inputs[0].type.shape)

    params = operator.raw_operator.reorganizeData

    from coremltools.proto.NeuralNetwork_pb2 import ReorganizeDataLayerParams as Params

    if params.mode == Params.DEPTH_TO_SPACE:
        if output_shape[1] % (params.blockSize * params.blockSize) != 0:
            raise RuntimeError('Channel number must be divisible by the square of block size')

        output_shape = [output_shape[0], output_shape[1] / params.blockSize / params.blockSize,
                        output_shape[2] * params.blockSize, output_shape[3] * params.blockSize]
    elif params.mode == Params.SPACE_TO_DEPTH:
        if output_shape[2] % params.blockSize != 0 or output_shape[3] % params.blockSize != 0:
            raise RuntimeError('Height and weight must be divisible by block size')

        output_shape = [output_shape[0], output_shape[1] * params.blockSize * params.blockSize,
                        output_shape[2] / params.blockSize, output_shape[3] / params.blockSize]
    else:
        raise ValueError('Unsupport reorganization mode {0}'.format(params.mode))

    operator.outputs[0].type = FloatTensorType([int(i) if i != 'None' else 'None' for i in output_shape],
                                               doc_string=operator.outputs[0].type.doc_string)
198637
def p_block(self, p):
        
        n = len(p)
        if n == 4:
            p[0] = ['block', p[1], p[2], p[3]]
        elif n == 3:
            p[0] = ['block', p[1],  [], p[2]]
        else:
            p[0] = ['block', p[1], [], p[1]]

        if self.options.get('lowercasenames'):
            for tag in (1, 3):
                p[0][tag] = p[0][tag].lower()
678119
def split_block_by_row_length(block, split_row_length):
    '''
    
    '''
    split_blocks = []
    current_block = []
    for row in block:
        if row_content_length(row) <= split_row_length:
            if current_block:
                split_blocks.append(current_block)
            split_blocks.append([row])
            current_block = []
        else:
            current_block.append(row)
    if current_block:
        split_blocks.append(current_block)

    return split_blocks
157875
def calculate_reshape_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])

    params = operator.raw_operator.reshape

    output_shape = list(int(i) for i in params.targetShape)

    if len(output_shape) == 3:
        output_shape = [operator.inputs[0].type.shape[0]] + output_shape

    operator.outputs[0].type.shape = output_shape
1374907
def calculate_bidirectional_lstm_output_shapes(operator):
    '''
    
    '''
    check_input_and_output_numbers(operator, input_count_range=[1, 5], output_count_range=[1, 5])
    check_input_and_output_types(operator, good_input_types=[FloatTensorType])

    input_shape = operator.inputs[0].type.shape

    # LSTM accepts [N, C] and [N, C, 1, 1] inputs
    if len(input_shape) not in [2, 4]:
        raise RuntimeError('Input must be a 2-D or 4-D tensor')

    params = operator.raw_operator.biDirectionalLSTM
    # The following line is more accurate but it may break some tests
    # output_shape = ['None', params.outputVectorSize] if params.params.sequenceOutput else [1, 2 *params.outputVectorSize]
    output_shape = ['None', 2 * params.outputVectorSize]
    state_shape = [1, params.outputVectorSize]

    # TODO: Changing input shapes of an operator is dangerous, this should be move to Topology's _fix_shapes function
    if len(operator.inputs) > 1:
        Y_h_in = operator.inputs[1]  # The forward initial hidden state of a single sequence
        Y_h_in.type.shape = state_shape
        Y_h_rev_in = operator.inputs[3]  # The backward initial hidden state of a single sequence
        Y_h_rev_in.type.shape = state_shape
    if len(operator.inputs) > 2:
        Y_c_in = operator.inputs[2]  # The forward initial cell state of a single sequence
        Y_c_in.type.shape = state_shape
        Y_c_rev_in = operator.inputs[4]  # The backward initial cell state of a single sequence
        Y_c_rev_in.type.shape = state_shape

    operator.outputs[0].type.shape = output_shape
    if len(operator.outputs) > 1:
        operator.outputs[1].type.shape = state_shape
        operator.outputs[3].type.shape = state_shape
    if len(operator.outputs) > 2:
        operator.outputs[2].type.shape = state_shape
        operator.outputs[4].type.shape = state_shape
526397
def pad(self, data, block_size):
		
		padding_symbol = self.padding_symbol()

		blocks_count = (len(data) // block_size)
		if (len(data) % block_size) != 0:
			blocks_count += 1

		total_length = blocks_count * block_size
		return self._fill(data, total_length, padding_symbol)
1284314
def get_block_start(lines, lineno, maximum_indents=80):
    """"""
    pattern = get_block_start_patterns()
    for i in range(lineno, 0, -1):
        match = pattern.search(lines.get_line(i))
        if match is not None and \
           count_line_indents(lines.get_line(i)) <= maximum_indents:
            striped = match.string.lstrip()
            # Maybe we're in a list comprehension or generator expression
            if i > 1 and striped.startswith('if') or striped.startswith('for'):
                bracs = 0
                for j in range(i, min(i + 5, lines.length() + 1)):
                    for c in lines.get_line(j):
                        if c == '#':
                            break
                        if c in '[(':
                            bracs += 1
                        if c in ')]':
                            bracs -= 1
                            if bracs < 0:
                                break
                    if bracs < 0:
                        break
                if bracs < 0:
                    continue
            return i
    return 1
151654
def _bounded(p1, p2, line, pos, line_no, lines):
    """"""
    substrings = []
    start_line_no = line_no
    end = pos
    while not line.startswith(p2, end):
        if line[end] == '\\':
            end += 2
        else:
            end += 1
        if end >= len(line):
            substrings.append(line[pos:])
            try:
                line_no, line = next(lines)
            except StopIteration:
                pattern = 'docstring' if p1 == '"""' else 'block comment'
                raise TdlParsingError('Unterminated {}'.format(pattern),
                                      line_number=start_line_no)
            pos = end = 0
    substrings.append(line[pos:end])
    end += len(p2)
    return ''.join(substrings), start_line_no, line_no, line, end
882424
public static DMatrixRBlock initializeQ(DMatrixRBlock Q,
                                              int numRows , int numCols , int blockLength ,
                                              boolean compact) {
        int minLength = Math.min(numRows,numCols);
        if( compact ) {
            if( Q == null ) {
                Q = new DMatrixRBlock(numRows,minLength,blockLength);
                MatrixOps_DDRB.setIdentity(Q);
            } else {
                if( Q.numRows != numRows || Q.numCols != minLength ) {
                    throw new IllegalArgumentException("Unexpected matrix dimension. Found "+Q.numRows+" "+Q.numCols);
                } else {
                    MatrixOps_DDRB.setIdentity(Q);
                }
            }
        } else {
            if( Q == null ) {
                Q = new DMatrixRBlock(numRows,numRows,blockLength);
                MatrixOps_DDRB.setIdentity(Q);
            } else {
                if( Q.numRows != numRows || Q.numCols != numRows ) {
                    throw new IllegalArgumentException("Unexpected matrix dimension. Found "+Q.numRows+" "+Q.numCols);
                } else {
                    MatrixOps_DDRB.setIdentity(Q);
                }
            }
        }
        return Q;
    }
142649
public static DMatrixRBlock identity(int numRows, int numCols, int blockLength ) {
        DMatrixRBlock A = new DMatrixRBlock(numRows,numCols,blockLength);

        int minLength = Math.min(numRows,numCols);

        for( int i = 0; i < minLength; i += blockLength ) {
            int h = Math.min(blockLength,A.numRows-i);
            int w = Math.min(blockLength,A.numCols-i);

            int index = i*A.numCols + h*i;

            int m = Math.min(h,w);
            for( int k = 0; k < m; k++ ) {
                A.data[index + k*w + k ] = 1;
            }
        }

        return A;
    }
1100053
def block_reduce(self, block_size, how=np.ma.mean):
        '''
        
        '''
        raster2 = block_reduce(self.raster, block_size, func=how)
        geot = self.geot
        geot = (geot[0], block_size[0] * geot[1], geot[2], geot[3], geot[4],
                block_size[1] * geot[-1])
        return GeoRaster(raster2, geot, nodata_value=self.nodata_value,\
                        projection=self.projection, datatype=self.datatype)
382459
private static void multBlockAdd( double []blockA, double []blockB, double []blockC,
                                     final int m, final int n, final int o,
                                     final int blockLength ) {
//        for( int i = 0; i < m; i++ ) {
//            for( int j = 0; j < o; j++ ) {
//                double val = 0;
//                for( int k = 0; k < n; k++ ) {
//                    val += blockA[ i*blockLength + k]*blockB[ k*blockLength + j];
//                }
//
//                blockC[ i*blockLength + j] += val;
//            }
//        }

//        int rowA = 0;
//        for( int i = 0; i < m; i++ , rowA += blockLength) {
//            for( int j = 0; j < o; j++ ) {
//                double val = 0;
//                int indexB = j;
//                int indexA = rowA;
//                int end = indexA + n;
//                for( ; indexA != end; indexA++ , indexB += blockLength ) {
//                    val += blockA[ indexA ]*blockB[ indexB ];
//                }
//
//                blockC[ rowA + j] += val;
//            }
//        }

//        for( int k = 0; k < n; k++ ) {
//            for( int i = 0; i < m; i++ ) {
//                for( int j = 0; j < o; j++ ) {
//                    blockC[ i*blockLength + j] += blockA[ i*blockLength + k]*blockB[ k*blockLength + j];
//                }
//            }
//        }

        for( int k = 0; k < n; k++ ) {
            int rowB = k*blockLength;
            int endB = rowB+o;
            for( int i = 0; i < m; i++ ) {
                int indexC = i*blockLength;
                double valA = blockA[ indexC + k];
                int indexB = rowB;
                
                while( indexB != endB ) {
                    blockC[ indexC++ ] += valA*blockB[ indexB++];
                }
            }
        }
    }
886524
def calculate_sequence_repeat_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_shape = operator.inputs[0].type.shape
    if len(input_shape) not in [2, 4]:
        raise RuntimeError('Input shape of CoreML SequenceRepeat must be either 2-D or 4-D but got %s' % input_shape)

    output_shape = copy.deepcopy(operator.inputs[0].type.shape)
    if output_shape[0] != None:
        output_shape[0] *= operator.raw_operator.sequenceRepeat.nRepetitions

    operator.outputs[0].type = FloatTensorType(output_shape, doc_string=operator.outputs[0].type.doc_string)
668736
def block_widths(self):
        
        if self._widths_cache is None:
            # The first column will have the correct lengths. We have an
            # invariant that requires that all blocks be the same width in a
            # column of blocks.
            self._widths_cache = (
                [obj.width() for obj in self._partitions_cache[0]]
                if len(self._partitions_cache) > 0
                else []
            )
        return self._widths_cache
273360
public static void computeRowOfV( final int blockLength ,
                                      final DSubmatrixD1 A ,
                                      final DSubmatrixD1 V ,
                                      int row ,
                                      double gamma )
    {
        // val=(y^T*u)
        double val = BlockHouseHolder_DDRB.innerProdRow(blockLength,A,row,V,row,1);

        // take in account the one
        double before = A.get(row,row+1);
        A.set(row,row+1,1);

        // v = y - (1/2)gamma*val * u
        VectorOps_DDRB.add_row(blockLength,V,row,1,A,row,-0.5*gamma*val,V,row,row+1,A.col1-A.col0);

        A.set(row,row+1,before);
    }
677878
function (line, lineNum) {
            if (line.trim() === '') {
                return;
            }


            function logAnyDelimiterType(line) {
                blocks.forEach(function (blockDef, blockIdx) {
                    if (blockDef.start.test(line) === true) {
                        fileStartDelimiters.push([blockIdx, lineNum, line.trim()]);
                    }
                    if (blockDef.end.test(line) === true) {
                        fileEndDelimiters.push([blockIdx, lineNum, line.trim()]);
                    }
                });
            }

            logAnyDelimiterType(line);


            var startCount = fileStartDelimiters.length;
            var endCount = fileEndDelimiters.length;

            /**
             * Checks that amount of start/end blocks are equal.
             *
             * @param blockDef
             * @param blockIdx
             */
            var checkBlocksParity = function (blockDef, blockIdx) {
                var block = blockStats[blockIdx];

                /**
                 * 'if' for start block check
                 */
                if (blockDef.start.test(line) === true) {

                    block.lastStartLine = lineNum;

                    if (block.startCount > block.endCount) {
                        generateMessage({
                            pattern: line.trim(),
                            lineNum: block.lastStartLine,
                            caseNum: 1
                        });
                    }

                    block.startCount++;
                }


                /**
                 * 'if' for end block check
                 */
                if (blockDef.end.test(line) === true) {

                    block.lastEndLine = lineNum;

                    if (block.endCount >= block.startCount) {
                        generateMessage({
                            pattern: line.trim(),
                            lineNum: block.lastEndLine,
                            caseNum: 2
                        });
                    }

                    block.endCount++;
                }
            };


            /**
             * Checks if any two (or more) pairs of start/end
             * blocks are intersecting.
             *
             * @param blockDef
             * @param blockIdx
             */
            var checkBlocksIntersection = function (blockDef, blockIdx) {
                if (blockDef.start.test(line)) {
                    blocksStack.push([blockIdx, lineNum, line.trim()]);
                }

                if (blockDef.end.test(line) && typeof last(blocksStack) !== "undefined") {
                    if (last(blocksStack)[0] === blockIdx) {
                        blocksStack.pop();
                    } else {
                        generateMessage({
                            start: last(blocksStack)[2],
                            pattern: line.trim(),
                            lineNum: last(blocksStack)[1],
                            endLineNum: lineNum,
                            caseNum: 3
                        });
                    }
                } else if (startCount - endCount > 1) {
                    generateMessage({
                        start: last(blocksStack)[2],
                        pattern: line.trim(),
                        lineNum: last(blocksStack)[1],
                        endLineNum: lineNum,
                        caseNum: 3
                    });
                }
            };

            if (options.parityCheck === true) {
                blocks.forEach(checkBlocksParity);
            }

            if (options.intersectionCheck === true) {
                blocks.forEach(checkBlocksIntersection);
            }
        }
1132385
public static void symmRankNMinus_L(int blockLength ,
                                        DSubmatrixD1 A , DSubmatrixD1 B )
    {
        int widthB = B.col1-B.col0;
        if( widthB > blockLength )
            throw new IllegalArgumentException("Width of B cannot be greater than the block length");

        int N = B.row1-B.row0;

        if( A.col1-A.col0 != N )
            throw new IllegalArgumentException("A does not have the expected number of columns based on B's height");
        if( A.row1-A.row0 != N )
            throw new IllegalArgumentException("A does not have the expected number of rows based on B's height");

        for( int i = B.row0; i < B.row1; i += blockLength ) {


            int heightB_i = Math.min(blockLength,B.row1-i);
            int indexB_i = i*B.original.numCols + heightB_i*B.col0;

            int rowA = i-B.row0+A.row0;
            int heightA = Math.min( blockLength , A.row1 - rowA);

            for( int j = B.row0; j <= i; j += blockLength ) {
                
                int widthB_j = Math.min(blockLength,B.row1-j);

                int indexA = rowA * A.original.numCols + (j-B.row0+A.col0)*heightA;
                int indexB_j = j*B.original.numCols + widthB_j*B.col0;

                if( i == j ) {
                    multTransBBlockMinus_L( B.original.data,A.original.data,
                            indexB_i,indexB_j,indexA,widthB,heightB_i,widthB_j);
                } else {
                    multTransBBlockMinus( B.original.data,A.original.data,
                            indexB_i,indexB_j,indexA,widthB,heightB_i,widthB_j);
                }
            }
        }
    }