Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
369,000
def file_list(load): ret = set() try: for container in __opts__[]: if container.get(, ) != load[]: continue container_list = _get_container_path(container) + lk = container_list + salt.fileserver.wait_lock(lk, container_list, 5) ...
Return a list of all files in a specified environment
369,001
def reset_training_state(self, dones, batch_info): for idx, done in enumerate(dones): if done > 0.5: self.processes[idx].reset()
A hook for a model to react when during training episode is finished
369,002
def start(self): run_by_ui = False if not self.current_user.algo: self._job = Job(self._project.id, self._software.id).save() user_job = User().fetch(self._job.userJob) self.set_credentials(user_job.publicKey, user_job.privateKey) else: ...
Connect to the Cytomine server and switch to job connection Incurs dataflows
369,003
def _get_channel(host, timeout): connection = create_blocking_connection(host) if timeout >= 0: connection.add_timeout( timeout, lambda: sys.stderr.write("Timeouted!\n") or sys.exit(1) ) return connection.channel()
Create communication channel for given `host`. Args: host (str): Specified --host. timeout (int): Set `timeout` for returned `channel`. Returns: Object: Pika channel object.
369,004
def yield_to_ioloop(self): try: yield self._yield_condition.wait( self._message.channel.connection.ioloop.time() + 0.001) except gen.TimeoutError: pass
Function that will allow Rejected to process IOLoop events while in a tight-loop inside an asynchronous consumer. .. code-block:: python :caption: Example Usage class Consumer(consumer.Consumer): @gen.coroutine def process(self): ...
369,005
def page(self, enabled=values.unset, date_created_after=values.unset, date_created_before=values.unset, friendly_name=values.unset, page_token=values.unset, page_number=values.unset, page_size=values.unset): params = values.of({ : enabled, ...
Retrieve a single page of CompositionHookInstance records from the API. Request is executed immediately :param bool enabled: Only show Composition Hooks enabled or disabled. :param datetime date_created_after: Only show Composition Hooks created on or after this ISO8601 date-time with timezone....
369,006
def connect_patch_namespaced_pod_proxy(self, name, namespace, **kwargs): kwargs[] = True if kwargs.get(): return self.connect_patch_namespaced_pod_proxy_with_http_info(name, namespace, **kwargs) else: (data) = self.connect_patch_namespaced_pod_proxy_with_http_inf...
connect PATCH requests to proxy of Pod This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.connect_patch_namespaced_pod_proxy(name, namespace, async_req=True) >>> result = thread.get() :param ...
369,007
def _get_default_field_names(self, declared_fields, model_info): return ( [model_info.pk.name] + list(declared_fields.keys()) + list(model_info.fields.keys()) + list(model_info.relations.keys()) )
Return default field names for serializer.
369,008
def get_authuser_by_name(cls, request): username = authenticated_userid(request) if username: return cls.get_item(username=username)
Get user by username Used by Token-based auth. Is added as request method to populate `request.user`.
369,009
def main(argv=None): args = docopt.docopt(__doc__, argv=argv, version=__version__) verbose = bool(args[]) f_roll = dice.roll kwargs = {} if args[]: f_roll = dice.roll_min elif args[]: f_roll = dice.roll_max if args[]: try: kwargs[] = int(args[]) ...
Run roll() from a command line interface
369,010
def _set_error_handler_callbacks(self, app): @app.errorhandler(NoAuthorizationError) def handle_auth_error(e): return self._unauthorized_callback(str(e)) @app.errorhandler(CSRFError) def handle_csrf_error(e): return self._unauthorized_callback(str(e)) ...
Sets the error handler callbacks used by this extension
369,011
def promise_method(func): name = func.__name__ @wraps(func) def wrapped(self, *args, **kwargs): cls_name = type(self).__name__ if getattr(self, % (cls_name,)): return getattr(getattr(self, % (cls_name,)), name)(*args, **kwargs) return func(self, *args, **kwargs) ...
A decorator which ensures that once a method has been marked as resolved (via Class.__resolved)) will then propagate the attribute (function) call upstream.
369,012
def open_report_template_path(self): directory_name = QFileDialog.getExistingDirectory( self, self.tr(), self.leReportTemplatePath.text(), QFileDialog.ShowDirsOnly) if directory_name: self.leReportTemplatePath.setText(director...
Open File dialog to choose the report template path.
369,013
def set(self, key, value, time=0, compress_level=-1): returns = [] for server in self.servers: returns.append(server.set(key, value, time, compress_level=compress_level)) return any(returns)
Set a value for a key on server. :param key: Key's name :type key: str :param value: A value to be stored on server. :type value: object :param time: Time in seconds that your key will expire. :type time: int :param compress_level: How much to compress. ...
369,014
def add_all(self, items, overflow_policy=OVERFLOW_POLICY_OVERWRITE): check_not_empty(items, "items cant be greater than %d" % MAX_BATCH_SIZE) for item in items: check_not_none(item, "item can't be None") item_list = [self._to_data(x) for x in items] return self._enc...
Adds all of the item in the specified collection to the tail of the Ringbuffer. An add_all is likely to outperform multiple calls to add(object) due to better io utilization and a reduced number of executed operations. The items are added in the order of the Iterator of the collection. If there...
369,015
def get(self, using=None, **kwargs): return self._get_connection(using).indices.get(index=self._name, **kwargs)
The get index API allows to retrieve information about the index. Any additional keyword arguments will be passed to ``Elasticsearch.indices.get`` unchanged.
369,016
def find(*args, **kwargs): end_at = kwargs.get(, datetime.datetime.now()) start_at = kwargs.get(, end_at - datetime.timedelta(days=1)) limit = kwargs.get(, 50) user = kwargs.get(, None) if user: return request_log.find(start_at, end_at, limit, spec={: user}) else: ...
kwargs supported: user: the username start_at: start datetime object end_at: end datetime object limit: # of objects to fetch
369,017
def recursively_preempt_states(self): super(ContainerState, self).recursively_preempt_states() self._transitions_cv.acquire() self._transitions_cv.notify_all() self._transitions_cv.release() for state in self.states.values(): state.recursively_preemp...
Preempt the state and all of it child states.
369,018
def set_running_mean(self, running_mean): callBigDlFunc(self.bigdl_type, "setRunningMean", self.value, JTensor.from_ndarray(running_mean)) return self
Set the running mean of the layer. Only use this method for a BatchNormalization layer. :param running_mean: a Numpy array.
369,019
def clear(self): with self._conn: self._conn.execute() self._conn.execute()
Clear all work items from the session. This removes any associated results as well.
369,020
def _create_sagemaker_model(self, instance_type, accelerator_type=None, tags=None): container_def = self.prepare_container_def(instance_type, accelerator_type=accelerator_type) self.name = self.name or utils.name_from_image(container_def[]) enable_network_isolation = self.enable_network...
Create a SageMaker Model Entity Args: instance_type (str): The EC2 instance type that this Model will be used for, this is only used to determine if the image needs GPU support or not. accelerator_type (str): Type of Elastic Inference accelerator to attach to an endpoint...
369,021
def H12(self): "Information measure of correlation 1." maxima = np.vstack((self.hx, self.hy)).max(0) return (self.H9() - self.hxy1) / maxima
Information measure of correlation 1.
369,022
def _scale_y_values(self, values, new_min, new_max, scale_old_from_zero=True): scaled_values = [] y_min_value = min(values) if scale_old_from_zero: y_min_value = 0 y_max_value = max(values) new_min = 0 OldRange = (y_max_value - y_min_value) o...
Take values and transmute them into a new range
369,023
def acceptance_fractions(mean_acceptance_fractions, burn=None, ax=None): factor = 2.0 lbdim = 0.2 * factor trdim = 0.2 * factor whspace = 0.10 dimy = lbdim + factor + trdim dimx = lbdim + factor + trdim if ax is None: fig, ax = plt.subplots() else: fig = ax.figure...
Plot the meana cceptance fractions for each MCMC step. :param mean_acceptance_fractions: The acceptance fractions at each MCMC step. :type mean_acceptance_fractions: :class:`numpy.array` :param burn: [optional] The burn-in point. If provided, a dashed vertical line will be shown a...
369,024
def systemInformationType17(): a = L2PseudoLength(l2pLength=0x01) b = TpPd(pd=0x6) c = MessageType(mesType=0x3e) d = Si17RestOctets() packet = a / b / c / d return packet
SYSTEM INFORMATION TYPE 17 Section 9.1.43e
369,025
def _register_self(self, logfile, key=JobDetails.topkey, status=JobStatus.unknown): fullkey = JobDetails.make_fullkey(self.full_linkname, key) if fullkey in self.jobs: job_details = self.jobs[fullkey] job_details.status = status else: job_details = se...
Runs this link, captures output to logfile, and records the job in self.jobs
369,026
def add_output(summary_output, long_output, helper): if summary_output != : helper.add_summary(summary_output) helper.add_long_output(long_output)
if the summary output is empty, we don't add it as summary, otherwise we would have empty spaces (e.g.: '. . . . .') in our summary report
369,027
def build_system_error(cls, errors=None): errors = [errors] if not isinstance(errors, list) else errors return cls(Status.SYSTEM_ERROR, errors)
Utility method to build a HTTP 500 System Error response
369,028
def format_list(extracted_list): list = [] for filename, lineno, name, line in extracted_list: item = % (filename,lineno,name) if line: item = item + % line.strip() list.append(item) return list
Format a list of traceback entry tuples for printing. Given a list of tuples as returned by extract_tb() or extract_stack(), return a list of strings ready for printing. Each string in the resulting list corresponds to the item with the same index in the argument list. Each string ends in a newline; ...
369,029
def update_version_records(self): from .__init__ import __version__ as version with self.connection(commit=True) as connection: for vrec in self.get_version_records(): if (vrec.rash_version == version and vrec.schema_version == schema_version): ...
Update rash_info table if necessary.
369,030
def connect(host="localhost", user=None, password="", db=None, port=3306, unix_socket=None, charset=, sql_mode=None, read_default_file=None, conv=decoders, use_unicode=None, client_flag=0, cursorclass=Cursor, init_command=None, connect_timeout=None, read_defau...
See connections.Connection.__init__() for information about defaults.
369,031
def get_index_line(self,lnum): if lnum < 1: sys.stderr.write("ERROR: line number should be greater than zero\n") sys.exit() elif lnum > len(self._lines): sys.stderr.write("ERROR: too far this line nuber is not in index\n") sys.exit() return self._lines[lnum-1]
Take the 1-indexed line number and return its index information
369,032
def patch(self, path=None, url_kwargs=None, **kwargs): return self._session.patch(self._url(path, url_kwargs), **kwargs)
Sends a PUT request. :param path: The HTTP path (either absolute or relative). :param url_kwargs: Parameters to override in the generated URL. See `~hyperlink.URL`. :param **kwargs: Optional arguments that ``request`` takes. :return: response object
369,033
def air_range(self) -> Union[int, float]: if self._weapons: weapon = next( (weapon for weapon in self._weapons if weapon.type in {TargetType.Air.value, TargetType.Any.value}), None, ) if weapon: return weapon.range ...
Does not include upgrades
369,034
def calc_chunklen(alph_len): t add up to one input encoding chunk is minimal. ' binlen, enclen = min([ (i, i*8 / math.log(alph_len, 2)) for i in range(1, 7) ], key=lambda k: k[1] % 1) return binlen, int(enclen)
computes the ideal conversion ratio for the given alphabet. A ratio is considered ideal when the number of bits in one output encoding chunk that don't add up to one input encoding chunk is minimal.
369,035
def draw_flow(img, flow, step=16, dtype=uint8): maxval = iinfo(img.dtype).max canno = (0, maxval, 0) h, w = img.shape[:2] y, x = mgrid[step//2:h:step, step//2:w:step].reshape(2, -1) fx, fy = flow[y, x].T lines = vstack([x, y, (x+fx), (y+fy)]).T.reshape(-1, 2, 2) lines = int...
draws flow vectors on image this came from opencv/examples directory another way: http://docs.opencv.org/trunk/doc/py_tutorials/py_gui/py_drawing_functions/py_drawing_functions.html
369,036
def get_prior(self, twig=None, **kwargs): raise NotImplementedError kwargs[] = return self.filter(twig=twig, **kwargs)
[NOT IMPLEMENTED] :raises NotImplementedError: because it isn't
369,037
def _load_from_socket(port, auth_secret): (sockfile, sock) = local_connect_and_auth(port, auth_secret) sock.settimeout(None) write_int(BARRIER_FUNCTION, sockfile) sockfile.flush() res = UTF8Deserializer().loads(sockfile) sockfile.close() sock.close() return re...
Load data from a given socket, this is a blocking method thus only return when the socket connection has been closed.
369,038
def estimate_intraday(returns, positions, transactions, EOD_hour=23): txn_val = transactions.copy() txn_val.index.names = [] txn_val[] = txn_val.amount * txn_val.price txn_val = txn_val.reset_index().pivot_table( index=, values=, columns=).replace(np.nan, 0) txn_val[...
Intraday strategies will often not hold positions at the day end. This attempts to find the point in the day that best represents the activity of the strategy on that day, and effectively resamples the end-of-day positions with the positions at this point of day. The point of day is found by detecting w...
369,039
def object_to_id(self, obj): search = Credential.search() search = search.filter("term", username=obj.username) search = search.filter("term", secret=obj.secret) if obj.domain: search = search.filter("term", domain=obj.domain) else: searc...
Searches elasticsearch for objects with the same username, password, optional domain, host_ip and service_id.
369,040
def get_consensus_at(self, block_id): query = args = (block_id,) con = self.db_open(self.impl, self.working_dir) rows = self.db_query_execute(con, query, args, verbose=False) res = None for r in rows: res = r[] con.close() return r...
Get the consensus hash at a given block. Return the consensus hash if we have one for this block. Return None if we don't
369,041
def is_readable(path=None): if os.path.isfile(path) and os.access(path, os.R_OK): return True return False
Test if the supplied filesystem path can be read :param path: A filesystem path :return: True if the path is a file that can be read. Otherwise, False
369,042
def update_link(self): name = repr(self) if not name: return self l = self.__class__._get_links() to_be_changed = list() if name in l: for wal in l[name]: if wal.ref_obj and self is not wal(): to_be_changed.app...
redirects all links to self (the new linked object)
369,043
def _warcprox_opts(self, args): warcprox_opts = warcprox.Options() warcprox_opts.address = warcprox_opts.port = 0 warcprox_opts.cacert = args.cacert warcprox_opts.certs_dir = args.certs_dir warcprox_opts.directory = args.warcs_dir warcp...
Takes args as produced by the argument parser built by _build_arg_parser and builds warcprox arguments object suitable to pass to warcprox.main.init_controller. Copies some arguments, renames some, populates some with defaults appropriate for brozzler-easy, etc.
369,044
def winddir_text(pts): "Convert wind direction from 0..15 to compass point text" global _winddir_text_array if pts is None: return None if not isinstance(pts, int): pts = int(pts + 0.5) % 16 if not _winddir_text_array: _ = pywws.localisation.translation.ugettext _wind...
Convert wind direction from 0..15 to compass point text
369,045
def quotes(self, security, start, end): try: url = % (security.symbol, start, end) try: page = self._request(url) except UfException as ufExcep: if Errors.NETWORK_400_ERROR == ufExcep.getCode: ...
Get historical prices for the given ticker security. Date format is 'YYYYMMDD' Returns a nested list.
369,046
def set_formatter(name, func): if name in (, , ): global af_self af_self = _formatter_self if func is None else func elif name == : global af_class af_class = _formatter_class if func is None else func elif name in (, , ): global af_named af_named = _form...
Replace the formatter function used by the trace decorator to handle formatting a specific kind of argument. There are several kinds of arguments that trace discriminates between: * instance argument - the object bound to an instance method. * class argument - the class object bound to a class method....
369,047
def read_original_textlc(lcpath): HAT-115-0003266.epdlc LOGINFO(.format(lcpath)) N_lines_to_parse_comments = 50 with open(lcpath, ) as file: head = [next(file) for ind in range(N_lines_to_parse_comments)] N_comment_lines = len([l for l in head if l.decode()[0] == ]) if N_comment...
Read .epdlc, and .tfalc light curves and return a corresponding labelled dict (if LC from <2012) or astropy table (if >=2012). Each has different keys that can be accessed via .keys() Input: lcpath: path (string) to light curve data, which is a textfile with HAT LC data. Example: dat = rea...
369,048
def is_type(msg_type, msg): for prop in MessageType.FIELDS[msg_type]["must"]: if msg.get(prop, False) is False: return False for prop in MessageType.FIELDS[msg_type]["prohibit"]: if msg.get(prop, False) is not False: return False ...
Return message's type is or not
369,049
def generate_output_list(self, source, key, val, line=, hr=True, show_name=False, colorize=True): output = generate_output( line=line, short=HR_RDAP[source][key][] if hr else key, name=HR_RDAP[source][key][] if (hr and show_name) else No...
The function for generating CLI output RDAP list results. Args: source (:obj:`str`): The parent key 'network' or 'objects' (required). key (:obj:`str`): The event key 'events' or 'events_actor' (required). val (:obj:`dict`): The event dictiona...
369,050
def _doElegant(self): cmdlist = [, self.sim_script, self.elegant_file, self.sim_path, self.sim_exec] subprocess.call(cmdlist)
perform elegant tracking
369,051
def simxGetLastErrors(clientID, operationMode): errors =[] errorCnt = ct.c_int() errorStrings = ct.POINTER(ct.c_char)() ret = c_GetLastErrors(clientID, ct.byref(errorCnt), ct.byref(errorStrings), operationMode) if ret == 0: s = 0 for i in range(errorCnt.value): a = b...
Please have a look at the function description/documentation in the V-REP user manual
369,052
def appendImport(self, statement): if type(statement) in (list,tuple): self.extras += statement else: self.extras.append(statement)
append additional import statement(s). import_stament -- tuple or list or str
369,053
def _utc_float(self): tai = self.tai leap_dates = self.ts.leap_dates leap_offsets = self.ts.leap_offsets leap_reverse_dates = leap_dates + leap_offsets / DAY_S i = searchsorted(leap_reverse_dates, tai, ) return tai - leap_offsets[i] / DAY_S
Return UTC as a floating point Julian date.
369,054
async def load(self, file_path, locale=None, key: int = 0, pos: int = 1, neg: Optional[ColRanges] = None): if neg is None: neg: ColRanges = [(2, None)] await self.start(file_path, locale...
Start the loading/watching process
369,055
def bump(ctx, verbose=False, pypi=False): cfg = config.load() scm = scm_provider(cfg.project_root, commit=False, ctx=ctx) if not scm.workdir_is_clean(): notify.warning("You have uncommitted changes, will create a time-stamped version!") pep440 = scm.pep440_dev_version(verbose=verbose...
Bump a development version.
369,056
def get_directed_graph_paths(element, arrow_length): edgepaths = element._split_edgepaths edges = edgepaths.split(datatype=, dimensions=edgepaths.kdims) arrows = [] for e in edges: sx, sy = e[0] ex, ey = e[1] rad = np.arctan2(ey-sy, ex-sx) xa0 = ex - np.cos(rad+np.pi...
Computes paths for a directed path which include an arrow to indicate the directionality of each edge.
369,057
def error(self, *args): if _canShortcutLogging(self.logCategory, ERROR): return errorObject(self.logObjectName(), self.logCategory, *self.logFunction(*args))
Log an error. By default this will also raise an exception.
369,058
def on_ready_to_stop(self):
Invoked when the consumer is ready to stop.
369,059
def get_namespace_view(self): from spyder_kernels.utils.nsview import make_remote_view settings = self.namespace_view_settings if settings: ns = self._get_current_namespace() view = repr(make_remote_view(ns, settings, EXCLUDED_NAMES)) return view ...
Return the namespace view This is a dictionary with the following structure {'a': {'color': '#800000', 'size': 1, 'type': 'str', 'view': '1'}} Here: * 'a' is the variable name * 'color' is the color used to show it * 'size' and 'type' are self-evident * and'vie...
369,060
def _make_links_from(self, body): ld = utils.CurieDict(self._core.default_curie, {}) for rel, link in body.get(, {}).items(): if rel != : if isinstance(link, list): ld[rel] = utils.LinkList( (self._navigator_or_thunk(lnk), ...
Creates linked navigators from a HAL response body
369,061
def _set_fabric_priority(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=fabric_priority.fabric_priority, is_container=, presence=False, yang_name="fabric-priority", rest_name="fabric-priority", parent=self, path_helper=self._path_helper, extmethods=s...
Setter method for fabric_priority, mapped from YANG variable /cee_map/remap/fabric_priority (container) If this variable is read-only (config: false) in the source YANG file, then _set_fabric_priority is considered as a private method. Backends looking to populate this variable should do so via calling ...
369,062
def py_run(command_options="", return_std=False, stdout=None, stderr=None): executable = sys.executable if "python" in sys.executable else "python" epylint_part = [executable, "-c", "from pylint import epylint;epylint.Run()"] options = shlex.split(command_options, posix=not sys.platform.star...
Run pylint from python ``command_options`` is a string containing ``pylint`` command line options; ``return_std`` (boolean) indicates return of created standard output and error (see below); ``stdout`` and ``stderr`` are 'file-like' objects in which standard output could be written. Calling ag...
369,063
def _filter_records(self, records, rtype=None, name=None, content=None, identifier=None): if not records: return [] if identifier is not None: LOGGER.debug(, len(records), identifier) records = [record for record in records if record[] == identifier] ...
Filter dns entries based on type, name or content.
369,064
def dump_weights(tf_save_dir, outfile, options): def _get_outname(tf_name): outname = re.sub(, , tf_name) outname = outname.lstrip() outname = re.sub(, , outname) outname = re.sub(, , outname) outname = re.sub(, , outname) outname = re.sub(, , outname) i...
Dump the trained weights from a model to a HDF5 file.
369,065
def save(self, obj): if obj not in self.session: self.session.add(obj) else: obj = self.session.merge(obj) self.session.flush() self.session.refresh(obj) return obj
save an object :param obj: the object :return: the saved object
369,066
def product_requests_button(page, page_perms, is_parent=False): if hasattr(page, ) or isinstance(page, ProductVariant): yield widgets.PageListingButton( , reverse(, kwargs={: page.id}), priority=40 )
Renders a 'requests' button on the page index showing the number of times the product has been requested. Attempts to only show such a button for valid product/variant pages
369,067
def getTransfer(self, iso_packets=0): result = USBTransfer( self.__handle, iso_packets, self.__inflight_add, self.__inflight_remove, ) self.__transfer_set.add(result) return result
Get an USBTransfer instance for asynchronous use. iso_packets: the number of isochronous transfer descriptors to allocate.
369,068
async def parse_tag_results(soup): soup = soup.find_all(, class_=) tags = [] for item in soup: tags.append(item.a.string) return tags
Parse a page of tag or trait results. Same format. :param soup: BS4 Class Object :return: A list of tags, Nothing else really useful there
369,069
def rpc_get_definition(self, filename, source, offset): return self._call_backend("rpc_get_definition", None, filename, get_source(source), offset)
Get the location of the definition for the symbol at the offset.
369,070
def get_all_entities(self, membership_cache=None, entities_by_kind=None, return_models=False, is_active=True): if membership_cache is None: membership_cache = EntityGroup.objects.get_membership_cache([self.id], is_active=is_active) if entities_by_kind is None: ...
Returns a list of all entity ids in this group or optionally returns a queryset for all entity models. In order to reduce queries for multiple group lookups, it is expected that the membership_cache and entities_by_kind are built outside of this method and passed in as arguments. :param membersh...
369,071
def _parse_author(self): r command = LatexCommand( , {: , : True, : }) try: parsed = next(command.parse(self._tex)) except StopIteration: self._logger.warning() self._authors = [] return try: con...
r"""Parse the author from TeX source. Sets the ``_authors`` attribute. Goal is to parse:: \author{ A.~Author, B.~Author, and C.~Author} Into:: ['A. Author', 'B. Author', 'C. Author']
369,072
def save_config_variables(self): command = 0x43 byte_list = [0x3F, 0x3C, 0x3F, 0x3C, 0x43] success = [0xF3, 0x43, 0x3F, 0x3C, 0x3F, 0x3C] resp = [] r = self.cnxn.xfer([command])[0] sleep(10e-3) resp.append(r) for each...
Save the configuration variables in non-volatile memory. This method should be used in conjuction with *write_config_variables*. :rtype: boolean :Example: >>> alpha.save_config_variables() True
369,073
def zip_process(**kwargs): str_localPath = "" str_zipFileName = "" str_action = "zip" str_arcroot = "" for k,v in kwargs.items(): if k == : str_localPath = v if k == : str_action = v if k == : str_zipFileName = v if k...
Process zip operations. :param kwargs: :return:
369,074
def enrich(self, column): if column not in self.data: return self.data self.data["filetype"] = reg = "\.c$|\.h$|\.cc$|\.cpp$|\.cxx$|\.c\+\+$|\.cp$|\.py$|\.js$|\.java$|\.rs$|\.go$" self.data.loc[self.data[column].str.contains(reg), ] = ...
This method adds a new column depending on the extension of the file. :param column: column where the file path is found :type column: string :return: returns the original dataframe with a new column named as 'filetype' that contains information about its extension ...
369,075
def find_transport_reactions(model): transport_reactions = [] transport_rxn_candidates = set(model.reactions) - set(model.boundary) \ - set(find_biomass_reaction(model)) transport_rxn_candidates = set( [rxn for rxn in transport_rxn_candidates if len(rxn.compartments) >= 2] ) ...
Return a list of all transport reactions. Parameters ---------- model : cobra.Model The metabolic model under investigation. Notes ----- A transport reaction is defined as follows: 1. It contains metabolites from at least 2 compartments and 2. at least 1 metabolite undergoes no...
369,076
def findentry(self, item): if not isinstance(item, str): raise TypeError( % type(item)) for entry in self: if item.lower() == entry.lower(): return entry return None
A caseless way of checking if an item is in the list or not. It returns None or the entry.
369,077
def new_thing(self, name, **stats): return self.character.new_thing( name, self.name, **stats )
Create a new thing, located here, and return it.
369,078
def get(block_id): _url = get_root_url() try: block = DB.get_block_details([block_id]).__next__() response = block response[] = { : .format(request.url), : .format(_url), : .format(_url) } return block except IndexError as err...
Processing block detail resource.
369,079
def length(self, t0=0, t1=1, error=None, min_depth=None): return abs(self.end - self.start)*(t1-t0)
returns the length of the line segment between t0 and t1.
369,080
def from_layer(cls, font, layerName=None, copy=False, skipExportGlyphs=None): if layerName is not None: layer = font.layers[layerName] else: layer = font.layers.defaultLayer if copy: self = _copyLayer(layer, obj_type=cls) self.lib = deepc...
Return a mapping of glyph names to glyph objects from `font`.
369,081
def authenticate(self, token_value): try: backend_path, user_id = token_value.split(, 1) except (ValueError, AttributeError): return False backend = auth.load_backend(backend_path) return bool(backend.get_user(user_id))
Check that the password is valid. This allows for revoking of a user's preview rights by changing the valid passwords.
369,082
def dataset_archive(dataset, signature, data_home=None, ext=".zip"): data_home = get_data_home(data_home) path = os.path.join(data_home, dataset+ext) if os.path.exists(path) and os.path.isfile(path): return sha256sum(path) == signature return False
Checks to see if the dataset archive file exists in the data home directory, found with ``get_data_home``. By specifying the signature, this function also checks to see if the archive is the latest version by comparing the sha256sum of the local archive with the specified signature. Parameters ----...
369,083
def register_actions(self, shortcut_manager): shortcut_manager.add_callback_for_action(, self.rename_selected_state) super(StatesEditorController, self).register_actions(shortcut_manager)
Register callback methods for triggered actions :param rafcon.gui.shortcut_manager.ShortcutManager shortcut_manager: Shortcut Manager Object holding mappings between shortcuts and actions.
369,084
def _symlink_local_src(self, gopath, go_local_src, required_links): source_list = [os.path.join(get_buildroot(), src) for src in go_local_src.sources_relative_to_buildroot()] rel_list = go_local_src.sources_relative_to_target_base() source_iter = zip(source_list, rel_list) return...
Creates symlinks from the given gopath to the source files of the given local package. Also duplicates directory structure leading to source files of package within gopath, in order to provide isolation to the package. Adds the symlinks to the source files to required_links.
369,085
def gf_poly_mul_simple(p, q): return r
Multiply two polynomials, inside Galois Field
369,086
def kwargs(self): return {k: v for k, v in self._kwargs.items() if k not in self._INTERNAL_FIELDS}
Returns a dict of the kwargs for this Struct which were not interpreted by the baseclass. This excludes fields like `extends`, `merges`, and `abstract`, which are consumed by SerializableFactory.create and Validatable.validate.
369,087
def ToTsvExcel(self, columns_order=None, order_by=()): csv_result = self.ToCsv(columns_order, order_by, separator="\t") if not isinstance(csv_result, six.text_type): csv_result = csv_result.decode("utf-8") return csv_result.encode("UTF-16LE")
Returns a file in tab-separated-format readable by MS Excel. Returns a file in UTF-16 little endian encoding, with tabs separating the values. Args: columns_order: Delegated to ToCsv. order_by: Delegated to ToCsv. Returns: A tab-separated little endian UTF16 file representing the ta...
369,088
def process_notes(notes, ref_data): ref_keys = ref_data.keys() found_refs = set() for k in ref_keys: if k in notes: found_refs.add(k) reference_sec = reference_sec += reference_sec += reference_sec += reference_sec += if len(found_refs) == ...
Add reference information to the bottom of a notes file `:ref:` tags are removed and the actual reference data is appended
369,089
def escape(s): if hasattr(s, ): return s.__html__() if isinstance(s, six.binary_type): s = six.text_type(str(s), ) elif isinstance(s, six.text_type): s = s else: s = str(s) return (s .replace(, ) .replace(, ) .replace(, ) .replace...
Convert the characters &, <, >, ' and " in string s to HTML-safe sequences. Use this if you need to display text that might contain such characters in HTML. Marks return value as markup string.
369,090
def from_object(obj): return obj if isinstance(obj, Contact) \ else Contact(cast.string_to_enum(obj.name, Contact.ContactName), obj.value, is_primary=obj.is_primary and cast.string_to_boolean(obj.is_primary, strict=True), ...
Convert an object representing a contact information to an instance `Contact`. @param obj: an object containg the following attributes: * `name`: an item of the enumeration `ContactName` representing the type of this contact information. * `value`: value of this...
369,091
def virtual_machines_list_available_sizes(name, resource_group, **kwargs): result = {} compconn = __utils__[](, **kwargs) try: sizes = __utils__[]( compconn.virtual_machines.list_available_sizes( resource_group_name=resource_group, vm_name=name ...
.. versionadded:: 2019.2.0 Lists all available virtual machine sizes to which the specified virtual machine can be resized. :param name: The name of the virtual machine. :param resource_group: The resource group name assigned to the virtual machine. CLI Example: .. code-block:: bash...
369,092
def _create_ucsm_host_to_service_profile_mapping(self): ucsm_ips = list(CONF.ml2_cisco_ucsm.ucsms) for ucsm_ip in ucsm_ips: with self.ucsm_connect_disconnect(ucsm_ip) as handle: try: sp_list_temp = handle.ConfigResolveClass(, None, ...
Reads list of Service profiles and finds associated Server.
369,093
def _update_valid_moves(self): left_end = self.board.left_end() right_end = self.board.right_end() moves = [] for d in self.hands[self.turn]: if left_end in d: moves.append((d, True)) if right_end in d and left_e...
Updates self.valid_moves according to the latest game state. Assumes that the board and all hands are non-empty.
369,094
def upload_files(selected_file, selected_host, only_link, file_name): try: answer = requests.post( url=selected_host[0]+"upload.php", files={:selected_file}) file_name_1 = re.findall(r, \ answer.text.replace("\\", ""))[0][2] if only_link: ...
Uploads selected file to the host, thanks to the fact that every pomf.se based site has pretty much the same architecture.
369,095
async def read_frame(self) -> DataFrame: if self._data_frames.qsize() == 0 and self.closed: raise StreamConsumedError(self.id) frame = await self._data_frames.get() self._data_frames.task_done() if frame is None: raise StreamConsumedError(self.id) ...
Read a single frame from the local buffer. If no frames are available but the stream is still open, waits until more frames arrive. Otherwise, raises StreamConsumedError. When a stream is closed, a single `None` is added to the data frame Queue to wake up any waiting `read_frame` corou...
369,096
def canGoBack(self): try: backId = self._navigation.index(self.currentId())-1 if backId >= 0: self._navigation[backId] else: return False except StandardError: return False else: return True
Returns whether or not this wizard can move forward. :return <bool>
369,097
def upsert(self, *fields): if not self._id: return self.insert() if self.count({: self._id}) == 0: self.insert() else: self.update(*fields)
Update or Insert this document depending on whether it exists or not. The presense of an `_id` value in the document is used to determine if the document exists. NOTE: This method is not the same as specifying the `upsert` flag when calling MongoDB. When called for a document with an `_...
369,098
def load_config(path=None, defaults=None): if defaults is None: defaults = DEFAULT_FILES config = configparser.SafeConfigParser(allow_no_value=True) if defaults: config.read(defaults) if path: with open(path) as fh: config.readfp(fh) return config
Loads and parses an INI style configuration file using Python's built-in ConfigParser module. If path is specified, load it. If ``defaults`` (a list of strings) is given, try to load each entry as a file, without throwing any error if the operation fails. If ``defaults`` is not given, the followi...
369,099
def dms2dd(degrees, minutes, seconds): dd = float(degrees) + old_div(float(minutes), 60) + \ old_div(float(seconds), (60 * 60)) return dd
Convert latitude/longitude of a location that is in degrees, minutes, seconds to decimal degrees Parameters ---------- degrees : degrees of latitude/longitude minutes : minutes of latitude/longitude seconds : seconds of latitude/longitude Returns ------- degrees : decimal degrees of lo...