Converts sweep into an equivalent protobuf representation.
330524
def sweep_to_proto_dict(sweep: Sweep, repetitions: int=1) -> Dict:
    """"""
    msg = {}  # type: Dict
    if not sweep == UnitSweep:
        sweep = _to_zip_product(sweep)
        msg['sweep'] = {
            'factors': [_sweep_zip_to_proto_dict(cast(Zip, factor)) for factor
                        in sweep.factors]
        }
    msg['repetitions'] = repetitions
    return msg
1252304
def Clean():
  """"""
  # Find all the compiled proto files and unlink them.
  for (root, _, files) in os.walk(ROOT):
    for filename in files:
      full_filename = os.path.join(root, filename)
      if full_filename.endswith("_pb2.py") or full_filename.endswith(
          "_pb2.pyc"):
        os.unlink(full_filename)
235904
def deconv(attrs, inputs, proto_obj):
    """"""
    new_attrs = translation_utils._fix_attribute_names(attrs, {'kernel_shape' : 'kernel',
                                                               'strides' : 'stride',
                                                               'pads': 'pad',
                                                               'dilations': 'dilate',
                                                               'group': 'num_group'})
    new_attrs = translation_utils._add_extra_attributes(new_attrs, {'num_group' : 1})
    new_attrs = translation_utils._fix_bias('Deconvolution', new_attrs, len(inputs))

    new_attrs = translation_utils._fix_channels('Deconvolution', new_attrs, inputs, proto_obj)
    kernel = new_attrs['kernel']
    stride = new_attrs['stride'] if 'stride' in new_attrs else []
    padding = new_attrs['pad'] if 'pad' in new_attrs else []
    dilations = new_attrs['dilate'] if 'dilate' in new_attrs else []
    num_filter = new_attrs['num_filter']
    num_group = new_attrs['num_group']
    no_bias = new_attrs['no_bias'] if 'no_bias' in new_attrs else False
    bias = None if no_bias is True else inputs[2]

    # Unlike ONNX, MXNet's deconvolution operator does not support asymmetric padding, so we first
    # use 'Pad' operator, which supports asymmetric padding. Then use the deconvolution operator.
    pad_width = (0, 0, 0, 0) + translation_utils._pad_sequence_fix(padding, kernel_dim=len(kernel))
    pad_op = symbol.pad(inputs[0], mode='constant', pad_width=pad_width)

    deconv_op = symbol.Deconvolution(pad_op, inputs[1], bias,
                                     kernel=kernel, stride=stride, dilate=dilations,
                                     num_filter=num_filter, num_group=num_group, no_bias=no_bias)

    return deconv_op, new_attrs, inputs
1009362
def _parameter_sweep(self, parameter_space, kernel_options, device_options, tuning_options):
        """"""
        results = []

        #randomize parameter space to do pseudo load balancing
        parameter_space = list(parameter_space)
        random.shuffle(parameter_space)

        #split parameter space into chunks
        work_per_thread = int(numpy.ceil(len(parameter_space) / float(self.max_threads)))
        chunks = _chunk_list(parameter_space, work_per_thread)

        for chunk in chunks:

            chunked_result = self._run_chunk(chunk, kernel_options, device_options, tuning_options)

            results.append(lift(chunked_result))

        return gather(*results)
753810
function Convert (proto, a) {
  if (a instanceof Buffer) {
    return Convert.toString(proto, a)
  } else {
    return Convert.toBuffer(proto, a)
  }
}
491492
def sweep(self):
        
        self.preSweep()
        if self.loadOrder == []:
            raise NetworkError('No loadOrder for the inputs. Make sure inputs are properly set.', self.loadOrder)
        if len(self.targets) != 0 and len(self.targets) != len(self.inputs):
            raise NetworkError("Number of inputs does not equal number of targets (inputs=%d, targets=%d)" % (len(self.targets), len(self.inputs)))
        if self.verbosity >= 1: print("Epoch #", self.epoch, "Cycle...")
        if not self.orderedInputs:
            self.randomizeOrder()
        tssError = 0.0; totalCorrect = 0; totalCount = 0; totalPCorrect = {}
        cnt = 0
        if self.saveResults:
            self.results = [(0,0,0) for x in self.loadOrder]
        for i in self.loadOrder:
            if self.verbosity >= 1 or self.interactive:
                print("-----------------------------------Pattern #", self.loadOrder[i] + 1)
            datum = self.getData(i) # creates a dictionary of input/targets from self.inputs, self.targets
            if cnt < len(self.loadOrder) - 1:
                self.currentSweepCount = cnt
            else:
                self.currentSweepCount = None
            self._sweeping = 1
            (error, correct, total, pcorrect) = self.step( **datum )
            self._sweeping = 0
            if self.saveResults:
                self.results[i] = (error, correct, total, pcorrect)
            tssError += error
            totalCorrect += correct
            totalCount += total
            sumMerge(totalPCorrect, pcorrect)
            if self.sweepReportRate and (cnt + 1) % self.sweepReportRate == 0:
                print("   Step # %6d | TSS Error: %.4f | Correct: %.4f" % \
                      (cnt + 1, tssError, totalCorrect * 1.0 / totalCount))
            if self.crossValidationSampleRate and self.epoch % self.crossValidationSampleRate == 0:
                self.saveNetworkForCrossValidation(self.crossValidationSampleFile)
            cnt += 1
        if self.learning and self.batch:
            self.change_weights() # batch mode, otherwise change weights in step
        self.postSweep()
        return (tssError, totalCorrect, totalCount, totalPCorrect)
