Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
377,400
def parseService(self, yadis_url, uri, type_uris, service_element): self.type_uris = type_uris self.server_url = uri self.used_yadis = True if not self.isOPIdentifier(): self.local_id = findOPLocalIdentifier(servic...
Set the state of this object based on the contents of the service element.
377,401
def set_subparsers_args(self, *args, **kwargs): self.subparsers_args = args self.subparsers_kwargs = kwargs
Sets args and kwargs that are passed when creating a subparsers group in an argparse.ArgumentParser i.e. when calling argparser.ArgumentParser.add_subparsers
377,402
def add_thermodynamic(self, em=1000): internal = set(r for r in self._model.reactions if not self._model.is_exchange(r)) v = self._v alpha = self._prob.namespace(internal, types=lp.VariableType.Binary) dmu = self._prob.namesp...
Apply thermodynamic constraints to the model. Adding these constraints restricts the solution space to only contain solutions that have no internal loops [Schilling00]_. This is solved as a MILP problem as described in [Muller13]_. The time to solve a problem with thermodynamic constrai...
377,403
async def async_get_current_program(channel, no_cache=False): chan = await async_determine_channel(channel) guide = await async_get_program_guide(chan, no_cache) if not guide: _LOGGER.warning(, channel) return now = datetime.datetime.now() for prog in guide: start = prog...
Get the current program info
377,404
def setItemPolicy(self, item, policy): index = item._combobox_indices[self.ColAction].get(policy, 0) self._updateItemComboBoxIndex(item, self.ColAction, index) combobox = self.itemWidget(item, self.ColAction) if combobox: combobox.setCurrentIndex(index)
Sets the policy of the given item
377,405
def get_users(profile=): grafana* if isinstance(profile, string_types): profile = __salt__[](profile) response = requests.get( .format(profile[]), auth=_get_auth(profile), headers=_get_headers(profile), timeout=profile.get(, 3), ) if response.status_code >= 40...
List all users. profile Configuration profile used to connect to the Grafana instance. Default is 'grafana'. CLI Example: .. code-block:: bash salt '*' grafana4.get_users
377,406
def make_qr(content, error=None, version=None, mode=None, mask=None, encoding=None, eci=False, boost_error=True): return make(content, error=error, version=version, mode=mode, mask=mask, encoding=encoding, eci=eci, micro=False, boost_error=boost_error)
\ Creates a QR Code (never a Micro QR Code). See :py:func:`make` for a description of the parameters. :rtype: QRCode
377,407
def get_or_create_model_key(self): model_cache_info = model_cache_backend.retrieve_model_cache_info(self.model._meta.db_table) if not model_cache_info: return uuid.uuid4().hex, True return model_cache_info.table_key, False
Get or create key for the model. Returns ~~~~~~~ (model_key, boolean) tuple
377,408
def compile_pycos(toc): global BUILDPATH basepath = os.path.join(BUILDPATH, "localpycos") new_toc = [] for (nm, fnm, typ) in toc: source_fnm = fnm[:-1] leading, mod_name = nm.split(".")[:-1], nm.split(".")[-1] ...
Given a TOC or equivalent list of tuples, generates all the required pyc/pyo files, writing in a local directory if required, and returns the list of tuples with the updated pathnames.
377,409
def contents(self): c = self._header[:] c.append(.format(self.font_weight)) c.append(.format(self.font_family)) c.append(.format(*self.screen_size)) sclw = self.original_size[0] * self.scale_factor sclh = self.original_size[1] * self.scale_factor longside...
Get svg string
377,410
def _seg(chars): s = ret = [] flag = 0 for n, c in enumerate(chars): if RE_HANS.match(c): if n == 0: flag = 0 if flag == 0: s += c else: ret.append(s) flag = 0 ...
按是否是汉字进行分词
377,411
def delete(ctx, short_name): wva = get_wva(ctx) subscription = wva.get_subscription(short_name) subscription.delete()
Delete a specific subscription by short name
377,412
def transform_audio(self, y): temposcale data = super(TempoScale, self).transform_audio(y) data[] = np.abs(fmt(data.pop(), axis=1, n_fmt=self.n_fmt)).astype(np.float32)[self.idx] return data
Apply the scale transform to the tempogram Parameters ---------- y : np.ndarray The audio buffer Returns ------- data : dict data['temposcale'] : np.ndarray, shape=(n_frames, n_fmt) The scale transform magnitude coefficients
377,413
def default_namespace(self, value): if value is not None: assert type(value) is unicode, " attribute: type is not !".format( "default_namespace", value) self.__default_namespace = value
Setter for **self.__default_namespace** attribute. :param value: Attribute value. :type value: unicode
377,414
def handle_msg(self, msg): if msg.type == BGP_MSG_KEEPALIVE: if self.state.bgp_state == const.BGP_FSM_OPEN_CONFIRM: self.state.bgp_state = const.BGP_FSM_ESTABLISHED self._enqueue_init_updates() elif msg.type == BGP_MSG_UPDAT...
BGP message handler. BGP message handling is shared between protocol instance and peer. Peer only handles limited messages under suitable state. Here we handle KEEPALIVE, UPDATE and ROUTE_REFRESH messages. UPDATE and ROUTE_REFRESH messages are handled only after session is established.
377,415
def get_price(item): the_price = "No Default Pricing" for price in item.get(, []): if not price.get(): the_price = "%0.4f" % float(price[]) return the_price
Finds the price with the default locationGroupId
377,416
def gevent_monkey_patch_report(self): try: import gevent.socket import socket if gevent.socket.socket is socket.socket: self.log("gevent monkey patching is active") return True else: self.notify_user("geven...
Report effective gevent monkey patching on the logs.
377,417
def _format_job_instance(job): ret = {: job.get(, ), : salt.utils.json.loads(job.get(, )), : job.get(, ), : job.get(, ), : job.get(, )} return ret
Format the job instance correctly
377,418
def size(self, source): result = [] for src in self.source_expand(source): size = 0 for f in self.s3walk(src): size += f[] result.append((src, size)) return result
Get the size component of the given s3url. If it is a directory, combine the sizes of all the files under that directory. Subdirectories will not be counted unless --recursive option is set.
377,419
def trace(function, *args, **k) : if doTrace : print ("> "+function.__name__, args, k) result = function(*args, **k) if doTrace : print ("< "+function.__name__, args, k, "->", result) return result
Decorates a function by tracing the begining and end of the function execution, if doTrace global is True
377,420
def list(self, *args, **kwargs): greedy = kwargs.pop(, False) resp = self.client.api.networks(*args, **kwargs) networks = [self.prepare_model(item) for item in resp] if greedy and version_gte(self.client.api._version, ): for net in networks: net.reloa...
List networks. Similar to the ``docker networks ls`` command. Args: names (:py:class:`list`): List of names to filter by. ids (:py:class:`list`): List of ids to filter by. filters (dict): Filters to be processed on the network list. Available filters: ...
377,421
def step1ab(self): if self.b[self.k] == "s": if self.ends("sses"): self.k = self.k - 2 elif self.ends("ies"): self.setto("i") elif self.b[self.k - 1] != "s": self.k = self.k - 1 if self.ends("eed"): ...
step1ab() gets rid of plurals and -ed or -ing. e.g. caresses -> caress ponies -> poni ties -> ti caress -> caress cats -> cat feed -> feed agreed -> agree disabled -> disable matting ...
377,422
def _compute_zs_mat(sz:TensorImageSize, scale:float, squish:float, invert:bool, row_pct:float, col_pct:float)->AffineMatrix: "Utility routine to compute zoom/squish matrix." orig_ratio = math.sqrt(sz[1]/sz[0]) for s,r,i in zip(scale,squish, invert): s,r = 1/math.sqrt(s),math.sqrt(...
Utility routine to compute zoom/squish matrix.
377,423
def _set_data(self, data, offset=None, copy=False): data = np.array(data, copy=copy) data = self._normalize_shape(data) if offset is None: self._resize(data.shape) elif all([i == 0 for i in offset]) and data.shape == self._shape: ...
Internal method for set_data.
377,424
def _generate_struct_deserializer(self, struct): struct_name = fmt_class_prefix(struct) with self.block_func( func=, args=fmt_func_args_declaration([(, )]), return_type=.format(struct_name), ...
Emits the deserialize method for the serialization object for the given struct.
377,425
def read_string(self, len): format = + str(len) + length = struct.calcsize(format) info = struct.unpack(format, self.data[self.offset:self.offset + length]) self.offset += length return info[0]
Reads a string of a given length from the packet
377,426
def __dtw_calc_accu_cost(C, D, D_steps, step_sizes_sigma, weights_mul, weights_add, max_0, max_1): for cur_n in range(max_0, D.shape[0]): for cur_m in range(max_1, D.shape[1]): for cur_step_idx, cur_w_add, cur_w_mul in zip(range(step_sizes_sigma.shape...
Calculate the accumulated cost matrix D. Use dynamic programming to calculate the accumulated costs. Parameters ---------- C : np.ndarray [shape=(N, M)] pre-computed cost matrix D : np.ndarray [shape=(N, M)] accumulated cost matrix D_steps : np.ndarray [shape=(N, M)] ...
377,427
def split_grads_by_size(threshold_size, device_grads): small_grads = [] large_grads = [] for dl in device_grads: small_dl = [] large_dl = [] for (g, v) in dl: tensor_size = g.get_shape().num_elements() if tensor_size <= threshold_size: sma...
Break gradients into two sets according to tensor size. Args: threshold_size: int size cutoff for small vs large tensor. device_grads: List of lists of (gradient, variable) tuples. The outer list is over devices. The inner list is over individual gradients. Returns: small_grads: Subset of dev...
377,428
def fuse_batchnorm_weights(gamma, beta, mean, var, epsilon): scale = gamma / np.sqrt(var + epsilon) bias = beta - gamma * mean / np.sqrt(var + epsilon) return [scale, bias]
float sqrt_var = sqrt(var_data[i]); a_data[i] = bias_data[i] - slope_data[i] * mean_data[i] / sqrt_var; b_data[i] = slope_data[i] / sqrt_var; ... ptr[i] = b * ptr[i] + a;
377,429
def _unpickle_channel(raw): try: return pickle.loads(raw) except (ValueError, pickle.UnpicklingError, EOFError, TypeError, IndexError) as exc: if isinstance(raw, bytes): raw = raw.decode() try: Channel.MATCH.match(raw) except Va...
Try and unpickle a channel with sensible error handling
377,430
def getCert(username, password, certHost=_SERVER, certfile=None, certQuery=_PROXY): if certfile is None: certfile = tempfile.NamedTemporaryFile() password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() top_level_url = "http://" + certHost log...
Access the cadc certificate server.
377,431
def _process_health_pill_value(self, wall_time, step, device_name, output_slot, node_name, tensor_proto, ...
Creates a HealthPillEvent containing various properties of a health pill. Args: wall_time: The wall time in seconds. step: The session run step of the event. device_name: The name of the node's device. output_slot: The numeric output slot. node_name: The name of the node (without the ...
377,432
def iplot_histogram(data, figsize=None, number_to_keep=None, sort=, legend=None): html_template = Template() javascript_template = Template() div_number = str(time.time()) div_number = re.sub(, , div_number) if figsize is None: figsize = (7, 5...
Create a histogram representation. Graphical representation of the input array using a vertical bars style graph. Args: data (list or dict): This is either a list of dicts or a single dict containing the values to represent (ex. {'001' : 130}) figsize (...
377,433
def new_data(self, mem, addr, data): done = False if mem.id == self.id: if addr == LocoMemory.MEM_LOCO_INFO: self.nr_of_anchors = data[0] if self.nr_of_anchors == 0: done = True else: self.anchor...
Callback for when new memory data has been fetched
377,434
def nvmlDeviceSetEccMode(handle, mode): r fn = _nvmlGetFunctionPointer("nvmlDeviceSetEccMode") ret = fn(handle, _nvmlEnableState_t(mode)) _nvmlCheckReturn(ret) return None
r""" /** * Set the ECC mode for the device. * * For Kepler &tm; or newer fully supported devices. * Only applicable to devices with ECC. * Requires \a NVML_INFOROM_ECC version 1.0 or higher. * Requires root/admin permissions. * * The ECC mode determines whether the GPU enable...
377,435
def opened(self, block_identifier: BlockSpecification) -> bool: return self.token_network.channel_is_opened( participant1=self.participant1, participant2=self.participant2, block_identifier=block_identifier, channel_identifier=self.channel_identifier, ...
Returns if the channel is opened.
377,436
def buildcontent(self): self.buildcontainer() self.buildjschart() self.htmlcontent = self.template_content_nvd3.render(chart=self)
Build HTML content only, no header or body tags. To be useful this will usually require the attribute `juqery_on_ready` to be set which will wrap the js in $(function(){<regular_js>};)
377,437
def basic_stats(self): comment_score = sum(comment.score for comment in self.comments) if self.comments: comment_duration = (self.comments[-1].created_utc - self.comments[0].created_utc) comment_rate = self._rate(len(self.comments), commen...
Return a markdown representation of simple statistics.
377,438
def _create_ring(self, nodes): for node_name, node_conf in nodes: for w in range(0, node_conf[] * node_conf[]): self._distribution[node_name] += 1 self._ring[self.hashi( % (node_name, w))] = node_name self._keys = sorted(self._ring.keys())
Generate a ketama compatible continuum/ring.
377,439
def visualRect(self, index): rect = super(XTreeWidget, self).visualRect(index) item = self.itemFromIndex(index) if not rect.isNull() and item and item.isFirstColumnSpanned(): vpos = self.viewport().mapFromParent(QtCore.QPoint(0, 0)) rect.setX(vpos.x()) ...
Returns the visual rectangle for the inputed index. :param index | <QModelIndex> :return <QtCore.QRect>
377,440
def zero_level_calibrate(self, duration, t0=0.0): t1 = t0 + duration indices = np.flatnonzero((self.timestamps >= t0) & (self.timestamps <= t1)) m = np.mean(self.gyro_data[:, indices], axis=1) self.gyro_data -= m.reshape(3,1) return self.gyro_data
Performs zero-level calibration from the chosen time interval. This changes the previously lodaded data in-place. Parameters -------------------- duration : float Number of timeunits to use for calibration t0 : float Starting tim...
377,441
def inference(self, observed_arr): if observed_arr.ndim < 4: observed_arr = np.expand_dims(observed_arr, axis=1) self.__add_channel_flag = True else: self.__add_channel_flag = False return super().inference(observed_arr)
Draws samples from the `true` distribution. Args: observed_arr: `np.ndarray` of observed data points. Returns: `np.ndarray` of inferenced.
377,442
def start(self, *args, **kwargs): args = (self.counter,) + args thread = threading.Thread( target=self._work_callback, args=args, kwargs=kwargs ) thread.setDaemon(self.daemon) thread.start()
Start the task. This is: * not threadsave * assumed to be called in the gtk mainloop
377,443
def orient_directed_graph(self, data, graph): warnings.warn("The algorithm is ran on the skeleton of the given graph.") return self.orient_undirected_graph(data, nx.Graph(graph))
Run the algorithm on a directed_graph. Args: data (pandas.DataFrame): DataFrame containing the data graph (networkx.DiGraph): Skeleton of the graph to orient Returns: networkx.DiGraph: Solution on the given skeleton. .. warning:: The algorithm is...
377,444
def nvmlUnitGetHandleByIndex(index): r c_index = c_uint(index) unit = c_nvmlUnit_t() fn = _nvmlGetFunctionPointer("nvmlUnitGetHandleByIndex") ret = fn(c_index, byref(unit)) _nvmlCheckReturn(ret) return bytes_to_str(unit)
r""" /** * Acquire the handle for a particular unit, based on its index. * * For S-class products. * * Valid indices are derived from the \a unitCount returned by \ref nvmlUnitGetCount(). * For example, if \a unitCount is 2 the valid indices are 0 and 1, corresponding to UNIT 0 and U...
377,445
def figure_tensor(func, **tf_pyfunc_kwargs): name = tf_pyfunc_kwargs.pop(, func.__name__) @wraps(func) def wrapper(*func_args, **func_kwargs): tf_args = PositionalTensorArgs(func_args) def pyfnc_callee(*tensor_values, **unused): try: figs = as_list...
Decorate matplotlib drawing routines. This dectorator is meant to decorate functions that return matplotlib figures. The decorated function has to have the following signature def decorated(*args, **kwargs) -> figure or iterable of figures where `*args` can be any positional argument and `**k...
377,446
def _check_feature_types(self): if self.default_feature_type is not None and self.default_feature_type not in self.allowed_feature_types: raise ValueError() for feature_type in self.feature_collection: if feature_type is not None and feature_type not in self.allow...
Checks that feature types are a subset of allowed feature types. (`None` is handled :raises: ValueError
377,447
def update(self): stats = self.get_init_value() if self.input_method == : for k, v in iteritems(self.glances_amps.update()): stats.append({: k, : v.NAME, : v.result(), ...
Update the AMP list.
377,448
def sync_objects_out(self, force=False): self.log() from ambry.bundle.files import BuildSourceFile self.dstate = self.STATES.BUILDING for f in self.build_source_files.list_records(): self.log(.format(f.record.path)) f.objects_to_record() self....
Synchronize from objects to records, and records to files
377,449
def to_example_dict(encoder, inputs, mask, outputs): bases = [] input_ids = [] last_idx = -1 for row in np.argwhere(inputs): idx, base_id = row idx, base_id = int(idx), int(base_id) assert idx > last_idx while idx != last_idx + 1: bases.append(encoder.UNK) last_idx += 1 ...
Convert single h5 record to an example dict.
377,450
def add_rednoise(psr,A,gamma,components=10,seed=None): if seed is not None: N.random.seed(seed) t = psr.toas() minx, maxx = N.min(t), N.max(t) x = (t - minx) / (maxx - minx) T = (day/year) * (maxx - minx) size = 2*components F = N.zeros((psr.nobs,size),) f = N.zeros(s...
Add red noise with P(f) = A^2 / (12 pi^2) (f year)^-gamma, using `components` Fourier bases. Optionally take a pseudorandom-number-generator seed.
377,451
def get_getter(cls, prop_name, user_getter=None, getter_takes_name=False): if user_getter: if getter_takes_name: _deps = type(cls)._get_old_style_getter_deps(cls, prop_name, user_getter) ...
Returns a function wich is a getter for a property. prop_name is the name off the property. user_getter is an optional function doing the work. If specified, that function will be called instead of getting the attribute whose name is in 'prop_name'. If user_getter is specified ...
377,452
def validate(self, **kwargs): default_data_schema = json.load(open(self.default_schema_file, )) data = kwargs.pop("data", None) file_path = kwargs.pop("file_path", None) if file_path is None: raise LookupError("file_path argument must be supplied...
Validates a data file :param file_path: path to file to be loaded. :param data: pre loaded YAML object (optional). :return: Bool to indicate the validity of the file.
377,453
def apply(self, data, path=None, applicator=None): if applicator: applicator.pset = self else: applicator = Applicator(self) return applicator.apply(data, path=path)
Apply permissions in this set to the provided data, effectively removing all keys from it are not permissioned to be viewed Arguments: data -- dict of data Returns: Cleaned data
377,454
def parse_iso8601(text): parsed = _parse_iso8601_duration(text) if parsed is not None: return parsed m = ISO8601_DT.match(text) if not m: raise ParserError("Invalid ISO 8601 string") ambiguous_date = False is_date = False is_time = False year = 0 month = 1 ...
ISO 8601 compliant parser. :param text: The string to parse :type text: str :rtype: datetime.datetime or datetime.time or datetime.date
377,455
def config(filename): Config = collections.namedtuple(, [ , , , , , , , , ]) return [Config(**d) for d in _get_config_generator(filename)]
Construct `Config` object and return a list. :parse filename: A string containing the path to YAML file. :return: list
377,456
def process_pure_python(self, content): output = [] savefig = False multiline = False multiline_start = None fmtin = self.promptin ct = 0 for lineno, line in enumerate(content): line_stripped = line.strip() if not len(line): ...
content is a list of strings. it is unedited directive conent This runs it line by line in the InteractiveShell, prepends prompts as needed capturing stderr and stdout, then returns the content as a list as if it were ipython code
377,457
def config_unset(name, value_regex=None, repo=None, user=None, password=None, output_encoding=None, **kwargs): rbazbazfoofoo\..+ ret = {: name, : {}, : True, : } ...
r''' .. versionadded:: 2015.8.0 Ensure that the named config key is not present name The name of the configuration key to unset. This value can be a regex, but the regex must match the entire key name. For example, ``foo\.`` would not match all keys in the ``foo`` section, it would...
377,458
def simple_memoize(callable_object): cache = dict() def wrapper(*rest): if rest not in cache: cache[rest] = callable_object(*rest) return cache[rest] return wrapper
Simple memoization for functions without keyword arguments. This is useful for mapping code objects to module in this context. inspect.getmodule() requires a number of system calls, which may slow down the tracing considerably. Caching the mapping from code objects (there is *one* code object for each ...
377,459
def _get_friends_count(session, user_id): response = session.fetch(, user_id=user_id, count=1) return response["count"]
https://vk.com/dev/friends.get
377,460
def get_properties(self, mode, name_list=None): assert mode in ("allprop", "name", "named") if mode in ("allprop", "name"): assert name_list is None name_list = self.get_property_names(mode == "allprop") else: assert name_li...
Return properties as list of 2-tuples (name, value). If mode is 'name', then None is returned for the value. name the property name in Clark notation. value may have different types, depending on the status: - string or unicode: for standard property values....
377,461
def handle_pkg_optional_fields(self, package, package_node): self.handle_package_literal_optional(package, package_node, self.spdx_namespace.versionInfo, ) self.handle_package_literal_optional(package, package_node, self.spdx_namespace.packageFileName, ) self.handle_package_literal_opti...
Write package optional fields.
377,462
def check_num_columns_in_param_list_arrays(param_list): try: num_columns = param_list[0].shape[1] assert all([x is None or (x.shape[1] == num_columns) for x in param_list]) except AssertionError: msg = "param_list arrays should have equal number of columns." ...
Ensure that each array in param_list, that is not None, has the same number of columns. Raises a helpful ValueError if otherwise. Parameters ---------- param_list : list of ndarrays or None. Returns ------- None.
377,463
def reverse(self, search: str): url_path = "/api/reverse/{search}".format(search=search) return self._request(path=url_path)
Return reverse DNS lookup information we have for the given IPv{4,6} address with history of changes. Multiple reverse DNS entries may match. We return all of them.
377,464
def delete_folder(self, folder_id, folder_etag=None, recursive=None): return self( join(, folder_id), dict(recursive=recursive), method=, headers={: folder_etag} if folder_etag else dict() )
Delete specified folder. Pass folder_etag to avoid race conditions (raises error 412). recursive keyword does just what it says on the tin.
377,465
def sieve(self, name=None, sample_rate=None, sample_range=None, exact_match=False, **others): if isinstance(name, Pattern): flags = name.flags name = name.pattern else: flags = 0 if exact_match: name = name if name.s...
Find all `Channels <Channel>` in this list matching the specified criteria. Parameters ---------- name : `str`, or regular expression any part of the channel name against which to match (or full name if `exact_match=False` is given) sample_rate : `float` ...
377,466
def _on_connection_close(self, connection, reply_code_or_reason, reply_text=None): self._channel = None if isinstance(reply_code_or_reason, pika_errs.ConnectionClosed): reply_code = reply_code_or_reason.reply_code reply_text = reply_code_or_reason.reply_text eli...
Callback invoked when a previously-opened connection is closed. Args: connection (pika.connection.SelectConnection): The connection that was just closed. reply_code_or_reason (int|Exception): The reason why the channel was closed. In older versions of pik...
377,467
def filepattern(self, *args, **kwargs): return [p.filepattern(*args, **kwargs) for p in self.problems]
Returns a list of filepatterns, one for each problem.
377,468
def main(argv=None): print (transliterate(, , )) if argv is None: argv = sys.argv try: text, inFormat, outFormat = argv[1:4] except ValueError: print (main.__doc__) return 2 inFormat = inFormat.upper() outFormat = outFormat.upper() try: f...
Call transliterator from a command line. python transliterator.py text inputFormat outputFormat ... writes the transliterated text to stdout text -- the text to be transliterated OR the name of a file containing the text inputFormat -- the name of the character block or transliteration sc...
377,469
def get_commits(self, repo, organization=): path = ( + organization + + repo.name + ) is_only_today = False if not os.path.exists(path): all_commits = repo.iter_commits() is_only_today = True else: files = os.listdir(path) ...
Retrieves the number of commits to a repo in the organization. If it is the first time getting commits for a repo, it will get all commits and save them to JSON. If there are previous commits saved, it will only get commits that have not been saved to disk since the last date of commits.
377,470
def get(self, request, path): if path == : config = { : request.build_absolute_uri(), : self.meteor_settings.get(, {}), : request.build_absolute_uri( % ( self.runtime_config.get(, ), ...
Return HTML (or other related content) for Meteor.
377,471
def send_to_azure(instance, data, thread_number, sub_commit, table_info, nb_threads): rows = data["rows"] if not rows: return 0 columns_name = data["columns_name"] table_name = data["table_name"] + "_" + str(thread_number) print(C.HEADER + "Create table %s..." % table_name + C.ENDC) ...
data = { "table_name" : 'name_of_the_azure_schema' + '.' + 'name_of_the_azure_table' #Must already exist, "columns_name" : [first_column_name,second_column_name,...,last_column_name], "rows" : [[first_raw_value,second_raw_value,...,last_raw_value],...] }
377,472
def get_function(self, name): p = ffi.lib.LLVMPY_GetNamedFunction(self, _encode_string(name)) if not p: raise NameError(name) return ValueRef(p, , dict(module=self))
Get a ValueRef pointing to the function named *name*. NameError is raised if the symbol isn't found.
377,473
def handle_ChannelClose(self, frame): self.sender.send_CloseOK() exc = exceptions._get_exception_type(frame.payload.reply_code) self._close_all(exc)
AMQP server closed the channel with an error
377,474
def factory(ec, code=None, token=None, refresh=None, **kwargs): TTYPE = {: , : , : } args = {} if code: args[] = init_token_handler(ec, code, TTYPE[]) if token: args[] = init_token_handler(ec, token, TTYPE[]) if refresh: args[] = init_token_handler(ec, token, TTYPE[])...
Create a token handler :param code: :param token: :param refresh: :return: TokenHandler instance
377,475
def __get_untitled_file_name(self): untitledNameId = Editor._Editor__untitled_name_id for file in self.list_files(): if not os.path.dirname(file) == self.__default_session_directory: continue search = re.search(r"\d+", os.path.basename(file)) ...
Returns an untitled file name. :return: Untitled file name. :rtype: unicode
377,476
def create_dataset(self, name, **kwargs): return self._write_op(self._create_dataset_nosync, name, **kwargs)
Create an array. Parameters ---------- name : string Array name. data : array_like, optional Initial data. shape : int or tuple of ints Array shape. chunks : int or tuple of ints, optional Chunk shape. If not provided, will...
377,477
def _verify(function): def wrapped(pin, *args, **kwargs): pin = int(pin) if pin not in _open: ppath = gpiopath(pin) if not os.path.exists(ppath): log.debug("Creating Pin {0}".format(pin)) with _export_lock: ...
decorator to ensure pin is properly set up
377,478
def get_type(self): if self.type_idx_value == None: self.type_idx_value = self.CM.get_type(self.type_idx) return self.type_idx_value
Return the type of the field :rtype: string
377,479
async def issue_cmd(self, cmd, value, retry=3): async with self._cmd_lock: if not self.connected: _LOGGER.debug( "Serial transport closed, not sending command %s", cmd) return while not self._cmdq.empty(): _LOGG...
Issue a command, then await and return the return value. This method is a coroutine
377,480
def respond(self, text, sessionID = "general"): text = self.__normalize(text) previousText = self.__normalize(self.conversation[sessionID][-2]) text_correction = self.__correction(text) current_topic = self.topic[sessionID] current_topic_order = current_topic.split(".")...
Generate a response to the user input. :type text: str :param text: The string to be mapped :rtype: str
377,481
def read_igor_D_gene_parameters(params_file_name): params_file = open(params_file_name, ) D_gene_info = {} in_D_gene_sec = False for line in params_file: if line.startswith(): in_D_gene_sec = True elif in_D_gene_sec: if line[0] == : spli...
Load genD from file. genD is a list of genomic D information. Each element is a list of the name of the D allele and the germline sequence. Parameters ---------- params_file_name : str File name for a IGOR parameter file. Returns ------- genD : list List of genomic...
377,482
def _scaled_int(s): r s = bytearray(s) sign = 1 - ((s[0] & 0x80) >> 6) int_val = (((s[0] & 0x7f) << 16) | (s[1] << 8) | s[2]) log.debug(, .join(hex(c) for c in s), int_val, sign) return (sign * int_val) / 10000.
r"""Convert a 3 byte string to a signed integer value.
377,483
def emit_java_headers(target, source, env): class_suffix = env.get(, ) classdir = env.get() if not classdir: try: s = source[0] except IndexError: classdir = else: try: classdir = s.attributes.java_classdir except...
Create and return lists of Java stub header files that will be created from a set of class files.
377,484
def use_astropy_helpers(**kwargs): global BOOTSTRAPPER config = BOOTSTRAPPER.config config.update(**kwargs) BOOTSTRAPPER = _Bootstrapper(**config) BOOTSTRAPPER.run()
Ensure that the `astropy_helpers` module is available and is importable. This supports automatic submodule initialization if astropy_helpers is included in a project as a git submodule, or will download it from PyPI if necessary. Parameters ---------- path : str or None, optional A fil...
377,485
def compare_values(values0, values1): values0 = {v[0]: v[1:] for v in values0} values1 = {v[0]: v[1:] for v in values1} created = [(k, v[0], v[1]) for k, v in values1.items() if k not in values0] deleted = [(k, v[0], v[1]) for k, v in values0.items() if k not in values1] modified = [(k, v[0], ...
Compares all the values of a single registry key.
377,486
def calculate_mvgd_stats(nw): omega = 2 * pi * 50 nw.control_circuit_breakers(mode=) trafos_dict = {} generators_dict = {} branches_dict = {} ring_dict = {} LA_dict = {} other_nodes_dict = {} lv_branches_dict = {} trafos_idx = 0 gen_idx = ...
MV Statistics for an arbitrary network Parameters ---------- nw: :any:`list` of NetworkDing0 The MV grid(s) to be studied Returns ------- mvgd_stats : pandas.DataFrame Dataframe containing several statistical numbers about the MVGD
377,487
def extract_atoms(molecule): if molecule == : return molecule try: return float(molecule) except BaseException: pass atoms = if not molecule[0].isalpha(): i = 0 while not molecule[i].isalpha(): i += 1 prefactor = float(molecule[:i]) ...
Return a string with all atoms in molecule
377,488
def last_insert_id(self, cursor, table_name, pk_name): table_name = self.quote_name(table_name) cursor.execute("SELECT CAST(IDENT_CURRENT(%s) as bigint)", [table_name]) return ...
Given a cursor object that has just performed an INSERT statement into a table that has an auto-incrementing ID, returns the newly created ID. This method also receives the table name and the name of the primary-key column.
377,489
def is_module_on_std_lib_path(cls, module): module_file_real_path = os.path.realpath(module.__file__) if module_file_real_path.startswith(cls.STANDARD_LIB_PATH): return True elif os.path.splitext(module_file_real_path)[1] == : py_file_real_path = os.path.realpath(os.path.splitext(module_fil...
Sometimes .py files are symlinked to the real python files, such as the case of virtual env. However the .pyc files are created under the virtual env directory rather than the path in cls.STANDARD_LIB_PATH. Hence this function checks for both. :param module: a module :return: True if module is on inter...
377,490
def format_cert_name(env=, account=, region=, certificate=None): cert_name = None if certificate: if certificate.startswith(): LOG.info("Full ARN provided...skipping lookup.") cert_name = certificate else: generated_cert_name = generate_custom_cert_name(...
Format the SSL certificate name into ARN for ELB. Args: env (str): Account environment name account (str): Account number for ARN region (str): AWS Region. certificate (str): Name of SSL certificate Returns: str: Fully qualified ARN for SSL certificate None: Cer...
377,491
def _annotate_validations(eval_files, data): for key in ["tp", "tp-calls", "fp", "fn"]: if eval_files.get(key): eval_files[key] = annotation.add_genome_context(eval_files[key], data) return eval_files
Add annotations about potential problem regions to validation VCFs.
377,492
def sine(w, A=1, phi=0, offset=0): from math import sin def f(i): return A * sin(w*i + phi) + offset return partial(force, sequence=_advance(f))
Return a driver function that can advance a sequence of sine values. .. code-block:: none value = A * sin(w*i + phi) + offset Args: w (float) : a frequency for the sine driver A (float) : an amplitude for the sine driver phi (float) : a phase offset to start the sine driver wi...
377,493
def store_text_log_summary_artifact(job, text_log_summary_artifact): step_data = json.loads( text_log_summary_artifact[])[] result_map = {v: k for (k, v) in TextLogStep.RESULTS} with transaction.atomic(): for step in step_data[]: name = step[][:TextLogStep._meta.get_field()....
Store the contents of the text log summary artifact
377,494
def change_attributes(self, bounds, radii, colors): self.n_cylinders = len(bounds) self.is_empty = True if self.n_cylinders == 0 else False if self.is_empty: self.bounds = bounds self.radii = radii self.colors = colors re...
Reinitialize the buffers, to accomodate the new attributes. This is used to change the number of cylinders to be displayed.
377,495
def buffer_read(library, session, count): buffer = create_string_buffer(count) return_count = ViUInt32() ret = library.viBufRead(session, buffer, count, byref(return_count)) return buffer.raw[:return_count.value], ret
Reads data from device or interface through the use of a formatted I/O read buffer. Corresponds to viBufRead function of the VISA library. :param library: the visa library wrapped by ctypes. :param session: Unique logical identifier to a session. :param count: Number of bytes to be read. :return: ...
377,496
def strsettings(self, indent=0, maxindent=25, width=0): out = [] makelabel = lambda name: * indent + name + settingsindent = _autoindent([makelabel(s) for s in self.options], indent, maxindent) for name in self.option_order: option = self.options[name] ...
Return user friendly help on positional arguments. indent is the number of spaces preceeding the text on each line. The indent of the documentation is dependent on the length of the longest label that is shorter than maxindent. A label longer than maxindent will be p...
377,497
def get(self, field_paths=None, transaction=None): if isinstance(field_paths, six.string_types): raise ValueError(" must be a sequence of paths, not a string.") if field_paths is not None: mask = common_pb2.DocumentMask(field_paths=sorted(field_paths)) else: ...
Retrieve a snapshot of the current document. See :meth:`~.firestore_v1beta1.client.Client.field_path` for more information on **field paths**. If a ``transaction`` is used and it already has write operations added, this method cannot be used (i.e. read-after-write is not allowe...
377,498
def revise(csp, Xi, Xj, removals): "Return true if we remove a value." revised = False for x in csp.curr_domains[Xi][:]: if every(lambda y: not csp.constraints(Xi, x, Xj, y), csp.curr_domains[Xj]): csp.prune(Xi, x, removals) revised = True return...
Return true if we remove a value.
377,499
def get_eventhub_info(self): alt_creds = { "username": self._auth_config.get("iot_username"), "password":self._auth_config.get("iot_password")} try: mgmt_auth = self._create_auth(**alt_creds) mgmt_client = uamqp.AMQPClient(self.mgmt_target, auth=m...
Get details on the specified EventHub. Keys in the details dictionary include: -'name' -'type' -'created_at' -'partition_count' -'partition_ids' :rtype: dict