_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q224200
reduce
train
def reduce(x, op='sum'): """Reduction function with given operation. Args: x (Variable): An input. op (str): 'sum' or 'mean'. Note: This is deprecated. Use ``mean`` or ``sum`` instead. """ import warnings warnings.warn( "Deprecated API. Use ``sum`` or ``mean`` ...
python
{ "resource": "" }
q224201
split
train
def split(x, axis=0): """ Split arrays at the specified axis. It returns a number corresponding the size of the given axis (i.e ``x.shape[axis]``) of :obj:`~nnabla.Variable` s. Args: x(~nnabla.Variable): N-D array axis(int): Axis Returns: A :obj:`tuple` of :obj:`~nnabla.Variab...
python
{ "resource": "" }
q224202
batch_normalization
train
def batch_normalization(x, beta, gamma, mean, variance, axes=[1], decay_rate=0.9, eps=1e-05, batch_stat=True, output_stat=False, n_outputs=None): r""" Batch normalization. .. math:: \begin{eqnarray} \mu &=& \frac{1}{M} \sum x_i \\ \sigma^2 &=& \frac{1}{M} \sum \left(x_i - \mu\ri...
python
{ "resource": "" }
q224203
fixed_point_quantize
train
def fixed_point_quantize(x, sign=True, n=8, delta=2**-4, quantize=True, ste_fine_grained=True, outputs=None): r"""Fixed Point Quantize Args: x (Variable): An input variable. sign (bool): Indicate the signed number or the unsigned number. Default is true. n (int): Bit width used. Note th...
python
{ "resource": "" }
q224204
pow2_quantize
train
def pow2_quantize(x, sign=True, with_zero=True, n=8, m=1, quantize=True, ste_fine_grained=True, outputs=None): r"""Pow2 Quantize Args: x (Variable): An input variable. sign (bool): Indicate the signed number or the unsigned number. Default is true. with_zero (bool): Indicate using zero ...
python
{ "resource": "" }
q224205
clip_by_value
train
def clip_by_value(x, min, max): r"""Clip inputs by values. .. math:: y = \begin{cases} max & (x > max) \\ x & (otherwise) \\ min & (x < min) \end{cases}. Args: x (Variable): An input variable. min (Variable): A min variab...
python
{ "resource": "" }
q224206
interpolate
train
def interpolate(x, scale=None, output_size=None, mode='linear', align_corners=None): ''' Resize an ND array with interpolation. Scaling factors for spatial dimensions are determined by either ``scale`` or ``output_size``. ``nd = len(scale)`` or ``nd = len(output_size)`` determines the number of ...
python
{ "resource": "" }
q224207
sort
train
def sort(x, axis=-1, reverse=False, with_index=False, only_index=False): """Sorts the elements of `x` along a given `axis` in ascending order by value. A negative `axis` counts from the last dimension of `x`, so the default of -1 sorts along the last dimension. If `reverse` is True, then the elements ar...
python
{ "resource": "" }
q224208
download
train
def download(url, output_file=None, open_file=True, allow_overwrite=False): '''Download a file from URL. Args: url (str): URL. output_file (str, optional): If given, the downloaded file is written to the given path. open_file (bool): If True, it returns an opened file stream of the down...
python
{ "resource": "" }
q224209
imread
train
def imread(path, grayscale=False, size=None, interpolate="bilinear", channel_first=False, as_uint16=False, num_channels=-1): """ Read image by cv2 module. Args: path (str or 'file object'): File path or object to read. grayscale (bool): size (tupple of int): (...
python
{ "resource": "" }
q224210
PolynomialScheduler.get_learning_rate
train
def get_learning_rate(self, iter): ''' Get learning rate with polymomial decay based on current iteration. Args: iter (int): current iteration (starting with 0). Returns: float: Learning rate ''' return self.init_lr * ((1.0 - iter * 1.0 / self.ma...
python
{ "resource": "" }
q224211
CosineScheduler.get_learning_rate
train
def get_learning_rate(self, iter): ''' Get learning rate with cosine decay based on current iteration. Args: iter (int): Current iteration (starting with 0). Returns: float: Learning rate ''' return self.init_lr * ((math.cos(iter * 1.0 / (self.ma...
python
{ "resource": "" }
q224212
affine
train
def affine(inp, n_outmaps, base_axis=1, w_init=None, b_init=None, fix_parameters=False, rng=None, with_bias=True, apply_w=None, apply_b=None): """ The affine layer, also known as the fully connected layer. Computes .. math:: {\\mathbf y} = {\\mathbf A} {\...
python
{ "resource": "" }
q224213
binary_weight_affine
train
def binary_weight_affine(inp, n_outmaps, base_axis=1, quantize_zero_to=1.0, w_init=None, wb_init=None, b_init=None, fix_parameters=False, rng=None, with_bias=True): """Binary Weight Affine, multiplier-less inner-product with a scale factor. ...
python
{ "resource": "" }
q224214
inq_affine
train
def inq_affine(inp, n_outmaps, base_axis=1, num_bits=4, inq_iterations=(), selection_algorithm='random', seed=-1, w_init=None, i_init=None, b_init=None, fix_parameters=False, rng=None, with_bias=True): """Incremental Network Quantization Affine Layer During training...
python
{ "resource": "" }
q224215
binary_connect_convolution
train
def binary_connect_convolution(inp, outmaps, kernel, pad=None, stride=None, dilation=None, group=1, quantize_zero_to=1.0, w_init=None, wb_init=None, b_init=None, base_axis=1, fix_parameters=False,...
python
{ "resource": "" }
q224216
inq_convolution
train
def inq_convolution(inp, outmaps, kernel, pad=None, stride=None, dilation=None, group=1, num_bits=4, inq_iterations=(), selection_algorithm='random', seed=-1, w_init=None, i_init=None, b_init=None, base_axis=1, fix_parameters=False, rng=Non...
python
{ "resource": "" }
q224217
depthwise_convolution
train
def depthwise_convolution(inp, kernel, pad=None, stride=None, dilation=None, multiplier=1, w_init=None, b_init=None, base_axis=1, fix_parameters=False, rng=None, with_bias=True): """ N-D Depthwise Convolution with a bias term. Reference: - F. Chollet...
python
{ "resource": "" }
q224218
batch_normalization
train
def batch_normalization(inp, axes=[1], decay_rate=0.9, eps=1e-5, batch_stat=True, output_stat=False, fix_parameters=False, param_init=None): """ Batch normalization layer. .. math:: \\begin{array}{lcl} \\mu &=& \\frac{1}{M} \\sum x_i\\\\ ...
python
{ "resource": "" }
q224219
mean_subtraction
train
def mean_subtraction(inp, base_axis=1, update_running_mean=True, fix_parameters=False): """ Mean subtraction layer. It subtracts the mean of the elements of the input array, and normalizes it to :math:`0`. Preprocessing arrays with this function has the effect of improving accuracy in various tasks...
python
{ "resource": "" }
q224220
prelu
train
def prelu(inp, base_axis=1, shared=True, fix_parameters=False): """ Parametrized Rectified Linear Unit function defined as .. math:: y_i = \max(0, x_i) + w_i \min(0, -x_i) where negative slope :math:`w` is learned and can vary across channels (an axis specified with base_axis). Weights are...
python
{ "resource": "" }
q224221
fixed_point_quantized_affine
train
def fixed_point_quantized_affine(inp, n_outmaps, base_axis=1, w_init=None, b_init=None, fix_parameters=False, rng=None, with_bias=True, quantize_w=True, sign_w=True, n_w=8, delta_w=2**-4, ...
python
{ "resource": "" }
q224222
fixed_point_quantized_convolution
train
def fixed_point_quantized_convolution(inp, outmaps, kernel, pad=None, stride=None, dilation=None, group=1, w_init=None, b_init=None, base_axis=1, fix_parameters=False, rng=None, with_bias=True, ...
python
{ "resource": "" }
q224223
pow2_quantized_affine
train
def pow2_quantized_affine(inp, n_outmaps, base_axis=1, w_init=None, b_init=None, fix_parameters=False, rng=None, with_bias=True, quantize_w=True, sign_w=True, with_zero_w=False, n_w=8, m_w=2, ste_fine_grained_w=True,...
python
{ "resource": "" }
q224224
pow2_quantized_convolution
train
def pow2_quantized_convolution(inp, outmaps, kernel, pad=None, stride=None, dilation=None, group=1, w_init=None, b_init=None, base_axis=1, fix_parameters=False, rng=None, with_bias=True, quantize_...
python
{ "resource": "" }
q224225
pruned_affine
train
def pruned_affine(inp, n_outmaps, base_axis=1, w_init=None, b_init=None, fix_parameters=False, rng=None, with_bias=True, prune_w=True, rate_w=0.9, prune_b=True, rate_b=0.9): """Pruned Affine. Pruned Affine is the affine function, exce...
python
{ "resource": "" }
q224226
pruned_convolution
train
def pruned_convolution(inp, outmaps, kernel, pad=None, stride=None, dilation=None, group=1, w_init=None, b_init=None, base_axis=1, fix_parameters=False, rng=None, with_bias=True, prune_w=True, rate_w=0.9, prune_b=True, rate_b=0....
python
{ "resource": "" }
q224227
lstm_cell
train
def lstm_cell(x, h, c, state_size, w_init=None, b_init=None, fix_parameters=False): """Long Short-Term Memory. Long Short-Term Memory, or LSTM, is a building block for recurrent neural networks (RNN) layers. LSTM unit consists of a cell and input, output, forget gates whose functions are defined as followi...
python
{ "resource": "" }
q224228
spectral_norm
train
def spectral_norm(w, dim=0, itr=1, eps=1e-12, test=False, u_init=None, fix_parameters=True): """Spectral Normalization. .. math:: W_{sn} = \\frac{W}{\\sigma(W)}. where :math:`W` is the input matrix, and the :math:`\\sigma(W)` is the spectral norm of :math:`W`. The spectral norm is approximately c...
python
{ "resource": "" }
q224229
LSTMCell.reset_state
train
def reset_state(self): """ Resets states h and c to zero. """ self.h.data.zero() self.c.data.zero()
python
{ "resource": "" }
q224230
Timer.lap
train
def lap(self): """Calculate lap time. Returns: float: Lap time. The duration from the previous call of ``lap()`` or initialization at first call. float: Total time. The duration from initialization. """ now = time.time() lap_time = now -...
python
{ "resource": "" }
q224231
FunctionBenchmarkWriter.write
train
def write(self, fb): """Write a single function benchmark. Args: fb (FunctionBenchmark): FunctionBenchmark class instance. Before passing to this, you should call ``fb.benchmark()``. """ print('[{}.{}]'.format(fb.module, fb.func.__name__), file=self.file) ...
python
{ "resource": "" }
q224232
FunctionBenchmark._setup
train
def _setup(self, delete=True): """Create a function instance and execute setup. Args: delete (bool): Delete buffered variables. """ if delete: self.clear() with nn.context_scope(self.ctx): outputs = self.func( *(self.inputs_f ...
python
{ "resource": "" }
q224233
FunctionBenchmark.benchmark_setup
train
def benchmark_setup(self): """Benchmark setup execution. """ def f(): self._setup() self.mod_ext.synchronize(**self.ext_kwargs) f() # Ignore first self.setup_stat = self._calc_benchmark_stat(f)
python
{ "resource": "" }
q224234
FunctionBenchmark.benchmark_forward
train
def benchmark_forward(self): """Benchmark forward execution. """ self._setup() def f(): self._forward() self.mod_ext.synchronize(**self.ext_kwargs) f() # Ignore first self.forward_stat = self._calc_benchmark_stat(f)
python
{ "resource": "" }
q224235
FunctionBenchmark.benchmark_backward
train
def benchmark_backward(self): """Benchmark backward execution. Note: If backward execution throws any exception, this benchmark system considers the error is because the function doesn't support backward operation, then set the benchmark ``None``. ...
python
{ "resource": "" }
q224236
context
train
def context(type_config='float', **kw): """CPU Context.""" backends = ['cpu:float'] if type_config == 'half': backends = ['cpu:half', 'cpu:float'] elif type_config == 'float': pass else: raise ValueError("Unknown data type config is given %s" % type_config) return nn.Cont...
python
{ "resource": "" }
q224237
revise_buffer_size
train
def revise_buffer_size(info, settings): ''' This function is used to revise buffer size, use byte as its unit, instead of data item. This is only used for nnb, not for csrc. When settings contains user customized data type, not pure FLOAT32, it affects the memory consumption. ''' size_ma...
python
{ "resource": "" }
q224238
ImageNetBase.category_names
train
def category_names(self): ''' Returns category names of 1000 ImageNet classes. ''' if hasattr(self, '_category_names'): return self._category_names with open(os.path.join(os.path.dirname(__file__), 'category_names.txt'), 'r') as fd: self._category_names = ...
python
{ "resource": "" }
q224239
GraphProfilerCsvWriter.write
train
def write(self): """ Write result to the file. The output file is specified by ``file``. """ writer = csv.writer(self.file) for f, b in zip(self.gb.result["forward"], self.gb.result["backward"]): f = f._asdict() b = b._asdict() if not ...
python
{ "resource": "" }
q224240
plot_series
train
def plot_series(filename, plot_kwargs=None): '''Plot series data from MonitorSeries output text file. Args: filename (str): Path to *.series.txt file produced by :obj:`~nnabla.MonitorSeries` class. plot_kwags (dict, optional): Keyward arguments passed to :function:`matplotlib.pyplot...
python
{ "resource": "" }
q224241
plot_time_elapsed
train
def plot_time_elapsed(filename, elapsed=False, unit='s', plot_kwargs=None): '''Plot series data from MonitorTimeElapsed output text file. Args: filename (str): Path to *.series.txt file produced by :obj:`~nnabla.MonitorSeries` class. elapsed (bool): If ``True``, it plots the total elapsed time....
python
{ "resource": "" }
q224242
MonitorSeries.add
train
def add(self, index, value): """Add a value to the series. Args: index (int): Index. value (float): Value. """ self.buf.append(value) if (index - self.flush_at) < self.interval: return value = np.mean(self.buf) if self.verbose...
python
{ "resource": "" }
q224243
MonitorTimeElapsed.add
train
def add(self, index): """Calculate time elapsed from the point previously called this method or this object is created to this is called. Args: index (int): Index to be displayed, and be used to take intervals. """ if (index - self.flush_at) < self.interval: ...
python
{ "resource": "" }
q224244
MonitorImage.add
train
def add(self, index, var): """Add a minibatch of images to the monitor. Args: index (int): Index. var (:obj:`~nnabla.Variable`, :obj:`~nnabla.NdArray`, or :obj:`~numpy.ndarray`): A minibatch of images with ``(N, ..., C, H, W)`` format. If C == 2, ...
python
{ "resource": "" }
q224245
data_iterator_simple
train
def data_iterator_simple(load_func, num_examples, batch_size, shuffle=False, rng=None, with_memory_cache=True, with_file_cache=True, cache_dir=No...
python
{ "resource": "" }
q224246
data_iterator_csv_dataset
train
def data_iterator_csv_dataset(uri, batch_size, shuffle=False, rng=None, normalize=True, with_memory_cache=True, with_file_cache=True, ...
python
{ "resource": "" }
q224247
data_iterator_cache
train
def data_iterator_cache(uri, batch_size, shuffle=False, rng=None, normalize=True, with_memory_cache=True, epoch_begin_callbacks=[], epoch_end_callbacks=...
python
{ "resource": "" }
q224248
data_iterator_concat_datasets
train
def data_iterator_concat_datasets(data_source_list, batch_size, shuffle=False, rng=None, with_memory_cache=True, with_file_cache=False, ...
python
{ "resource": "" }
q224249
DataIterator.slice
train
def slice(self, rng, num_of_slices=None, slice_pos=None, slice_start=None, slice_end=None, cache_dir=None): ''' Slices the data iterator so that newly generated data iterator has access to limited portion of the original data. Args: rng (numpy.random.Rand...
python
{ "resource": "" }
q224250
auto_forward
train
def auto_forward(auto=True): """ Context for dynamic graph execution mode. Args: auto (bool): Whether forward computation is executed during a computation graph construction. Returns: bool """ global __auto_forward_state prev = __auto_forward_state __auto_forward_s...
python
{ "resource": "" }
q224251
FunctionProfile.print_stats
train
def print_stats(self, reset=True): '''Manually print profiling result. Args: reset (bool): If False is specified, the profiling statistics so far is maintained. If ``True`` (default), :obj:`~reset_stats` is called to reset the profiling statis...
python
{ "resource": "" }
q224252
get_model_home
train
def get_model_home(): ''' Returns a root folder path for downloading models. ''' d = os.path.join(get_data_home(), 'nnp_models') if not os.path.isdir(d): os.makedirs(d) return d
python
{ "resource": "" }
q224253
get_model_url_base
train
def get_model_url_base(): ''' Returns a root folder for models. ''' url_base = get_model_url_base_from_env() if url_base is not None: logger.info('NNBLA_MODELS_URL_BASE is set as {}.'.format(url_base)) else: url_base = 'https://nnabla.org/pretrained-models/nnp_models/' return...
python
{ "resource": "" }
q224254
load_image_imread
train
def load_image_imread(file, shape=None, max_range=1.0): ''' Load image from file like object. :param file: Image contents :type file: file like object. :param shape: shape of output array e.g. (3, 128, 192) : n_color, height, width. :type shape: tuple of int :param float max_range: ...
python
{ "resource": "" }
q224255
load_csv
train
def load_csv(file, shape=None, normalize=False): """ Load CSV file. :param file: CSV file. :type file: file like object :param shape : data array is reshape to this shape. :type shape: tuple of int :return: numpy array """ value_list = [] if six.PY2: for row in csv.read...
python
{ "resource": "" }
q224256
SimpleGraph.save
train
def save(self, vleaf, fpath, cleanup=False, format=None): """Save the graph to a given file path. Args: vleaf (`nnabla.Variable`): End variable. All variables and functions which can be traversed from this variable are shown in the reuslt. fpath (`str`): The file path used to save. ...
python
{ "resource": "" }
q224257
SimpleGraph.view
train
def view(self, vleaf, fpath=None, cleanup=True, format=None): """View the graph. Args: vleaf (`nnabla.Variable`): End variable. All variables and functions which can be traversed from this variable are shown in the reuslt. fpath (`str`): The file path used to save. cleanu...
python
{ "resource": "" }
q224258
Module.get_modules
train
def get_modules(self, memo=None, prefix=""): """Get modules. This function is internally used as the helper method for other methods. Args: memo (set, optional): Module set in order to memorize to visit. prefix (str, optional): Prefix to a specific parameter name. ...
python
{ "resource": "" }
q224259
HexIntegerField.get_prep_value
train
def get_prep_value(self, value): """ Return the integer value to be stored from the hex string """ if value is None or value == "": return None if isinstance(value, six.string_types): value = _hex_string_to_unsigned_integer(value) if _using_signed_storage(): value = _unsigned_to_signed_integer(value) ...
python
{ "resource": "" }
q224260
HexIntegerField.from_db_value
train
def from_db_value(self, value, expression, connection, context): """ Return an unsigned int representation from all db backends """ if value is None: return value if _using_signed_storage(): value = _signed_to_unsigned_integer(value) return value
python
{ "resource": "" }
q224261
HexIntegerField.to_python
train
def to_python(self, value): """ Return a str representation of the hexadecimal """ if isinstance(value, six.string_types): return value if value is None: return value return _unsigned_integer_to_hex_string(value)
python
{ "resource": "" }
q224262
apns_send_bulk_message
train
def apns_send_bulk_message( registration_ids, alert, application_id=None, certfile=None, **kwargs ): """ Sends an APNS notification to one or more registration_ids. The registration_ids argument needs to be a list. Note that if set alert should always be a string. If it is not set, it won"t be included in the no...
python
{ "resource": "" }
q224263
_cm_send_request
train
def _cm_send_request( registration_ids, data, cloud_type="GCM", application_id=None, use_fcm_notifications=True, **kwargs ): """ Sends a FCM or GCM notification to one or more registration_ids as json data. The registration_ids needs to be a list. """ payload = {"registration_ids": registration_ids} if registra...
python
{ "resource": "" }
q224264
_cm_handle_canonical_id
train
def _cm_handle_canonical_id(canonical_id, current_id, cloud_type): """ Handle situation when FCM server response contains canonical ID """ devices = GCMDevice.objects.filter(cloud_message_type=cloud_type) if devices.filter(registration_id=canonical_id, active=True).exists(): devices.filter(registration_id=curren...
python
{ "resource": "" }
q224265
AppConfig._validate_applications
train
def _validate_applications(self, apps): """Validate the application collection""" for application_id, application_config in apps.items(): self._validate_config(application_id, application_config) application_config["APPLICATION_ID"] = application_id
python
{ "resource": "" }
q224266
AppConfig._validate_apns_certificate
train
def _validate_apns_certificate(self, certfile): """Validate the APNS certificate at startup.""" try: with open(certfile, "r") as f: content = f.read() check_apns_certificate(content) except Exception as e: raise ImproperlyConfigured( "The APNS certificate file at %r is not readable: %s" % (cert...
python
{ "resource": "" }
q224267
AppConfig._validate_allowed_settings
train
def _validate_allowed_settings(self, application_id, application_config, allowed_settings): """Confirm only allowed settings are present.""" for setting_key in application_config.keys(): if setting_key not in allowed_settings: raise ImproperlyConfigured( "Platform {}, app {} does not support the settin...
python
{ "resource": "" }
q224268
AppConfig._validate_required_settings
train
def _validate_required_settings( self, application_id, application_config, required_settings ): """All required keys must be present""" for setting_key in required_settings: if setting_key not in application_config.keys(): raise ImproperlyConfigured( MISSING_SETTING.format( application_id=appl...
python
{ "resource": "" }
q224269
AppConfig._get_application_settings
train
def _get_application_settings(self, application_id, platform, settings_key): """ Walks through PUSH_NOTIFICATIONS_SETTINGS to find the correct setting value or raises ImproperlyConfigured. """ if not application_id: conf_cls = "push_notifications.conf.AppConfig" raise ImproperlyConfigured( "{} requ...
python
{ "resource": "" }
q224270
_wns_authenticate
train
def _wns_authenticate(scope="notify.windows.com", application_id=None): """ Requests an Access token for WNS communication. :return: dict: {'access_token': <str>, 'expires_in': <int>, 'token_type': 'bearer'} """ client_id = get_manager().get_wns_package_security_id(application_id) client_secret = get_manager().g...
python
{ "resource": "" }
q224271
_wns_send
train
def _wns_send(uri, data, wns_type="wns/toast", application_id=None): """ Sends a notification data and authentication to WNS. :param uri: str: The device's unique notification URI :param data: dict: The notification data to be sent. :return: """ access_token = _wns_authenticate(application_id=application_id) ...
python
{ "resource": "" }
q224272
_wns_prepare_toast
train
def _wns_prepare_toast(data, **kwargs): """ Creates the xml tree for a `toast` notification :param data: dict: The notification data to be converted to an xml tree. { "text": ["Title text", "Message Text", "Another message!"], "image": ["src1", "src2"], } :return: str """ root = ET.Element("toast") visu...
python
{ "resource": "" }
q224273
wns_send_bulk_message
train
def wns_send_bulk_message( uri_list, message=None, xml_data=None, raw_data=None, application_id=None, **kwargs ): """ WNS doesn't support bulk notification, so we loop through each uri. :param uri_list: list: A list of uris the notification will be sent to. :param message: str: The notification data to be sent. ...
python
{ "resource": "" }
q224274
_add_sub_elements_from_dict
train
def _add_sub_elements_from_dict(parent, sub_dict): """ Add SubElements to the parent element. :param parent: ElementTree.Element: The parent element for the newly created SubElement. :param sub_dict: dict: Used to create a new SubElement. See `dict_to_xml_schema` method docstring for more information. e.g.: {"e...
python
{ "resource": "" }
q224275
_add_element_attrs
train
def _add_element_attrs(elem, attrs): """ Add attributes to the given element. :param elem: ElementTree.Element: The element the attributes are being added to. :param attrs: dict: A dictionary of attributes. e.g.: {"attribute1": "value", "attribute2": "another"} :return: ElementTree.Element """ for attr, value...
python
{ "resource": "" }
q224276
WSClient.login
train
def login(self, host_spec="", username="", password=""): """ Authenticate with infrastructure via the Skydive analyzer This method will also set the authentication cookie to be used in the future requests :param host_spec: Host IP and port (e.g. 192.168.10.1:8082) :type host_spe...
python
{ "resource": "" }
q224277
TargetAndroid._sdkmanager
train
def _sdkmanager(self, *args, **kwargs): """Call the sdkmanager in our Android SDK with the given arguments.""" # Use the android-sdk dir as cwd by default kwargs['cwd'] = kwargs.get('cwd', self.android_sdk_dir) command = self.sdkmanager_path + ' ' + ' '.join(args) return_child = ...
python
{ "resource": "" }
q224278
TargetAndroid._android_get_installed_platform_tools_version
train
def _android_get_installed_platform_tools_version(self): """ Crudely parse out the installed platform-tools version """ platform_tools_dir = os.path.join( self.android_sdk_dir, 'platform-tools') if not os.path.exists(platform_tools_dir): retu...
python
{ "resource": "" }
q224279
TargetAndroid._android_update_sdk
train
def _android_update_sdk(self, *sdkmanager_commands): """Update the tools and package-tools if possible""" auto_accept_license = self.buildozer.config.getbooldefault( 'app', 'android.accept_sdk_license', False) if auto_accept_license: # `SIGPIPE` is not being reported som...
python
{ "resource": "" }
q224280
TargetAndroid.cmd_logcat
train
def cmd_logcat(self, *args): '''Show the log from the device ''' self.check_requirements() serial = self.serials[0:] if not serial: return filters = self.buildozer.config.getrawdefault( "app", "android.logcat_filters", "", section_sep=":", split_ch...
python
{ "resource": "" }
q224281
Target.path_or_git_url
train
def path_or_git_url(self, repo, owner='kivy', branch='master', url_format='https://github.com/{owner}/{repo}.git', platform=None, squash_hyphen=True): """Get source location for a git checkout This method will check the `buildozer....
python
{ "resource": "" }
q224282
Target.install_or_update_repo
train
def install_or_update_repo(self, repo, **kwargs): """Install or update a git repository into the platform directory. This will clone the contents of a git repository to `buildozer.platform_dir`. The location of this repo can be speficied via URL and branch name, or via a custom (local) ...
python
{ "resource": "" }
q224283
set_config_token_from_env
train
def set_config_token_from_env(section, token, config): '''Given a config section and token, checks for an appropriate environment variable. If the variable exists, sets the config entry to its value. The environment variable checked is of the form SECTION_TOKEN, all upper case, with any dots replac...
python
{ "resource": "" }
q224284
Buildozer.prepare_for_build
train
def prepare_for_build(self): '''Prepare the build. ''' assert(self.target is not None) if hasattr(self.target, '_build_prepared'): return self.info('Preparing build') self.info('Check requirements for {0}'.format(self.targetname)) self.target.check_r...
python
{ "resource": "" }
q224285
Buildozer.build
train
def build(self): '''Do the build. The target can set build_mode to 'release' or 'debug' before calling this method. (:meth:`prepare_for_build` must have been call before.) ''' assert(self.target is not None) assert(hasattr(self.target, '_build_prepared')) ...
python
{ "resource": "" }
q224286
Buildozer.log_env
train
def log_env(self, level, env): """dump env into debug logger in readable format""" self.log(level, "ENVIRONMENT:") for k, v in env.items(): self.log(level, " {} = {}".format(k, pformat(v)))
python
{ "resource": "" }
q224287
Buildozer.check_configuration_tokens
train
def check_configuration_tokens(self): '''Ensure the spec file is 'correct'. ''' self.info('Check configuration tokens') self.migrate_configuration_tokens() get = self.config.getdefault errors = [] adderror = errors.append if not get('app', 'title', ''): ...
python
{ "resource": "" }
q224288
Buildozer.check_application_requirements
train
def check_application_requirements(self): '''Ensure the application requirements are all available and ready to be packaged as well. ''' requirements = self.config.getlist('app', 'requirements', '') target_available_packages = self.target.get_available_packages() if targe...
python
{ "resource": "" }
q224289
Buildozer.check_garden_requirements
train
def check_garden_requirements(self): '''Ensure required garden packages are available to be included. ''' garden_requirements = self.config.getlist('app', 'garden_requirements', '') # have we installed the garden packages? if exists(self.gardenlibs_dir) and \ ...
python
{ "resource": "" }
q224290
Buildozer.cmd_init
train
def cmd_init(self, *args): '''Create a initial buildozer.spec in the current directory ''' if exists('buildozer.spec'): print('ERROR: You already have a buildozer.spec file.') exit(1) copyfile(join(dirname(__file__), 'default.spec'), 'buildozer.spec') prin...
python
{ "resource": "" }
q224291
Buildozer.cmd_distclean
train
def cmd_distclean(self, *args): '''Clean the whole Buildozer environment. ''' print("Warning: Your ndk, sdk and all other cached packages will be" " removed. Continue? (y/n)") if sys.stdin.readline().lower()[0] == 'y': self.info('Clean the global build directory...
python
{ "resource": "" }
q224292
Buildozer.cmd_serve
train
def cmd_serve(self, *args): '''Serve the bin directory via SimpleHTTPServer ''' try: from http.server import SimpleHTTPRequestHandler from socketserver import TCPServer except ImportError: from SimpleHTTPServer import SimpleHTTPRequestHandler ...
python
{ "resource": "" }
q224293
TargetIos.cmd_xcode
train
def cmd_xcode(self, *args): '''Open the xcode project. ''' app_name = self.buildozer.namify(self.buildozer.config.get('app', 'package.name')) app_name = app_name.lower() ios_dir = ios_dir = join(self.buildozer.platform_dir, 'kivy-ios') self.buildozer.cmd('ope...
python
{ "resource": "" }
q224294
TargetIos.cmd_list_identities
train
def cmd_list_identities(self, *args): '''List the available identities to use for signing. ''' identities = self._get_available_identities() print('Available identities:') for x in identities: print(' - {}'.format(x))
python
{ "resource": "" }
q224295
CassetteContextDecorator._handle_generator
train
def _handle_generator(self, fn): """Wraps a generator so that we're inside the cassette context for the duration of the generator. """ with self as cassette: coroutine = fn(cassette) # We don't need to catch StopIteration. The caller (Tornado's # gen.c...
python
{ "resource": "" }
q224296
Cassette.append
train
def append(self, request, response): """Add a request, response pair to this cassette""" request = self._before_record_request(request) if not request: return # Deepcopy is here because mutation of `response` will corrupt the # real response. response = copy.d...
python
{ "resource": "" }
q224297
Cassette._responses
train
def _responses(self, request): """ internal API, returns an iterator with all responses matching the request. """ request = self._before_record_request(request) for index, (stored_request, response) in enumerate(self.data): if requests_match(request, stored_re...
python
{ "resource": "" }
q224298
Cassette.play_response
train
def play_response(self, request): """ Get the response corresponding to a request, but only if it hasn't been played back before, and mark it as played """ for index, response in self._responses(request): if self.play_counts[index] == 0: self.play_coun...
python
{ "resource": "" }
q224299
Cassette.responses_of
train
def responses_of(self, request): """ Find the responses corresponding to a request. This function isn't actually used by VCR internally, but is provided as an external API. """ responses = [response for index, response in self._responses(request)] if responses: ...
python
{ "resource": "" }