149326
def _value_to_pb(value, proto_type):
    
    data_type_pb = getattr(google_dot_protobuf_dot_wrappers__pb2, proto_type)()
    ParseDict(value, data_type_pb)
    return data_type_pb
674832
function formalizeWrap(wrap) {
    const result = {before: '', after: ''};

    if ((typeof wrap === 'string' && wrap.length > 0) || typeof wrap === 'number') {
        result.before = result.after = wrap;
    } else if (Array.isArray(wrap) && wrap.length > 0) {
        result.before = [].slice.call(wrap, 0, 1)[0];
        result.after = wrap.length > 1 ? [].slice.call(wrap, 1, 2)[0] : result.before;
    } else if (_.isPlainObject(wrap)) {
        let i = 0;

        // crappy method getting the value of the first and second item in object
        for (let el in wrap) {
            if (!wrap.hasOwnProperty(el)) {
                continue;
            }

            if (i < 2) {
                result.before = wrap[el];
            }

            i++;
        }

        // set value of after to the value of before if after is empty
        result.after = result.after.length < 1 ? result.before : result.after;
    }

    return result;
}
592121
def metainfo_to_protobuf(self) -> bytes:
        ''''''

        card = cardtransferproto()
        card.version = self.version
        card.amount.extend(self.amount)
        card.number_of_decimals = self.number_of_decimals
        if self.asset_specific_data:
            if not isinstance(self.asset_specific_data, bytes):
                card.asset_specific_data = self.asset_specific_data.encode()
            else:
                card.asset_specific_data = self.asset_specific_data

        if card.ByteSize() > net_query(self.network).op_return_max_bytes:
            raise OverSizeOPReturn('''
                        Metainfo size exceeds maximum of {max} bytes supported by this network.'''
                                   .format(max=net_query(self.network)
                                           .op_return_max_bytes))

        return card.SerializeToString()
443155
def convert_from_sliced_object(data):
    """"""
    if data.base is not None and isinstance(data, np.ndarray) and isinstance(data.base, np.ndarray):
        if not data.flags.c_contiguous:
            warnings.warn("Usage of np.ndarray subset (sliced data) is not recommended "
                          "due to it will double the peak memory cost in LightGBM.")
            return np.copy(data)
    return data
240785
def to_gremlin(self):
        """"""
        self.validate()
        template_data = {
            'direction': self.direction,
            'edge_name': self.edge_name,
            'inverse_direction': 'in' if self.direction == 'out' else 'out'
        }
        return (u'collectMany{{entry -> entry.{direction}_{edge_name}'
                u'.collect{{edge -> edge.{inverse_direction}V.next()}}}}'
                .format(**template_data))
1198905
def pattern_convert(grammar, raw_node_info):
    """"""
    type, value, context, children = raw_node_info
    if children or type in grammar.number2symbol:
        return pytree.Node(type, children, context=context)
    else:
        return pytree.Leaf(type, value, context=context)
1097381
def _tiles_from_cleaned_bounds(tp, bounds, zoom):
    """"""
    lb = _tile_from_xy(tp, bounds.left, bounds.bottom, zoom, on_edge_use="rt")
    rt = _tile_from_xy(tp, bounds.right, bounds.top, zoom, on_edge_use="lb")
    for tile_id in product([zoom], range(rt.row, lb.row + 1), range(lb.col, rt.col + 1)):
        yield tp.tile(*tile_id)
513945
def spacetodepth(attrs, inputs, proto_obj):
    """"""
    new_attrs = translation_utils._fix_attribute_names(attrs, {'blocksize':'block_size'})

    return "space_to_depth", new_attrs, inputs
945306
def _build_protobuf(self):
        
        pb = _pb_from_query(self._query)

        start_cursor = self.next_page_token
        if start_cursor is not None:
            pb.start_cursor = base64.urlsafe_b64decode(start_cursor)

        end_cursor = self._end_cursor
        if end_cursor is not None:
            pb.end_cursor = base64.urlsafe_b64decode(end_cursor)

        if self.max_results is not None:
            pb.limit.value = self.max_results - self.num_results

        if start_cursor is None and self._offset is not None:
            # NOTE: We don't need to add an offset to the request protobuf
            #       if we are using an existing cursor, because the offset
            #       is only relative to the start of the result set, not
            #       relative to each page (this method is called per-page)
            pb.offset = self._offset

        return pb
582339
def to_resolvers(sweepable: Sweepable) -> List[ParamResolver]:
    """"""
    if isinstance(sweepable, ParamResolver):
        return [sweepable]
    elif isinstance(sweepable, Sweep):
        return list(sweepable)
    elif isinstance(sweepable, collections.Iterable):
        iterable = cast(collections.Iterable, sweepable)
        return list(iterable) if isinstance(next(iter(iterable)),
                                            ParamResolver) else sum(
            [list(s) for s in iterable], [])
    raise TypeError('Unexpected Sweepable type.')
1331441
def as_proto(self):
        """"""
        if self._dims is None:
            return tensor_shape_pb2.TensorShapeProto(unknown_rank=True)
        else:
            return tensor_shape_pb2.TensorShapeProto(
                dim=[
                    tensor_shape_pb2.TensorShapeProto.Dim(
                        size=-1 if d.value is None else d.value
                    )
                    for d in self._dims
                ]
            )