Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
11,300
def broadcast(*sinks_): @push def bc(): sinks = [s() for s in sinks_] while True: msg = yield for s in sinks: s.send(msg) return bc
The |broadcast| decorator creates a |push| object that receives a message by ``yield`` and then sends this message on to all the given sinks. .. |broadcast| replace:: :py:func:`broadcast`
11,301
def _sb_decoder(self): bloc = self.telnet_sb_buffer if len(bloc) > 2: if bloc[0] == TTYPE and bloc[1] == IS: self.terminal_type = bloc[2:] if bloc[0] == NAWS: if len(bloc) != 5: print "Bad le...
Figures out what to do with a received sub-negotiation block.
11,302
def set_calibrated_weights(self): period = self.period survey_scenario = self.survey_scenario assert survey_scenario.simulation is not None for simulation in [survey_scenario.simulation, survey_scenario.baseline_simulation]: if simulation is None: con...
Modify the weights to use the calibrated weights
11,303
async def states(self, country: str) -> list: data = await self._request( , , params={: country}) return [d[] for d in data[]]
Return a list of supported states in a country.
11,304
def call_listen(self, chunks, running): listeners = [] crefs = {} for chunk in chunks: crefs[(chunk[], chunk[], chunk[])] = chunk if in chunk: listeners.append({(chunk[], chunk[], chunk[]): chunk[]}) if in chunk: for ...
Find all of the listen routines and call the associated mod_watch runs
11,305
def form_valid(self, post_form, attachment_formset, **kwargs): save_attachment_formset = attachment_formset is not None \ and not self.preview if self.preview: return self.render_to_response( self.get_context_data( preview=True, post_...
Processes valid forms. Called if all forms are valid. Creates a Post instance along with associated attachments if required and then redirects to a success page.
11,306
def is_action_available(self, action): temp_state = np.rot90(self._state, action) return self._is_action_available_left(temp_state)
Determines whether action is available. That is, executing it would change the state.
11,307
def _AddStopTimeObjectUnordered(self, stoptime, schedule): stop_time_class = self.GetGtfsFactory().StopTime cursor = schedule._connection.cursor() insert_query = "INSERT INTO stop_times (%s) VALUES (%s);" % ( .join(stop_time_class._SQL_FIELD_NAMES), .join([] * len(stop_time_class._SQL_FIE...
Add StopTime object to this trip. The trip isn't checked for duplicate sequence numbers so it must be validated later.
11,308
def ls(args): assert args.path, "Not finded MAKESITE HOME." print_header("Installed sites:") for site in gen_sites(args.path): LOGGER.debug(site.get_info()) return True
List sites ---------- Show list of installed sites. :: usage: makesite ls [-h] [-v] [-p PATH] Show list of installed sites. optional arguments: -p PATH, --path PATH path to makesite sites instalation dir. you can set it in $makesite_home ...
11,309
def declare_queue(self, queue_name=, passive=False, durable=False, exclusive=False, auto_delete=False, arguments=None): result = self._channel.queue_declare( queue=queue_name, passive=passive, durable=durable, exclusive=exclusive, ...
ε£°ζ˜ŽδΈ€δΈͺι˜Ÿεˆ— :param queue_name: ι˜Ÿεˆ—ε :param passive: :param durable: :param exclusive: :param auto_delete: :param arguments: :return: pika ζ‘†ζžΆη”Ÿζˆηš„ιšζœΊε›žθ°ƒι˜Ÿεˆ—ε
11,310
def _expand_slice(self, indices): keys = list(self.data.keys()) expanded = [] for idx, ind in enumerate(indices): if isinstance(ind, slice) and ind.step is not None: dim_ind = slice(ind.start, ind.stop) if dim_ind == slice(None): ...
Expands slices containing steps into a list.
11,311
def get_grid_points_by_rotations(address_orig, reciprocal_rotations, mesh, is_shift=None, is_dense=False): _set_no_error() if is_shift is None: _is_shift = np.zeros(...
Returns grid points obtained after rotating input grid address Parameters ---------- address_orig : array_like Grid point address to be rotated. dtype='intc', shape=(3,) reciprocal_rotations : array_like Rotation matrices {R} with respect to reciprocal basis vectors. Def...
11,312
def add_task(self, task_id, backend, category, backend_args, archive_args=None, sched_args=None): try: archiving_cfg = self.__parse_archive_args(archive_args) scheduling_cfg = self.__parse_schedule_args(sched_args) self.__validate_args(task_id, backe...
Add and schedule a task. :param task_id: id of the task :param backend: name of the backend :param category: category of the items to fecth :param backend_args: args needed to initialize the backend :param archive_args: args needed to initialize the archive :param sched_...
11,313
def kmodels(wordlen: int, k: int, input=None, output=None): assert 0 <= k < 2**wordlen if output is None: output = _fresh() if input is None: input = _fresh() input_names = named_indexes(wordlen, input) atoms = map(aiger.atom, input_names) active = False expr = aiger...
Return a circuit taking a wordlen bitvector where only k valuations return True. Uses encoding from [1]. Note that this is equivalent to (~x < k). - TODO: Add automated simplification so that the circuits are equiv. [1]: Chakraborty, Supratik, et al. "From Weighted to Unweighted Model ...
11,314
def arguments_to_lists(function): def l_function(*args, **kwargs): l_args = [_to_list(arg) for arg in args] l_kwargs = {} for key, value in kwargs.items(): l_kwargs[key] = _to_list(value) return function(*l_args, **l_kwargs) return l_function
Decorator for a function that converts all arguments to lists. :param function: target function :return: target function with only lists as parameters
11,315
def find_by_id(self, story, params={}, **options): path = "/stories/%s" % (story) return self.client.get(path, params, **options)
Returns the full record for a single story. Parameters ---------- story : {Id} Globally unique identifier for the story. [params] : {Object} Parameters for the request
11,316
def delete_doc_by_id(self, collection, doc_id, **kwargs): if in doc_id: doc_id = .format(doc_id) temp = {"delete": {"query": .format(doc_id)}} resp, con_inf = self.transport.send_request(method=, endpoint=, ...
:param str collection: The name of the collection for the request :param str id: ID of the document to be deleted. Can specify '*' to delete everything. Deletes items from Solr based on the ID. :: >>> solr.delete_doc_by_id('SolrClient_unittest','changeme')
11,317
def bel_process_belrdf(): if request.method == : return {} response = request.body.read().decode() body = json.loads(response) belrdf = body.get() bp = bel.process_belrdf(belrdf) return _stmts_from_proc(bp)
Process BEL RDF and return INDRA Statements.
11,318
def version(): click.echo( % __version__) click.echo( % CUR_API_VERSION) try: r = client.get() except RequestException as ex: raise exc.TowerCLIError( % six.text_type(ex)) config = r.json() license = config.get(, {}).get...
Display full version information.
11,319
def _set_link_local_route_oif_type(self, v, load=False): parent = getattr(self, "_parent", None) if parent is not None and load is False: raise AttributeError("Cannot set keys directly when" + " within an instantiated list") if hasattr(v, "_utype"): v = v._utyp...
Setter method for link_local_route_oif_type, mapped from YANG variable /rbridge_id/vrf/address_family/ipv6/unicast/ipv6/route/link_local_static_route_nh/link_local_route_oif_type (enumeration) If this variable is read-only (config: false) in the source YANG file, then _set_link_local_route_oif_type is considere...
11,320
def number_to_dp(number: Optional[float], dp: int, default: Optional[str] = "", en_dash_for_minus: bool = True) -> str: if number is None: return default if number == float("inf"): return u"∞" if number == float("-inf"): s = u"-...
Format number to ``dp`` decimal places, optionally using a UTF-8 en dash for minus signs.
11,321
def refresh_information(self, accept=MEDIA_TYPE_TAXII_V20): response = self.__raw = self._conn.get(self.url, headers={"Accept": accept}) self._populate_fields(**response) self._loaded_information = True
Update the properties of this API Root. This invokes the ``Get API Root Information`` endpoint.
11,322
def _wr_ver_n_key(self, fout_txt, verbose): with open(fout_txt, ) as prt: self._prt_ver_n_key(prt, verbose) print(.format(TXT=fout_txt))
Write GO DAG version and key indicating presence of GO ID in a list.
11,323
def pad_chunk_columns(chunk): columns = set() for record in chunk: columns.update(record.keys()) for record in chunk: for column in columns: record.setdefault(column, None) return chunk
Given a set of items to be inserted, make sure they all have the same columns by padding columns with None if they are missing.
11,324
def inheritsFrom(self, target_name): for t in self.hierarchy: if t and t.getName() == target_name or target_name in t.description.get(, {}): return True return False
Return true if this target inherits from the named target (directly or indirectly. Also returns true if this target is the named target. Otherwise return false.
11,325
def _to_dict(self): _dict = {} if hasattr(self, ) and self.results is not None: _dict[] = [x._to_dict() for x in self.results] if hasattr(self, ) and self.count is not None: _dict[] = self.count return _dict
Return a json dictionary representing this model.
11,326
def IsAllSpent(self): for item in self.Items: if item == CoinState.Confirmed: return False return True
Flag indicating if all balance is spend. Returns: bool:
11,327
def _parse_kexgss_continue(self, m): if not self.transport.server_mode: srv_token = m.get_string() m = Message() m.add_byte(c_MSG_KEXGSS_CONTINUE) m.add_string( self.kexgss.ssh_init_sec_context( target=self.gss_host, re...
Parse the SSH2_MSG_KEXGSS_CONTINUE message. :param `.Message` m: The content of the SSH2_MSG_KEXGSS_CONTINUE message
11,328
def db(self): if self._db is None: if self.tcex.default_args.tc_playbook_db_type == : from .tcex_redis import TcExRedis self._db = TcExRedis( self.tcex.default_args.tc_playbook_db_path, self.tcex.default_args.tc_playbo...
Return the correct KV store for this execution.
11,329
def group_membership_show(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/group_memberships api_path = "/api/v2/group_memberships/{id}.json" api_path = api_path.format(id=id) return self.call(api_path, **kwargs)
https://developer.zendesk.com/rest_api/docs/core/group_memberships#show-membership
11,330
def relabel(self, column_label, new_label): if isinstance(column_label, numbers.Integral): column_label = self._as_label(column_label) if isinstance(column_label, str) and isinstance(new_label, str): column_label, new_label = [column_label], [new_label] if len(co...
Changes the label(s) of column(s) specified by ``column_label`` to labels in ``new_label``. Args: ``column_label`` -- (single str or array of str) The label(s) of columns to be changed to ``new_label``. ``new_label`` -- (single str or array of str): The label na...
11,331
def get_events(self): header = BASE_HEADERS.copy() header[] = self.__cookie request = requests.post(BASE_URL + , headers=header, timeout=10) if request.status_code != 200: self.__logged_in = False ...
Return a set of events. Which have been occured since the last call of this method. This method should be called regulary to get all occuring Events. There are three different Event types/classes which can be returned: - DeviceStateChangedEvent, if any device changed it's stat...
11,332
def confirm_reservation(self, username, domain, password, email=None): self.set_password(username=username, domain=domain, password=password) if email is not None: self.set_email(username=username, domain=domain, email=email)
Confirm a reservation for a username. The default implementation just calls :py:func:`~xmpp_backends.base.XmppBackendBase.set_password` and optionally :py:func:`~xmpp_backends.base.XmppBackendBase.set_email`.
11,333
def _dict_to_object(desired_type: Type[T], contents_dict: Dict[str, Any], logger: Logger, options: Dict[str, Dict[str, Any]], conversion_finder: ConversionFinder = None, is_dict_of_dicts: bool = False) -> T: constructor_args_types_and_opt = get_constructor_attribute...
Utility method to create an object from a dictionary of constructor arguments. Constructor arguments that dont have the correct type are intelligently converted if possible :param desired_type: :param contents_dict: :param logger: :param options: :param conversion_finder: :param is_dict_of_...
11,334
def set_trace(context): try: import ipdb as pdb except ImportError: import pdb print("For best results, pip install ipdb.") print("Variables that are available in the current context:") render = lambda s: template.Template(s).render(context) availables = get_variables(co...
Start a pdb set_trace inside of the template with the context available as 'context'. Uses ipdb if available.
11,335
def fix_version(context): if not prerequisites_ok(): return lines = codecs.open(, , ).readlines() for index, line in enumerate(lines): if line.startswith(): new_line = % context[] lines[index] = new_line time.sleep(1) codecs.open(, , ).writelines(lines)
Fix the version in metadata.txt Relevant context dict item for both prerelease and postrelease: ``new_version``.
11,336
def _remove(self, obj): for idx, item in enumerate(self._queue): if item == obj: del self._queue[idx] break
Python 2.4 compatibility.
11,337
def conditionally_create_profile(role_name, service_type): if service_type not in INSTANCE_PROFILE_SERVICE_TYPES: print_if_verbose("service type: {} not eligible for instance profile".format(service_type)) return instance_profile = get_instance_profile(role_name) if not instance_profile: print(...
Check that there is a 1:1 correspondence with an InstanceProfile having the same name as the role, and that the role is contained in it. Create InstanceProfile and attach to role if needed.
11,338
def build_dated_queryset(self): qs = self.get_dated_queryset() years = self.get_date_list(qs) [self.build_year(dt) for dt in years]
Build pages for all years in the queryset.
11,339
def init_logger(self): self.logger.setLevel(logging.DEBUG) self.logger.propagate = False if self.min_log_level_to_print: level = self.min_log_level_to_print handler_class = logging.StreamHandler self._create_handler(handler_class, l...
Create configuration for the root logger.
11,340
def basicConfig(level=logging.WARNING, transient_level=logging.NOTSET): fmt = "%(asctime)s [%(levelname)s] [%(name)s:%(lineno)d] %(message)s" logging.root.setLevel(transient_level) hand = TransientStreamHandler(level=level) hand.setFormatter(logging.Formatter(fmt)) logging.root.addHandler(han...
Shortcut for setting up transient logging I am a replica of ``logging.basicConfig`` which installs a transient logging handler to stderr.
11,341
def create(self, user_id, name, department=None, position=None, mobile=None, gender=0, tel=None, email=None, weixin_id=None, extattr=None): user_data = optionaldict() user_data[] = user_id user_data[] = name user_data[] = gender user_data[] ...
εˆ›ε»Ίζˆε‘˜ https://work.weixin.qq.com/api/doc#90000/90135/90195
11,342
def get_api_versions(call=None, kwargs=None): if kwargs is None: kwargs = {} if not in kwargs: raise SaltCloudSystemExit( ) if not in kwargs: raise SaltCloudSystemExit( ) api_versions = [] try: resconn = get_conn(...
Get a resource type api versions
11,343
def get_transfer_role(chain_state: ChainState, secrethash: SecretHash) -> Optional[str]: task = chain_state.payment_mapping.secrethashes_to_task.get(secrethash) if not task: return None return role_from_transfer_task(task)
Returns 'initiator', 'mediator' or 'target' to signify the role the node has in a transfer. If a transfer task is not found for the secrethash then the function returns None
11,344
def compile_highstate(self): err = [] top = self.get_top() err += self.verify_tops(top) matches = self.top_matches(top) high, errors = self.render_highstate(matches) err += errors if err: return err return high
Return just the highstate or the errors
11,345
def eeg_microstates_plot(method, path="", extension=".png", show_sensors_position=False, show_sensors_name=False, plot=True, save=True, dpi=150, contours=0, colorbar=False, separate=False): figures = [] names = [] try: microstates = method["microstates_good_fit"] except KeyError:...
Plot the microstates.
11,346
def analytic_file(self, new_status, old_status=None): if not old_status: old_status = self.domain_status if "file_to_test" in PyFunceble.INTERN and PyFunceble.INTERN["file_to_test"]: output = ( self....
Generate :code:`Analytic/*` files based on the given old and new statuses. :param new_status: The new status of the domain. :type new_status: str :param old_status: The old status of the domain. :type old_status: str
11,347
def com_daltonmaag_check_ufolint(font): import subprocess ufolint_cmd = ["ufolint", font] try: subprocess.check_output(ufolint_cmd, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as e: yield FAIL, ("ufolint failed the UFO source. Output follows :" "\n\n{}\n").format(...
Run ufolint on UFO source directory.
11,348
def calculate_query_times(**kwargs): return { "total_time_avg": round(numpy.mean(kwargs["total_times"]), 1), "total_time_min": round(numpy.min(kwargs["total_times"]), 1), "total_time_max": round(numpy.max(kwargs["total_times"]), 1), "total_time_85": round(numpy.percentile(kwargs...
Calculates aggregate query times from all iteration times Kwargs: total_times(list): List of total time calculations execution_times(list): List of execution_time calculations results_iter_times(list): List of results_iter_time calculations connect_times(list): List of connect_tim...
11,349
def intersection_update(self, other): if not isinstance(other, Set): raise ValueError() if self is other: return for item in list(self.items): if item not in other.items: self.items.remove(item)
Update the set, removing any elements from other which are not in both sets. @param other: the collection of items with which to update the set @type other: Set object
11,350
def parents( self, node ): if in node: index = node[]() parents = list(meliaeloader.children( node, index, )) return parents return []
Retrieve/calculate the set of parents for the given node
11,351
def init_db(drop_all=False, bind=engine): try: if drop_all: Base.metadata.drop_all(bind=bind) Base.metadata.create_all(bind=bind) except OperationalError as err: msg = if msg in err.message: sys.stderr.write(db_user_warning) raise return...
Initialize the database, optionally dropping existing tables.
11,352
def choose_database_name(metadata, config): if config.database_name is not None: return config.database_name if metadata.testing: return f"{metadata.name}_test_db" return f"{metadata.name}_db"
Choose the database name to use. As a default, databases should be named after the service that uses them. In addition, database names should be different between unit testing and runtime so that there is no chance of a unit test dropping a real database by accident.
11,353
def hashable_to_uuid(hashable_): bytes_ = _ensure_hashable_bytes(hashable_) try: bytes_sha1 = hashlib.sha1(bytes_) except TypeError: print( % (hashable_,)) print( % (bytes_,)) raise hashbytes_20 = bytes_sha1.digest() hashbytes_16 = hashbytes_20[0:16] uui...
TODO: ensure that python2 and python3 agree on hashes of the same information Args: hashable_ (hashable): hashables are bytes-like objects An object that supports the Buffer Protocol, like bytes, bytearray or memoryview. Bytes-like objects can be used for various operations ...
11,354
def number_observer(t=None, targets=None): from ecell4_base.core import NumberObserver, FixedIntervalNumberObserver, TimingNumberObserver if t is None: return NumberObserver(targets) elif isinstance(t, numbers.Number): return FixedIntervalNumberObserver(t, targets) elif hasattr(t, ...
Return a number observer. If t is None, return NumberObserver. If t is a number, return FixedIntervalNumberObserver. If t is an iterable (a list of numbers), return TimingNumberObserver. Parameters ---------- t : float, list or tuple, optional. default None A timing of the observation. See ...
11,355
def save(self, *args, **kwargs): self.uid = .format(self.slug) super(ElectionType, self).save(*args, **kwargs)
**uid**: :code:`electiontype:{name}`
11,356
def gen_salt_and_hash(val=None): if not val: val = random_str() str_salt = random_str() str_hash = hashlib.sha256(val + str_salt).hexdigest() return str_salt, str_hash
Generate a salt & hash If no string is provided then a random string will be used to hash & referred to as `val`. The salt will always be randomly generated & the hash will be a sha256 hex value of the `val` & the salt as a concatenated string. It follows the guidance here: crackstation.n...
11,357
def rectwv_coeff_add_longslit_model(rectwv_coeff, geometry, debugplot=0): logger = logging.getLogger(__name__) grism_name = rectwv_coeff.tags[] logger.info( + grism_name) filter_name = rectwv_coeff.tags[] logger.info( + filter_name) list_valid_islitlets = list(range(1, EMIR_NBA...
Compute longslit_model coefficients for RectWaveCoeff object. Parameters ---------- rectwv_coeff : RectWaveCoeff instance Rectification and wavelength calibration coefficients for a particular CSU configuration corresponding to a longslit observation. geometry : TBD debugplo...
11,358
def mark_quality(self, start_time, length, qual_name): y_pos = BARS[][] height = 10 old_score = self.scene.itemAt(start_time + length / 2, y_pos + height - 1, self.transform()) if old...
Mark signal quality, only add the new ones. Parameters ---------- start_time : int start time in s of the epoch being scored. length : int duration in s of the epoch being scored. qual_name : str one of the stages defined in global stages.
11,359
def to_representation(self, instance): request = self.context[] enterprise_customer = instance.enterprise_customer representation = super(EnterpriseCustomerCatalogDetailSerializer, self).to_representation(instance) paginated_content = instance.get_paginated_content(re...
Serialize the EnterpriseCustomerCatalog object. Arguments: instance (EnterpriseCustomerCatalog): The EnterpriseCustomerCatalog to serialize. Returns: dict: The EnterpriseCustomerCatalog converted to a dict.
11,360
def base_taskname(taskname, packagename=None): if not isinstance(taskname, str): return taskname indx = taskname.rfind() if indx >= 0: base_taskname = taskname[(indx+1):] pkg_name = taskname[:indx] else: base_taskname = taskname pkg_name = a...
Extract the base name of the task. Many tasks in the `drizzlepac` have "compound" names such as 'drizzlepac.sky'. This function will search for the presence of a dot in the input `taskname` and if found, it will return the string to the right of the right-most dot. If a dot is not found, it will return...
11,361
def __get_query_filters(cls, filters={}, inverse=False): query_filters = [] for name in filters: if name[0] == and not inverse: continue if name[0] != and inverse: continue field_name = name...
Convert a dict with the filters to be applied ({"name1":"value1", "name2":"value2"}) to a list of query objects which can be used together in a query using boolean combination logic. :param filters: dict with the filters to be applied :param inverse: if True include all the inverse filt...
11,362
def blit(self, surface, pos=(0, 0)): for x in range(surface.width): for y in range(surface.height): point = (x + pos[0], y + pos[1]) if self.point_on_screen(point): self.matrix[point[0]][point[1]] = surface.matrix[x][y]
Blits a surface on the screen at pos :param surface: Surface to blit :param pos: Top left corner to start blitting :type surface: Surface :type pos: tuple
11,363
def disable_metrics_collection(self, as_group, metrics=None): params = {: as_group} if metrics: self.build_list_params(params, metrics, ) return self.get_status(, params)
Disables monitoring of group metrics for the Auto Scaling group specified in AutoScalingGroupName. You can specify the list of affected metrics with the Metrics parameter.
11,364
def router_main(self): while True: gotpkt = True try: timestamp,dev,pkt = self.net.recv_packet(timeout=1.0) except NoPackets: log_debug("No packets available in recv_packet") gotpkt = False except Shutdo...
Main method for router; we stay in a loop in this method, receiving packets until the end of time.
11,365
def _validate_pending_children(self): for n in self.pending_children: assert n.state in (NODE_PENDING, NODE_EXECUTING), \ (str(n), StateString[n.state]) assert len(n.waiting_parents) != 0, (str(n), len(n.waiting_parents)) for p in n.waiting_parents: ...
Validate the content of the pending_children set. Assert if an internal error is found. This function is used strictly for debugging the taskmaster by checking that no invariants are violated. It is not used in normal operation. The pending_children set is used to detect cycles...
11,366
def import_locations(self, cells_file): self._cells_file = cells_file field_names = (, , , , , , , , , , ) parse_date = lambda s: datetime.datetime.strptime(s, ) field_parsers = (int, float, float, ...
Parse OpenCellID.org data files. ``import_locations()`` returns a dictionary with keys containing the OpenCellID.org_ database identifier, and values consisting of a ``Cell`` objects. It expects cell files in the following format:: 22747,52.0438995361328,-0.2246370017529,2...
11,367
def doesnt_have(self, relation, boolean=, extra=None): return self.has(relation, , 1, boolean, extra)
Add a relationship count to the query. :param relation: The relation to count :type relation: str :param boolean: The boolean value :type boolean: str :param extra: The extra query :type extra: Builder or callable :rtype: Builder
11,368
def entity(self, entity_id, get_files=False, channel=None, include_stats=True, includes=None): s id either as a reference or a string @param get_files Whether to fetch the files for the charm or not. @param channel Optional channel name. @param include_stats Optionally dis...
Get the default data for any entity (e.g. bundle or charm). @param entity_id The entity's id either as a reference or a string @param get_files Whether to fetch the files for the charm or not. @param channel Optional channel name. @param include_stats Optionally disable stats collection...
11,369
def to_even_columns(data, headers=None): result = col_width = max(len(word) for row in data for word in row) + 2 if headers: header_width = max(len(word) for row in headers for word in row) + 2 if header_width > col_width: col_width = header_width result += "".jo...
Nicely format the 2-dimensional list into evenly spaced columns
11,370
def _argument_adapter(callback): def wrapper(*args, **kwargs): if kwargs or len(args) > 1: callback(Arguments(args, kwargs)) elif args: callback(args[0]) else: callback(None) return wrapper
Returns a function that when invoked runs ``callback`` with one arg. If the function returned by this function is called with exactly one argument, that argument is passed to ``callback``. Otherwise the args tuple and kwargs dict are wrapped in an `Arguments` object.
11,371
def get_next_step(self): if self.parent.step_kw_purpose.\ selected_purpose() == layer_purpose_hazard: new_step = self.parent.step_kw_hazard_category else: if is_raster_layer(self.parent.layer): new_step = self.parent.step_kw_band_selector ...
Find the proper step when user clicks the Next button. :returns: The step to be switched to :rtype: WizardStep instance or None
11,372
def get_two_parameters(self, regex_exp, parameters): Rx, Ry, other = self.get_parameters(regex_exp, parameters) if other is not None and other.strip(): raise iarm.exceptions.ParsingError("Extra arguments found: {}".format(other)) if Rx and Ry: return Rx.upper(), ...
Get two parameters from a given regex expression Raise an exception if more than two were found :param regex_exp: :param parameters: :return:
11,373
def _unescape(self, msg): if isinstance(msg, (int, float, long)): return msg unescaped = i = 0 while i < len(msg): unescaped += msg[i] if msg[i] == : i+=1 i+=1 return unescaped
Removes double quotes that were used to escape double quotes. Expects a string without its delimiting quotes, or a number. Returns a new unescaped string.
11,374
def _ensure_unicode_string(string): if not isinstance(string, six.text_type): string = string.decode() return string
Returns a unicode string for string. :param string: The input string. :type string: `basestring` :returns: A unicode string. :rtype: `unicode`
11,375
def from_secrets_file(client_secrets, storage=None, flags=None, storage_path=None, api_version="v3", readonly=False, http_client=None, ga_hook=None): scope = GOOGLE_API_SCOPE_READONLY if readonly else GOOGLE_API_SCOPE flow = flow_from_clientsecrets(client_secrets...
Create a client for a web or installed application. Create a client with a client secrets file. Args: client_secrets: str, path to the client secrets file (downloadable from Google API Console) storage: oauth2client.client.Storage, a Storage implementation to store ...
11,376
def shutdown(self): result = _lib.SSL_shutdown(self._ssl) if result < 0: self._raise_ssl_error(self._ssl, result) elif result > 0: return True else: return False
Send the shutdown message to the Connection. :return: True if the shutdown completed successfully (i.e. both sides have sent closure alerts), False otherwise (in which case you call :meth:`recv` or :meth:`send` when the connection becomes readable/writeable).
11,377
def _evalTimeStr(self, datetimeString, sourceTime): s = datetimeString.strip() sourceTime = self._evalDT(datetimeString, sourceTime) if s in self.ptc.re_values[]: self.currentContext.updateAccuracy(pdtContext.ACU_NOW) else: sTim...
Evaluate text passed by L{_partialParseTimeStr()}
11,378
def diffusionAddCountsFromSource(grph, source, target, nodeType = , extraType = None, diffusionLabel = , extraKeys = None, countsDict = None, extraMapping = None): progArgs = (0, "Starting to add counts to graph") if metaknowledge.VERBOSE_MODE: progKwargs = { : False} else: progKwargs =...
Does a diffusion using [diffusionCount()](#metaknowledge.diffusion.diffusionCount) and updates _grph_ with it, using the nodes in the graph as keys in the diffusion, i.e. the source. The name of the attribute the counts are added to is given by _diffusionLabel_. If the graph is not composed of citations from the source...
11,379
def get_library(self, username, status=None): r = self._query_( % username, , params={: status}) results = [LibraryEntry(item) for item in r.json()] return results
Fetches a users library. :param str username: The user to get the library from. :param str status: only return the items with the supplied status. Can be one of `currently-watching`, `plan-to-watch`, `completed`, `on-hold` or `dropped`. :returns: List of Library objects...
11,380
def _let_to_py_ast(ctx: GeneratorContext, node: Let) -> GeneratedPyAST: assert node.op == NodeOp.LET with ctx.new_symbol_table("let"): let_body_ast: List[ast.AST] = [] for binding in node.bindings: init_node = binding.init assert init_node is not None in...
Return a Python AST Node for a `let*` expression.
11,381
def show(self, index): if self.menu and self.menu.parent: self.text = "Return to %s menu" % self.menu.parent.title else: self.text = "Exit" return super(ExitItem, self).show(index)
This class overrides this method
11,382
def get_meta(self, key=None): if self.is_fake: return {} if key == "tag": return self.tag elif key is None: ret = {} for key in self.journal.info.keys(): ret[key] = self.meta_mappings.map_get(self.journal.info, key)[1] ...
Get metadata value for collection.
11,383
def parse_template(input_filename, output_filename=): data = load_input() with open(input_filename, ) as file: template = file.read().decode("utf-8") if not in data: raise ValueError("Could not find in data") for field in data[]: subs = ["filename", "va...
Parses a template file Replaces all occurences of @@problem_id@@ by the value of the 'problem_id' key in data dictionary input_filename: file to parse output_filename: if not specified, overwrite input file
11,384
def _validate_arguments(self): super(SplineTerm, self)._validate_arguments() if self.basis not in self._bases: raise ValueError("basis must be one of {}, "\ "but found: {}".format(self._bases, self.basis)) self.n_splines = check_param(...
method to sanitize model parameters Parameters --------- None Returns ------- None
11,385
def _getScalesRand(self): if self.P>1: scales = [] for term_i in range(self.n_randEffs): _scales = sp.randn(self.diag[term_i].shape[0]) if self.jitter[term_i]>0: _scales = sp.concatenate((_scales,sp.array([sp.sqrt(self.jitter[t...
Internal function for parameter initialization Return a vector of random scales
11,386
def get_process_by_id(self, process_id): route_values = {} if process_id is not None: route_values[] = self._serialize.url(, process_id, ) response = self._send(http_method=, location_id=, version=, ...
GetProcessById. [Preview API] Get a process by ID. :param str process_id: ID for a process. :rtype: :class:`<Process> <azure.devops.v5_1.core.models.Process>`
11,387
def get_hashhash(self, username): return hashlib.sha256( self.users.get_hash(username) ).hexdigest()
Generate a digest of the htpasswd hash
11,388
def do_stack(self, arg): if arg: raise CmdError("too many arguments") pid, tid = self.get_process_and_thread_ids_from_prefix() process = self.get_process(pid) thread = process.get_thread(tid) try: stack_trace = thread....
[~thread] k - show the stack trace [~thread] stack - show the stack trace
11,389
def _get_healthmgr_cmd(self): healthmgr_main_class = healthmgr_cmd = [os.path.join(self.heron_java_home, ), , , , , , , ...
get the command to start the topology health manager processes
11,390
def to_eaf(self, skipempty=True, pointlength=0.1): from pympi.Elan import Eaf eaf_out = Eaf() if pointlength <= 0: raise ValueError() for tier in self.get_tiers(): eaf_out.add_tier(tier.name) for ann in tier.get_intervals(True): ...
Convert the object to an pympi.Elan.Eaf object :param int pointlength: Length of respective interval from points in seconds :param bool skipempty: Skip the empty annotations :returns: :class:`pympi.Elan.Eaf` object :raises ImportError: If the Eaf module c...
11,391
def hostname(self): from six.moves.urllib.parse import urlparse return urlparse(self._base_url).netloc.split(, 1)[0]
Get the hostname that this connection is associated with
11,392
def _expand_formula_(formula_string): formula_string = re.sub(r, , formula_string) hydrate_pos = formula_string.find() if hydrate_pos >= 0: formula_string = _expand_hydrate_(hydrate_pos, formula_string) search_result = re.search( r, formula_string) if search_result is No...
Accounts for the many ways a user may write a formula string, and returns an expanded chemical formula string. Assumptions: -The Chemical Formula string it is supplied is well-written, and has no hanging parethneses -The number of repeats occurs after the elemental symbol or ) ] character EXCEPT in the case...
11,393
def _ffn_layer_multi_inputs(inputs_list, hparams, ffn_layer_type="dense", name="ffn", kernel_initializer=None, bias_initializer=None, activation=None, ...
Implements a Feed-forward layer with multiple inputs, pad-removing, etc. Args: inputs_list: list of input tensors hparams: hyper-parameters ffn_layer_type: dense / dense_dropconnect/ dense_relu_dense name: name kernel_initializer: kernel initializer bias_initializer: bias initializer acti...
11,394
def remove_exit(self): if self.items: if self.items[-1] is self.exit_item: del self.items[-1] return True return False
Remove the exit item if necessary. Used to make sure we only remove the exit item, not something else. Returns: bool: True if item needed to be removed, False otherwise.
11,395
def to_yaml(template, clean_up=False, long_form=False): data = load_json(template) if clean_up: data = clean(data) return dump_yaml(data, clean_up, long_form)
Assume the input is JSON and convert to YAML
11,396
def recent_comments(context): latest = context["settings"].COMMENTS_NUM_LATEST comments = ThreadedComment.objects.all().select_related("user") context["comments"] = comments.order_by("-id")[:latest] return context
Dashboard widget for displaying recent comments.
11,397
def write(self, frames): with HDFStore(self._path, , complevel=self._complevel, complib=self._complib) \ as store: panel = pd.Panel.from_dict(dict(frames)) panel.to_hdf(store, ) with tables.open_file(self._path, mode=) as h5file: ...
Write the frames to the target HDF5 file, using the format used by ``pd.Panel.to_hdf`` Parameters ---------- frames : iter[(int, DataFrame)] or dict[int -> DataFrame] An iterable or other mapping of sid to the corresponding OHLCV pricing data.
11,398
def _refresh_html_home(self): req = self._parent.client.get(HOME_ENDPOINT) if req.status_code == 403: self._parent.login() self.update() elif req.status_code == 200: self._parent.html[] = generate_soup_html(req.text) else: req.rais...
Function to refresh the self._parent.html['home'] object which provides the status if zones are scheduled to start automatically (program_toggle).
11,399
def handle_message_registered(self, msg_data, host): response = None if msg_data["method"] == "EVENT": logger.debug("<%s> <euuid:%s> Event message " "received" % (msg_data["cuuid"], msg_data["euuid"])) response = self.event(msg_data["cuuid"], ...
Processes messages that have been delivered by a registered client. Args: msg (string): The raw packet data delivered from the listener. This data will be unserialized and then processed based on the packet's method. host (tuple): The (address, host) tuple of the sou...