Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
353,000
def is_callable(self): self._callable = Call(self, call_name=self._name, callable=True) return self
The fake can be called. This is useful for when you stub out a function as opposed to a class. For example:: >>> import fudge >>> remove = Fake('os.remove').is_callable() >>> remove('some/path')
353,001
def bdp_bds_cache(func, tickers, flds, **kwargs) -> ToQuery: cache_data = [] log_level = kwargs.get(, logs.LOG_LEVEL) logger = logs.get_logger(bdp_bds_cache, level=log_level) kwargs[] = kwargs.pop(, func == ) kwargs[] = kwargs.get(, True) tickers = utils.flatten(tickers) flds = utils.f...
Find cached `BDP` / `BDS` queries Args: func: function name - bdp or bds tickers: tickers flds: fields **kwargs: other kwargs Returns: ToQuery(ticker, flds, kwargs)
353,002
def map(self, key_pattern, func, all_args, timeout=None): results = [] keys = [ make_key(key_pattern, func, args, {}) for args in all_args ] cached = dict(zip(keys, self.get_many(keys))) cache_to_add = {} for key, args in zip(keys, all_arg...
Cache return value of multiple calls. Args: key_pattern (str): the key pattern to use for generating keys for caches of the decorated function. func (function): the function to call. all_args (list): a list of args to be used to make calls to ...
353,003
def newlogins(sessions): if not sessions: return [], [] users = {} dates = {} for session in sessions: user = session.user date = session.started_at.strftime("%Y/%m/%d") if user not in users: users[user] = date ...
Brand new logins each day, and total of users each day. :return: data, total 2 lists of dictionaries of the following format [{'x':epoch, 'y': value},]
353,004
def handle(self, pkt, raddress, rport): "Handle a packet, hopefully an ACK since we just sent a DAT." if isinstance(pkt, TftpPacketACK): log.debug("Received ACK for packet %d" % pkt.blocknumber) if self.context.next_block == pkt.blocknumber: if self.c...
Handle a packet, hopefully an ACK since we just sent a DAT.
353,005
def show_weights(estimator, **kwargs): format_kwargs, explain_kwargs = _split_kwargs(kwargs) expl = explain_weights(estimator, **explain_kwargs) html = format_as_html(expl, **format_kwargs) return HTML(html)
Return an explanation of estimator parameters (weights) as an IPython.display.HTML object. Use this function to show classifier weights in IPython. :func:`show_weights` accepts all :func:`eli5.explain_weights` arguments and all :func:`eli5.formatters.html.format_as_html` keyword arguments, so i...
353,006
def access_token_valid(self, token, log_msg): if (token in self.access_tokens): (cookie, issue_time) = self.access_tokens[token] age = int(time.time()) - issue_time if (age <= (self.access_token_lifetime + 1)): self.logger.info(log_msg + " " + token +...
Check token validity. Returns true if the token is valid. The set of allowed access tokens is stored in self.access_tokens. Uses log_msg as prefix to info level log message of acceptance or rejection.
353,007
def phenotypes(): ind_id = request.form[] phenotype_id = request.form[] if not phenotype_id: return abort(500, ) ind_obj = app.db.individual(ind_id) try: added_terms = app.db.add_phenotype(ind_obj, phenotype_id) if added_terms is None: flash("Term with id {...
Add phenotype(s) to the case model.
353,008
def get(self, request, *args, **kwargs): user_has_validation_string = self.get_object().validationString user_has_permissions = request.user.has_perm() if request.GET.get(, None) == user_has_validation_string or user_has_permissions: return super(ViewInvoiceView, self).get(r...
Invoices can be viewed only if the validation string is provided, unless the user is logged in and has view_all_invoice permissions
353,009
def views_preview(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/views api_path = "/api/v2/views/preview.json" return self.call(api_path, method="POST", data=data, **kwargs)
https://developer.zendesk.com/rest_api/docs/core/views#previewing-views
353,010
def read(self, size=None): if not self._is_open: raise IOError() if self._range_offset < 0 or self._range_size < 0: raise IOError() if self._current_offset < 0: raise IOError( .format( self._current_offset)) if self._current_offset >= self._range_size: ...
Reads a byte string from the file-like object at the current offset. The function will read a byte string of the specified size or all of the remaining data if no size was specified. Args: size (Optional[int]): number of bytes to read, where None is all remaining data. Returns: ...
353,011
def iget_list_column_slice(list_, start=None, stop=None, stride=None): if isinstance(start, slice): slice_ = start else: slice_ = slice(start, stop, stride) return (row[slice_] for row in list_)
iterator version of get_list_column
353,012
def unzip(zip_uri, is_url, clone_to_dir=, no_input=False, password=None): clone_to_dir = os.path.expanduser(clone_to_dir) make_sure_path_exists(clone_to_dir) if is_url: identifier = zip_uri.rsplit(, 1)[1] zip_path = os.path.join(clone_to_dir, identifier) ...
Download and unpack a zipfile at a given URI. This will download the zipfile to the cookiecutter repository, and unpack into a temporary directory. :param zip_uri: The URI for the zipfile. :param is_url: Is the zip URI a URL or a file? :param clone_to_dir: The cookiecutter repository directory ...
353,013
def end_of_directory(self, succeeded=True, update_listing=False, cache_to_disc=True): self._update_listing = update_listing if not self._end_of_directory: self._end_of_directory = True return xbmcplugin.endOfDirectory(self.handle, su...
Wrapper for xbmcplugin.endOfDirectory. Records state in self._end_of_directory. Typically it is not necessary to call this method directly, as calling :meth:`~xbmcswift2.Plugin.finish` will call this method.
353,014
def setdefaults(d, defaults): if not isinstance(d, dict) or defaults is None: return d elif isinstance(defaults, _wrap_types): return setdefaults(d, [defaults]) use_none = not any(isinstance(s, dict) for s in defaults) accumulated = {} for current, remaining in _to_ke...
If defaults is a str, updates a dict with None at an optionally dot-notated current: 'a.b' --> {'a': {'b': None}} If defaults is a list, updates a dict with None at each optionally dot-notated current: ['a.b', 'a.c'] --> {'a': {'b': None, 'c': None}} If defaults is a dict, applies keys as fields...
353,015
def psychrometric_vapor_pressure_wet(dry_bulb_temperature, wet_bulb_temperature, pressure, psychrometer_coefficient=6.21e-4 / units.kelvin): r return (saturation_vapor_pressure(wet_bulb_temperature) - psychrometer_coefficient * pressure * (dry_bulb_temperature - ...
r"""Calculate the vapor pressure with wet bulb and dry bulb temperatures. This uses a psychrometric relationship as outlined in [WMO8-2014]_, with coefficients from [Fan1987]_. Parameters ---------- dry_bulb_temperature: `pint.Quantity` Dry bulb temperature wet_bulb_temperature: `pint....
353,016
def API520_SH(T1, P1): r if P1 > 20780325.0: raise Exception() if T1 > 922.15: raise Exception() if T1 < 422.15: return 1. return float(bisplev(T1, P1, API520_KSH_tck))
r'''Calculates correction due to steam superheat for steam flow for use in API 520 relief valve sizing. 2D interpolation among a table with 28 pressures and 10 temperatures is performed. Parameters ---------- T1 : float Temperature of the fluid entering the valve [K] P1 : float ...
353,017
def _stump(f, *args, **kwargs): global LOGGER def aux(*xs, **kws): f_kws = kws.copy() f_kws.update(dict(zip(inspect.getfullargspec(f).args, xs))) level = kwargs.get(, logging.INFO) post = kwargs.get(, False) pre = kwargs.get(, False) print_return = kwargs.g...
Worker for the common actions of all stump methods, aka the secret sauce. *Keyword parameters* - log :: integer - Specifies a custom level of logging to pass to the active logger. - Default: INFO - print_time :: bool - Include timestamp in message - print_return :: bool - in...
353,018
def load_frompickle(cls, fname, reload_object=False): if fname[-4:] != : fname += with open(fname, ) as f: tnet = pickle.load(f) if reload_object: reloadnet = teneto.TenetoBIDS(tnet.BIDS_dir, pipeline=tnet.pipeline, pipeline_subdir=tnet.pipeline_subd...
Loaded saved instance of fname : str path to pickle object (output of TenetoBIDS.save_aspickle) reload_object : bool (default False) reloads object by calling teneto.TenetoBIDS (some information lost, for development) Returns ------- self : ...
353,019
def serialize(obj, **options): try: if in options: return salt.utils.json.dump(obj, _json_module=_json, **options) else: return salt.utils.json.dumps(obj, _json_module=_json, **options) except Exception as error: raise SerializationError(error)
Serialize Python data to JSON. :param obj: the data structure to serialize :param options: options given to lower json/simplejson module.
353,020
def insert_patches(self, patches): patchlines = [] for patch_name in patches: patchline = PatchLine(patch_name) patch = patchline.get_patch() if patch: self.patch2line[patch] = patchline patchlines.append(patchline) patchli...
Insert list of patches at the front of the curent patches list
353,021
def discover(package, cls_match_func): matched_classes = set() for _, module_name, _ in pkgutil.walk_packages( package.__path__, prefix=package.__name__ + , ): module = __import__(module_name, fromlist=[str()], level=0) for _, imported_class in inspect...
Returns a set of classes in the directory matched by cls_match_func Args: path - A Python package cls_match_func - Function taking a class and returning true if the class is to be included in the output.
353,022
def writeString(self, u): s = self.context.getBytesForString(u) self.writeBytes(s)
Write a unicode to the data stream.
353,023
def NumbersToWords(number): units = [ , , , , , , , , ] tens = [ , , , , , , , , ] output = "" if number != 0: str_val = str(number) if 4 ...
little function that converts numbers to words. This could be more efficient, and won't work if the number is bigger than 999 but it's for stave names, and I doubt any part would have more than 10 staves let alone 999.
353,024
def hline( self, x: int, y: int, width: int, bg_blend: int = tcod.constants.BKGND_DEFAULT, ) -> None: self.__deprecate_defaults("draw_rect", bg_blend) lib.TCOD_console_hline(self.console_c, x, y, width, bg_blend)
Draw a horizontal line on the console. This always uses ord('─'), the horizontal line character. Args: x (int): The x coordinate from the left. y (int): The y coordinate from the top. width (int): The horizontal length of this line. bg_blend (int): The b...
353,025
def _proc_loop(proc_id, alive, queue, fn): print("proc {} started".format(proc_id)) try: while alive.value: data = fn() put_success = False while alive.value and not put_success: try: queue.p...
Thread loop for generating data Parameters ---------- proc_id: int Process id alive: multiprocessing.Value variable for signaling whether process should continue or not queue: multiprocessing.Queue queue for passing data back fn: funct...
353,026
def android_setup_view(request): logger.debug(request.POST) if request.method == "POST": if "user_token" in request.POST and "gcm_token" in request.POST: user_token = request.POST.get("user_token") gcm_token = request.POST.get("gcm_token") logger.debug(user_toke...
Set up a GCM session. This does *not* require a valid login session. Instead, a token from the client session is sent to the Android backend, which queries a POST request to this view. The "android_gcm_rand" is randomly set when the Android app is detected through the user agent. If it has the same val...
353,027
def cleanup(workdir, fileroot, scans=[]): os.chdir(workdir) for scan in scans: merge_segments(fileroot, scan, cleanup=True, sizelimit=2.)
Cleanup up noise and cands files. Finds all segments in each scan and merges them into single cand/noise file per scan.
353,028
def typelogged(memb): if not pytypes.typelogging_enabled: return memb if _check_as_func(memb): return typelogged_func(memb) if isclass(memb): return typelogged_class(memb) if ismodule(memb): return typelogged_module(memb) if memb in sys.modules or memb in pytypes...
Decorator applicable to functions, methods, properties, classes or modules (by explicit call). If applied on a module, memb must be a module or a module name contained in sys.modules. See pytypes.set_global_typelogged_decorator to apply this on all modules. Observes function and method calls at runtime ...
353,029
def compatibility_or_constraints(self, target): if self.get_options().is_flagged(): return tuple(self.interpreter_constraints) return tuple(target.compatibility or self.interpreter_constraints)
Return either the compatibility of the given target, or the interpreter constraints. If interpreter constraints are supplied by the CLI flag, return those only.
353,030
def _swap_gate(self, lines, ctrl_lines): delta_pos = self._gate_offset(SWAP) gate_width = self._gate_width(SWAP) lines.sort() gate_str = "" for line in lines: op = self._op(line) w = "{}cm".format(.5 * gate_width) s1 = "[xshift=-{w},y...
Return the TikZ code for a Swap-gate. :param lines: List of length 2 denoting the target qubit of the Swap gate. :type: list[int] :param ctrl_lines: List of qubit lines which act as controls. :type: list[int]
353,031
def file_size(f): if isinstance(f, (six.string_types, six.text_type)): return os.path.getsize(f) else: cur = f.tell() f.seek(0, 2) size = f.tell() f.seek(cur) return size
Returns the size of a file in bytes. Raises ------ OSError : Accessing the given file path failed Parameters ---------- f : io.IOBase | str The file path or object for which the size should be determined
353,032
def dump_counts(self, out=sys.stdout, count_fn=len, colwidth=10): if len(self._pivot_attrs) == 1: out.write("Pivot: %s\n" % .join(self._pivot_attrs)) maxkeylen = max(len(str(k)) for k in self.keys()) maxvallen = colwidth keytally = {} for k, s...
Dump out the summary counts of entries in this pivot table as a tabular listing. @param out: output stream to write to @param count_fn: (default=len) function for computing value for each pivot cell @param colwidth: (default=10)
353,033
def merge_dicts(a, b): anyconfig.merge(a, b, ac_merge=MERGE_STRATEGY) return a
Merges the values of B into A and returns a mutated dict A. :: dict a b: - c: 0 - c: 2 d: e: "aaa" f: 3 dict b a: 1 b: - c: 3 d: e: "bbb" Will give an object such as:: {'a': 1...
353,034
def discount_with_boundaries(X, New, gamma): Y = np.zeros_like(X) T = X.shape[0] Y[T-1] = X[T-1] for t in range(T-2, -1, -1): Y[t] = X[t] + gamma * Y[t+1] * (1 - New[t+1]) return Y
X: 2d array of floats, time x features New: 2d array of bools, indicating when a new episode has started
353,035
def load_lsdsng(filename): with open(filename, ) as fp: preamble_data = bread.parse(fp, spec.lsdsng_preamble) with open(filename, ) as fp: fp.seek(int(len(preamble_data) / 8)) factory = BlockFactory() while True: block_data = b...
Load a Project from a ``.lsdsng`` file. :param filename: the name of the file from which to load :rtype: :py:class:`pylsdj.Project`
353,036
def decrypt(data, _key): if _key is None: Log.error("Expecting a key") _input = get_module("mo_json").json2value(data.decode(), leaves=False, flexible=False) key_expander_256 = key_expander.KeyExpander(256) expanded_key = key_expander_256.expand(_key) aes_cipher_256 = aes_ci...
ACCEPT BYTES -> UTF8 -> JSON -> {"salt":s, "length":l, "data":d}
353,037
def get_tournament(self, tag: crtag, timeout=0): url = self.api.TOURNAMENT + + tag return self._get_model(url, PartialTournament, timeout=timeout)
Get a tournament information Parameters ---------- tag: str A valid tournament tag. Minimum length: 3 Valid characters: 0289PYLQGRJCUV \*\*timeout: Optional[int] = None Custom timeout that overwrites Client.timeout
353,038
def find_nearest(sorted_list, x): if x <= sorted_list[0]: return sorted_list[0] elif x >= sorted_list[-1]: return sorted_list[-1] else: lower = find_le(sorted_list, x) upper = find_ge(sorted_list, x) if (x - lower) > (upper - x): return upper ...
Find the nearest item of x from sorted array. :type array: list :param array: an iterable object that support inex :param x: a comparable value note: for finding the nearest item from a descending array, I recommend find_nearest(sorted_list[::-1], x). Because the built-in list[::-1] method is...
353,039
def post_dispatch(self): middleware = sort_by_priority(self, reverse=True) return tuple(m.post_dispatch for m in middleware if hasattr(m, ))
List of post-dispatch methods from registered middleware.
353,040
def render_impl(self, template, context, at_paths=None, at_encoding=anytemplate.compat.ENCODING, **kwargs): if "text" in kwargs: kwargs["text"] = None if "input_encoding" not in kwargs: kwargs["input_encoding"] = at_encoding.lower() if "outp...
Render given template file and return the result. :param template: Template file path :param context: A dict or dict-like object to instantiate given template file :param at_paths: Template search paths :param at_encoding: Template encoding :param kwargs: Keyword arg...
353,041
def server_session(model=None, session_id=None, url="default", relative_urls=False, resources="default"): ll load separately are of the same version as that of the server if session_id is None: raise ValueError("Must supply a session_id") url = _clean_url(url) app_path = _get_app_p...
Return a script tag that embeds content from a specific existing session on a Bokeh server. This function is typically only useful for serving from a a specific session that was previously created using the ``bokeh.client`` API. Bokeh apps embedded using these methods will NOT set the browser window t...
353,042
def update_all(cls, engine, obj_or_data, upsert=False): obj_or_data = ensure_list(obj_or_data) update_all( engine=engine, table=cls.__table__, data=[obj.to_dict(include_null=False) for obj in obj_or_data], upsert=upsert, )
The :meth:`sqlalchemy.crud.updating.update_all` function in ORM syntax. :param engine: an engine created by``sqlalchemy.create_engine``. :param obj_or_data: single object or list of object :param upsert: if True, then do insert also.
353,043
def debugInfo(self): return ("min = {}, max = {}, step = {}, decimals = {}, specVal = {}" .format(self.minValue, self.maxValue, self.stepSize, self.decimals, self.specialValueText))
Returns the string with debugging information
353,044
def bs_param_dists(run_list, **kwargs): fthetas = kwargs.pop(, [lambda theta: theta[:, 0], lambda theta: theta[:, 1]]) labels = kwargs.pop(, [r + str(i + 1) + for i in range(len(fthetas))]) ftheta_lims = kwargs.pop(, [[-1, 1]] * l...
Creates posterior distributions and their bootstrap error functions for input runs and estimators. For a more detailed description and some example use cases, see 'nestcheck: diagnostic tests for nested sampling calculations' (Higson et al. 2019). Parameters ---------- run_list: dict or list o...
353,045
def _fit_overlay_lists(self, text, start, matchers, **kw): if matchers: for o in matchers[0].fit_overlays(text, start): for rest in self._fit_overlay_lists(text, o.end, matchers[1:]): yield [o] + rest else: yield []
Return a list of overlays that start at start.
353,046
def canMove(self): if not self.filled(): return True for y in self.__size_range: for x in self.__size_range: c = self.getCell(x, y) if (x < self.__size-1 and c == self.getCell(x+1, y)) \ or (y < self.__size-1 and c == s...
test if a move is possible
353,047
def get_power(self): power = (yield from self.handle_int(self.API.get())) return bool(power)
Check if the device is on.
353,048
def esp(self): result = np.zeros(self.numc, float) for index1 in range(self.numc): result[index1] = self.esp_component(index1) return result
Compute the electrostatic potential at each atom due to other atoms
353,049
def rotate(self, deg, **kwargs): opts = Image._normalize_options(kwargs) if deg == "auto": if self._orig_format == "JPEG": try: exif = self.img._getexif() or dict() deg = _orientation_to_rotation.get(exif.get(274, 0), 0) ...
Rotates the image clockwise around its center. Returns the instance. Supports the following optional keyword arguments: expand - Expand the output image to fit rotation
353,050
def four_blocks(topleft, topright, bottomleft, bottomright): return vstack(hstack(topleft, topright), hstack(bottomleft, bottomright))
Convenience function that creates a block matrix with the specified blocks. Each argument must be a NumPy matrix. The two top matrices must have the same number of rows, as must the two bottom matrices. The two left matrices must have the same number of columns, as must the two right matrices.
353,051
def predict_mappings(self, mappings): if self.nat_type not in self.predictable_nats: msg = "Can't predict mappings for non-predictable NAT type." raise Exception(msg) for mapping in mappings: mapping["bound"] = mapping["sock"].getsockname()[1] ...
This function is used to predict the remote ports that a NAT will map a local connection to. It requires the NAT type to be determined before use. Current support for preserving and delta type mapping behaviour.
353,052
def drop(self, ex): "helper for apply_sql in DropX case" if ex.name not in self: if ex.ifexists: return raise KeyError(ex.name) table_ = self[ex.name] parent = table_.parent_table if table_.child_tables: if not ex.cascade: raise table.IntegrityError(,ex.name) ...
helper for apply_sql in DropX case
353,053
def row_from_cols(self, values): row = self.RowType() for c, t, v in zip(self.dbcolumnnames, self.dbcolumntypes, values): if t in ligolwtypes.IDTypes: v = ilwd.ilwdchar(v) setattr(row, c, v) return row
Given an iterable of values in the order of columns in the database, construct and return a row object. This is a convenience function for turning the results of database queries into Python objects.
353,054
def _tomask(self, indices, element): r element = self._parse_element(element, single=True) indices = self._parse_indices(indices) N = sp.shape(self[element + ])[0] ind = sp.array(indices, ndmin=1) mask = sp.zeros((N, ), dtype=bool) mask[ind] = True return ...
r""" This is a generalized version of tomask that accepts a string of 'pore' or 'throat' for programmatic access.
353,055
def get_top_submissions(course_id, item_id, item_type, number_of_top_scores, use_cache=True, read_replica=True): if number_of_top_scores < 1 or number_of_top_scores > MAX_TOP_SUBMISSIONS: error_msg = ( u"Number of top scores must be a number between 1 and {}.".format(MAX_TOP_SUBMISSIONS) ...
Get a number of top scores for an assessment based on a particular student item This function will return top scores for the piece of assessment. It will consider only the latest and greater than 0 score for a piece of assessment. A score is only calculated for a student item if it has completed the workfl...
353,056
def load(self, *filenames): if len(filenames) == 1: if os.path.basename( filenames[0] ) == : return self.load_coldshot( os.path.dirname( filenames[0]) ) elif os.path.isdir( filenames[0] ): return self.load_coldshot( filenames[0] ) try: ...
Load our dataset (iteratively)
353,057
def IntegerTake(input_vertex: vertex_constructor_param_types, index: Collection[int], label: Optional[str]=None) -> Vertex: return Integer(context.jvm_view().IntegerTakeVertex, label, cast_to_integer_vertex(input_vertex), cast_to_long_array(index))
A vertex that extracts a scalar at a given index :param input_vertex: the input vertex to extract from :param index: the index to extract at
353,058
def destroy_channels(self): for item_name in dir(self): item = getattr(self, item_name) if isinstance(item, self.RedisAtomicBase): self.redis.delete(item.item_name)
Destroy Redis channels managed by this state instance.
353,059
def getJobState(self, CorpNum, JobID, UserID=None): if JobID == None or len(JobID) != 18: raise PopbillException(-99999999, "작업아이디(jobID)가 올바르지 않습니다.") return self._httpget( + JobID + , CorpNum, UserID)
수집 상태 확인 args CorpNum : 팝빌회원 사업자번호 JobID : 작업아이디 UserID : 팝빌회원 아이디 return 수집 상태 정보 raise PopbillException
353,060
def GetOobResult(self, param, user_ip, gitkit_token=None): if in param: try: if param[] == GitkitClient.RESET_PASSWORD_ACTION: request = self._PasswordResetRequest(param, user_ip) oob_code, oob_link = self._BuildOobLink(request, ...
Gets out-of-band code for ResetPassword/ChangeEmail request. Args: param: dict of HTTP POST params user_ip: string, end user's IP address gitkit_token: string, the gitkit token if user logged in Returns: A dict of { email: user email who initializes the request new_emai...
353,061
def _patch_chromosomal_features(cytobands, one_chrom_match, two_chrom_match): chromosomes = cytobands["chrom"].unique() df = pd.DataFrame() for chromosome in chromosomes: chromosome_length = np.max( cytobands[cytobands["chrom"] == chromosome]["end"].values ) ...
Highlight positions for each chromosome segment / feature. Parameters ---------- cytobands : pandas.DataFrame cytoband table from UCSC one_chrom_match : list of dicts segments to highlight on the chromosomes representing one shared chromosome two_chrom_match : list of dicts ...
353,062
def reset(self): super(ApicalTiebreakSequenceMemory, self).reset() self.prevApicalInput = np.empty(0, dtype="uint32") self.prevApicalGrowthCandidates = np.empty(0, dtype="uint32") self.prevPredictedCells = np.empty(0, dtype="uint32")
Clear all cell and segment activity.
353,063
def batch_norm(inputs, decay=0.999, center=True, scale=False, epsilon=0.001, moving_vars=, activation=None, is_training=True, trainable=True, restore=True, scope=None, ...
Adds a Batch Normalization layer. Args: inputs: a tensor of size [batch_size, height, width, channels] or [batch_size, channels]. decay: decay for the moving average. center: If True, subtract beta. If False, beta is not created and ignored. scale: If True, multiply by gamma. If False, ga...
353,064
def read_band(self, blocksize=CHUNK_SIZE): band = self.filehandle shape = band.shape if len(band.block_shapes) == 1: total_size = blocksize * blocksize * 1.0 lines, cols = band.block_shapes[0] if cols > lines: hblocks = cols ...
Read the band in chunks.
353,065
def caption_hashtags(self) -> List[str]: if not self.caption: return [] hashtag_regex = re.compile(r"(?: return re.findall(hashtag_regex, self.caption.lower())
List of all lowercased hashtags (without preceeding #) that occur in the Post's caption.
353,066
def get_recipients_data(self, reports): if not reports: return [] recipients = [] recipient_names = [] for num, report in enumerate(reports): ar = report.getAnalysisRequest() report_recipient_names = [] ...
Recipients data to be used in the template
353,067
def sum_queryset(qs: QuerySet, key: str= , default=Decimal(0)) -> Decimal: res = qs.aggregate(b=Sum(key))[] return default if res is None else res
Returns aggregate sum of queryset 'amount' field. :param qs: QuerySet :param key: Field to sum (default: 'amount') :param default: Default value if no results :return: Sum of 'amount' field values (coalesced 0 if None)
353,068
def run_fusion(job, fastqs, junction_file, univ_options, star_fusion_options, fusion_inspector_options): work_dir = job.fileStore.getLocalTempDir() input_files = {: fastqs[0], : fastqs[1], : st...
Runs STAR-Fusion and filters fusion calls using FusionInspector :param tuple fastqs: RNA-Seq FASTQ Filestore IDs :param toil.fileStore.FileID junction_file: Chimeric junction file :param dict univ_options: universal arguments used by almost all tools :param dict star_fusion_options: STAR-Fusion specifi...
353,069
def print_class_details(self, fname, classname): fobj = open(fname, "w") fobj.write(self.header % (classname, self.style)) fobj.write("<h1>%s</h1>\n" % (classname)) sizes = [tobj.get_max_size() for tobj in self.index[classname]] total = 0 for s in sizes: ...
Print detailed statistics and instances for the class `classname`. All data will be written to the file `fname`.
353,070
def display_grid(self): window_start = self.parent.value() window_length = self.parent.value() window_end = window_start + window_length if self.parent.value(): x_tick = self.parent.value() x_ticks = arange(window_start, window_end + x_tick, x_tick) ...
Display grid on x-axis and y-axis.
353,071
async def list_statuses(self, request): error_traps = [error_handlers.StatusResponseMissing] if request.method == : if request.headers[] != : LOGGER.debug( , request.headers[]) raise errors.StatusWrong...
Fetches the committed status of batches by either a POST or GET. Request: body: A JSON array of one or more id strings (if POST) query: - id: A comma separated list of up to 15 ids (if GET) - wait: Request should not return until all batches committed ...
353,072
def image_upload(self, product_id, position, session, pic_path=None, image=None): request = TOPRequest() request[] = product_id request[] = position if pic_path!=None: request[] = pic_path if image!=None: request[] = image self.create(self.execute(request, sessio...
taobao.fenxiao.product.image.upload 产品图片上传 产品主图图片空间相对路径或绝对路径添加或更新,或者是图片上传。如果指定位置的图片已存在,则覆盖原有信息,如果位置为1,自动设为主图。
353,073
def parse_unicode(self, i, wide=False): text = self.get_wide_unicode(i) if wide else self.get_narrow_unicode(i) value = int(text, 16) single = self.get_single_stack() if self.span_stack: text = self.convert_case(chr(value), self.span_stack[-1]) value = o...
Parse Unicode.
353,074
def dotcase(text, acronyms=None): words, _case, _sep = case_parse.parse_case(text, acronyms) return .join([w.lower() for w in words])
Return text in dot.case style. Args: text: input string to convert case detect_acronyms: should attempt to detect acronyms acronyms: a list of acronyms to detect >>> dotcase("hello world") 'hello.world' >>> dotcase("helloHTMLWorld", True, ["HTML"]) 'hello.html.world'
353,075
def cli(env, ack_all): manager = AccountManager(env.client) events = manager.get_upcoming_events() if ack_all: for event in events: result = manager.ack_event(event[]) event[] = result env.fout(event_table(events))
Summary and acknowledgement of upcoming and ongoing maintenance events
353,076
def load_all_resources(): pkgname = resources.__name__ for importer, mod_name, _ in pkgutil.iter_modules(resources.__path__): full_mod_name = % (pkgname, mod_name) if full_mod_name not in sys.modules: module = importer.find_module(mod_name ).load_module(...
Load all resources inside this package When compiling qt resources, the compiled python file will register the resource on import. .. Warning:: This will simply import all modules inside this package
353,077
def bench(image, thread_count): threads = [threading.Thread(target=lambda: encoder.encode_png(image)) for _ in xrange(thread_count)] start_time = datetime.datetime.now() for thread in threads: thread.start() for thread in threads: thread.join() end_time = datetime.datetime.now() delt...
Encode `image` to PNG on `thread_count` threads in parallel. Returns: A `float` representing number of seconds that it takes all threads to finish encoding `image`.
353,078
def _inline_activate_venv(): components = [] for name in ("bin", "Scripts"): bindir = os.path.join(project.virtualenv_location, name) if os.path.exists(bindir): components.append(bindir) if "PATH" in os.environ: components.append(os.environ["PATH"]) os.environ["P...
Built-in venv doesn't have activate_this.py, but doesn't need it anyway. As long as we find the correct executable, built-in venv sets up the environment automatically. See: https://bugs.python.org/issue21496#msg218455
353,079
def notify(request, info): t = time() actor = request.actor remote_actor = request.caller if isinstance(remote_actor, ActorProxyMonitor): remote_actor.mailbox = request.connection info[] = t remote_actor.info = info callback = remote_actor.callback ...
The actor notify itself with a dictionary of information. The command perform the following actions: * Update the mailbox to the current consumer of the actor connection * Update the info dictionary * Returns the time of the update
353,080
def add_permission(self, name): perm = self.find_permission(name) if perm is None: try: perm = self.permission_model() perm.name = name self.get_session.add(perm) self.get_session.commit() return perm ...
Adds a permission to the backend, model permission :param name: name of the permission: 'can_add','can_edit' etc...
353,081
def _log_board_terrain(self, terrain): self._logln(.format(.join(t.value for t in terrain)))
Tiles are logged counterclockwise beginning from the top-left. See module hexgrid (https://github.com/rosshamish/hexgrid) for the tile layout. :param terrain: list of catan.board.Terrain objects
353,082
def p_expr_GE_expr(p): p[0] = make_binary(p.lineno(2), , p[1], p[3], lambda x, y: x >= y)
expr : expr GE expr
353,083
def get_version_from_pc(search_dirs, target): for dirname in search_dirs: for root, dirs, files in os.walk(dirname): for f in files: if f == target: file_path = os.path.join(root, target) _tmp = _grep("Version: ", file_path) ...
similar to 'pkg-config --modversion GraphicsMagick++
353,084
def filter_single_reads_by_length(in_file, quality_format, min_length=20, out_file=None): logger.info("Removing reads in %s thare are less than %d bases." % (in_file, min_length)) in_iterator = SeqIO.parse(in_file, quality_format) out_iterator = (record...
removes reads from a fastq file which are shorter than a minimum length
353,085
def _GetOrderedEntries(data): def Tag(field): if isinstance(field, string_types): return 0, field if isinstance(field, int): return 1, field message = "Unexpected field of type ".format(field, type(field)) raise TypeError(message) for field...
Gets entries of `RDFProtoStruct` in a well-defined order. Args: data: A raw data dictionary of `RDFProtoStruct`. Yields: Entries of the structured in a well-defined order.
353,086
def read_component_sitemap( self, sitemapindex_uri, sitemap_uri, sitemap, sitemapindex_is_file): if (sitemapindex_is_file): if (not self.is_file_uri(sitemap_uri)): remote_uri = sitemap_uri sitemap_uri = self.mapper.src_to_dst(remo...
Read a component sitemap of a Resource List with index. Each component must be a sitemap with the
353,087
def get_all(self, key=None): key = self.definition.main_key if key is None else key key = self.definition.key_synonyms.get(key, key) entries = self._get_all(key) if key in self.definition.scalar_nonunique_keys: return set(entries) return entries
Returns all data entries for a particular key. Default is the main key. Args: key (str): key whose values to return (default: main key) Returns: List of all data entries for the key
353,088
def log_binary(logger, message, **kwargs): if logger.isEnabledFor(logging.DEBUG): output = (.format(k, binascii.hexlify( bytearray(v)).decode()) for k, v in sorted(kwargs.items())) logger.debug(, message, .join(output))
Log binary data if debug is enabled.
353,089
def route(origin, destination, city_origin=, city_destination=, time=None, deparr=, eduroam=False, recommendations=False, *, raw=False): assert deparr == or deparr == time = datetime.now() if time is None else datetime.fromtimestamp(int(time)) url = if eduroam \ else try: ...
VVO Online EFA TripRequest (GET http://efa.vvo-online.de:8080/dvb/XML_TRIP_REQUEST2) :param origin: Origin of route :param destination: Destination of route :param city_origin: City of origin :param city_destination: City of destination :param time: Unix timestamp of departure :param deparr...
353,090
def cli(env): manager = CapacityManager(env.client) items = manager.get_create_options() items.sort(key=lambda term: int(term[])) table = formatting.Table(["KeyName", "Description", "Term", "Default Hourly Price Per Instance"], title="Reserved Capacity Options") ta...
List options for creating Reserved Capacity
353,091
def add_sql_operation(self, app_label, sql_name, operation, dependencies): deps = [(dp[0], SQL_BLOB, dp[1], self._sql_operations.get(dp)) for dp in dependencies] self.add_operation(app_label, operation, dependencies=deps) self._sql_operations[(app_label, sql_name)] = operation
Add SQL operation and register it to be used as dependency for further sequential operations.
353,092
def gradients_X_X2(self, dL_dK, X, X2): return self._comp_grads(dL_dK, X, X2)[3:]
Derivative of the covariance matrix with respect to X
353,093
def validate_header(fields, column_names ): if len(fields) != len(column_names): msg = .format( len(column_names), len(fields)) raise FormatError(msg) for f, column in zip(fields, column_names): if f.identifier != column:...
Validate the `column_names` according to the specification in `fields`. :param fields: The `FieldSpec` objects forming the specification. :param column_names: A sequence of column identifier. :raises FormatError: When the number of columns or the column identifie...
353,094
def forwards(self, orm): "Write your forwards methods here." if not db.dry_run: for pl in orm[].objects.all(): pl.listing_set.update(publishable=pl.publishable) publishable = pl.publishable publishable.publish_from = pl.publish_from ...
Write your forwards methods here.
353,095
def edge_coord_in_direction(tile_id, direction): tile_coord = tile_id_to_coord(tile_id) for edge_coord in edges_touching_tile(tile_id): if tile_edge_offset_to_direction(edge_coord - tile_coord) == direction: return edge_coord raise ValueError(.format( direction, tile...
Returns the edge coordinate in the given direction at the given tile identifier. :param tile_id: tile identifier, int :param direction: direction, str :return: edge coord, int
353,096
def composite_multiscale_entropy(time_series, sample_length, scale, tolerance=None): cmse = np.zeros((1, scale)) for i in range(scale): for j in range(i): tmp = util_granulate_time_series(time_series[j:], i + 1) cmse[i] += sample_entropy(tmp, sample_length, tolerance) / (i ...
Calculate the Composite Multiscale Entropy of the given time series. Args: time_series: Time series for analysis sample_length: Number of sequential points of the time series scale: Scale factor tolerance: Tolerance (default = 0.1...0.2 * std(time_series)) Returns: Vect...
353,097
def _parse_and_store_headers(self): header_storage = self._store_header() header_storage.send(None) for header_line in self._next_header_line(): if header_line is None: self._buffer += yield continue else: header_...
Coroutine used retrieve header data and parse each header until the body is found.
353,098
def t_heredoc_END_HEREDOC(t): r if t.value == t.lexer.heredoc_label: del t.lexer.heredoc_label t.lexer.pop_state() else: t.type = return t
r'(?<=\n)[A-Za-z_][\w_]*
353,099
def unreachable(self, completed, failed=None): if len(self) == 0: return False against = set() if not self.success: against = completed if failed is not None and not self.failure: against = against.union(failed) if self.all: ...
return whether this dependency has become impossible.