Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
371,700
def diffPrefsPrior(priorstring): assert isinstance(priorstring, str) prior = priorstring.split() if len(prior) == 3 and prior[0] == : [c1, c2] = [float(x) for x in prior[1 : ]] assert c1 > 0 and c2 > 0, "C1 and C2 must be > 1 for invquadratic prior" return (, c1, c2) else: ...
Parses `priorstring` and returns `prior` tuple.
371,701
def spherical_sum(image, binning_factor=1.0): r = np.sqrt(sum(xi ** 2 for xi in image.space.meshgrid)) rmax = max(np.linalg.norm(c) for c in image.space.domain.corners()) n_bins = int(np.sqrt(sum(n ** 2 for n in image.shape)) / binning_factor) rad_sum, _ = np.histogram(r, weights=image, bins=n_bins...
Sum image values over concentric annuli. Parameters ---------- image : `DiscreteLp` element Input data whose radial sum should be computed. binning_factor : positive float, optional Reduce the number of output bins by this factor. Increasing this number can help reducing fluctua...
371,702
def find_host_network_interface_by_id(self, id_p): if not isinstance(id_p, basestring): raise TypeError("id_p can only be an instance of type basestring") network_interface = self._call("findHostNetworkInterfaceById", in_p=[id_p]) network_interface = IHo...
Searches through all host network interfaces for an interface with the given GUID. The method returns an error if the given GUID does not correspond to any host network interface. in id_p of type str GUID of the host network interface to search for. return ...
371,703
def _init_template(self, cls, base_init_template): if self.__class__ is not cls: raise TypeError("Inheritance from classes with @GtkTemplate decorators " "is not allowed at this time") connected_signals = set() self.__connected_template_signals__ = connected_...
This would be better as an override for Gtk.Widget
371,704
def from_raw(self, file_names=None, **kwargs): if file_names: self.file_names = file_names if not isinstance(file_names, (list, tuple)): self.file_names = [file_names, ] raw_file_loader = self.loader set_number = 0 ...
Load a raw data-file. Args: file_names (list of raw-file names): uses CellpyData.file_names if None. If the list contains more than one file name, then the runs will be merged together.
371,705
def init_session(self): if self.session: self.session.close() self.session = make_session(self.username, self.password, self.bearer_token, self.extra_headers_dict)
Defines a session object for passing requests.
371,706
def __optimize_configuration(self): index_neighbor = 0 while (index_neighbor < self.__maxneighbor): current_medoid_index = self.__current[random.randint(0, self.__number_clusters - 1)] current_medoid_cluster_index = self.__belong[current_medoid_index] ...
! @brief Finds quasi-optimal medoids and updates in line with them clusters in line with algorithm's rules.
371,707
def accuracy(self): if self._input_csv_files: df = self._get_data_from_csv_files() if not in df or not in df: raise ValueError() labels = sorted(set(df[]) | set(df[])) accuracy_results = [] for label in labels: correct_count = len(df[(df[] == df[]) & (df[] == ...
Get accuracy numbers for each target and overall. Returns: A DataFrame with two columns: 'class' and 'accuracy'. It also contains the overall accuracy with class being '_all'. Raises: Exception if the CSV headers do not include 'target' or 'predicted', or BigQuery does not return 'targ...
371,708
def most_seen_creators_by_works_card(work_kind=None, role_name=None, num=10): object_list = most_seen_creators_by_works( work_kind=work_kind, role_name=role_name, num=num) object_list = chartify(object_list, , cutoff=1) if role_name: creators_name = ...
Displays a card showing the Creators that are associated with the most Works. e.g.: {% most_seen_creators_by_works_card work_kind='movie' role_name='Director' num=5 %}
371,709
def normalize_pred_string(predstr): tokens = [t for t in split_pred_string(predstr)[:3] if t is not None] if predstr.lstrip("__'.join(tokens).lower()
Normalize the predicate string *predstr* to a conventional form. This makes predicate strings more consistent by removing quotes and the `_rel` suffix, and by lowercasing them. Examples: >>> normalize_pred_string('"_dog_n_1_rel"') '_dog_n_1' >>> normalize_pred_string('_dog_n_1') ...
371,710
def use(self, middleware=None, path=, method_mask=HTTPMethod.ALL): if middleware is None: return lambda mw: self.use(mw, path, method_mask) if hasattr(middleware, ): router = getattr(middleware, ) if isinstance(router, (types.MethodType,)): ...
Use the middleware (a callable with parameters res, req, next) upon requests match the provided path. A None path matches every request. Returns the middleware so this method may be used as a decorator. Args: middleware (callable): A function with signature '(req, res)' ...
371,711
def set_offset_and_sequence_number(self, event_data): if not event_data: raise Exception(event_data) self.offset = event_data.offset.value self.sequence_number = event_data.sequence_number
Updates offset based on event. :param event_data: A received EventData with valid offset and sequenceNumber. :type event_data: ~azure.eventhub.common.EventData
371,712
def get_template_names(self): if self.request.is_ajax(): return [self.list_template_name] else: return super(Search, self).get_template_names()
Dispatch template according to the kind of request: ajax or normal.
371,713
def getPlatformsByName(platformNames=[], mode=None, tags=[], excludePlatformNames=[]): allPlatformsList = getAllPlatformObjects(mode) platformList = [] if "all" in platformNames and len(tags) == 0: for plat in allPlatformsList: if str(plat.platformName).lower() not ...
Method that recovers the names of the <Platforms> in a given list. :param platformNames: List of strings containing the possible platforms. :param mode: The mode of the search. The following can be chosen: ["phonefy", "usufy", "searchfy"]. :param tags: Just in case the method to select...
371,714
def load_history(self, f): warnings.warn( "load_history is deprecated and will be removed in the next " "release, please use load_params with the f_history keyword", DeprecationWarning) self.history = History.from_file(f)
Load the history of a ``NeuralNet`` from a json file. See ``save_history`` for examples. Parameters ---------- f : file-like object or str
371,715
def configuration(self, event): try: self.log("Schemarequest for all configuration schemata from", event.user.account.name, lvl=debug) response = { : , : , : configschemastore } self.fi...
Return all configurable components' schemata
371,716
def set_paths(etc_paths = [ "/etc/" ]): global _ETC_PATHS _ETC_PATHS = [] for p in etc_paths: _ETC_PATHS.append(os.path.expanduser(p))
Sets the paths where the configuration files will be searched * You can have multiple configuration files (e.g. in the /etc/default folder and in /etc/appfolder/)
371,717
def is_carrying_minerals(self) -> bool: return any( buff.value in self._proto.buff_ids for buff in {BuffId.CARRYMINERALFIELDMINERALS, BuffId.CARRYHIGHYIELDMINERALFIELDMINERALS} )
Checks if a worker or MULE is carrying (gold-)minerals.
371,718
def map_tree(visitor, tree): newn = [map_tree(visitor, node) for node in tree.nodes] return visitor(tree, newn)
Apply function to nodes
371,719
def _make_lcdproc( lcd_host, lcd_port, retry_config, charset=DEFAULT_LCDPROC_CHARSET, lcdd_debug=False): class ServerSpawner(utils.AutoRetryCandidate): @utils.auto_retry def connect(self): return lcdrunner.LcdProcServer( lcd_host, lcd_port,...
Create and connect to the LCDd server. Args: lcd_host (str): the hostname to connect to lcd_prot (int): the port to connect to charset (str): the charset to use when sending messages to lcdproc lcdd_debug (bool): whether to enable full LCDd debug retry_attempts (int): the nu...
371,720
def anonymous_required(func=None, url=None): url = url or "/" def _dec(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): if request.user.is_authenticated(): return redirect(url) else: ...
Required that the user is not logged in.
371,721
def remove_record(self, orcid_id, token, request_type, put_code): self._update_activities(orcid_id, token, requests.delete, request_type, put_code=put_code)
Add a record to a profile. Parameters ---------- :param orcid_id: string Id of the author. :param token: string Token received from OAuth 2 3-legged authorization. :param request_type: string One of 'activities', 'education', 'employment', 'fu...
371,722
def get_all_objects(self): "Return pointers to all GC tracked objects" for i, generation in enumerate(self.gc_generations): generation_head_ptr = pygc_head_ptr = generation.head.get_pointer() generation_head_addr = generation_head_ptr._value while True: ...
Return pointers to all GC tracked objects
371,723
def native(self, value, context=None): separator = self.separator.strip() if self.strip and hasattr(self.separator, ) else self.separator value = super().native(value, context) if value is None: return self.cast() if hasattr(value, ): value = value.split(separator) value = self._clean(val...
Convert the given string into a list of substrings.
371,724
def get_assessments_taken_by_query(self, assessment_taken_query): and_list = list() or_list = list() for term in assessment_taken_query._query_terms: if in assessment_taken_query._query_terms[term] and in assessment_taken_query._query_terms[term]: ...
Gets a list of ``AssessmentTaken`` elements matching the given assessment taken query. arg: assessment_taken_query (osid.assessment.AssessmentTakenQuery): the assessment taken query return: (osid.assessment.AssessmentTakenList) - the returned ``Assessm...
371,725
def is_transaction_invalidated(transaction, state_change): is_our_failed_update_transfer = ( isinstance(state_change, ContractReceiveChannelSettled) and isinstance(transaction, ContractSendChannelUpdateTransfer) and state_change.token_network_ide...
True if the `transaction` is made invalid by `state_change`. Some transactions will fail due to race conditions. The races are: - Another transaction which has the same side effect is executed before. - Another transaction which *invalidates* the state of the smart contract required by the local trans...
371,726
def _register_namespace_and_command(self, namespace): self._add_namespace(namespace) cmd_name = namespace.source_name.split(".", 1)[0] + ".$cmd" dest_cmd_name = namespace.dest_name.split(".", 1)[0] + ".$cmd" self._add_namespace(Namespace(dest_name=dest_cmd_name, source_...
Add a Namespace and the corresponding command namespace.
371,727
def add_arguments(parser): parser.add_argument(, , help=, required=False, nargs=) parser.add_argument(, , help=, action=)
Args for the init command
371,728
def get_weather_data(filename=, **kwargs): r if not in kwargs: kwargs[] = os.path.join(os.path.split( os.path.dirname(__file__))[0], ) file = os.path.join(kwargs[], filename) weather_df = pd.read_csv( file, index_col=0, header=[0, 1], date_parser=lambda idx: pd...
r""" Imports weather data from a file. The data include wind speed at two different heights in m/s, air temperature in two different heights in K, surface roughness length in m and air pressure in Pa. The file is located in the example folder of the windpowerlib. The height in m for which the data ...
371,729
def match(self, data, threshold=0.5, generator=False): blocked_pairs = self._blockData(data) clusters = self.matchBlocks(blocked_pairs, threshold) if generator: return clusters else: return list(clusters)
Identifies records that all refer to the same entity, returns tuples containing a set of record ids and a confidence score as a float between 0 and 1. The record_ids within each set should refer to the same entity and the confidence score is a measure of our confidence that all ...
371,730
def main(argv=None): if argv is None: argv = sys.argv else: sys.argv.extend(argv) program_name = os.path.basename(sys.argv[0]) program_version = "v%s" % __version__ program_build_date = str(__updated__) program_version_message = % (program_version, ...
Parse command line options and create a server/volume composite.
371,731
def create_anisomagplot(plotman, x, y, z, alpha, options): sizex, sizez = getfigsize(plotman) f, ax = plt.subplots(2, 3, figsize=(3 * sizex, 2 * sizez)) if options.title is not None: plt.suptitle(options.title, fontsize=18) plt.subplots_adjust(wspace=1.5, top=2) if options...
Plot the data of the tomodir in one overview plot.
371,732
def _get_area_data(self): if self.mode == : data = [self.hist[].data,\ self.hist[].data,\ self.hist[].data,\ self.hist[].data] elif self.area == : data = [self.hist[].data,\ ...
Get histogram list based on area type. List pattern: [type1_hel+,type2_hel+,type1_hel-,type2_hel-] where type1/2 = F/B or R/L in that order.
371,733
def statistic_recommend(classes, P): if imbalance_check(P): return IMBALANCED_RECOMMEND if binary_check(classes): return BINARY_RECOMMEND return MULTICLASS_RECOMMEND
Return recommend parameters which are more suitable due to the input dataset characteristics. :param classes: all classes name :type classes : list :param P: condition positive :type P : dict :return: recommendation_list as list
371,734
def do_alias(self, arg): args = arg.split() if len(args) == 0: keys = sorted(self.aliases.keys()) for alias in keys: self.message("%s = %s" % (alias, self.aliases[alias])) return if args[0] in self.aliases and len(args) == 1: ...
alias [name [command [parameter parameter ...] ]] Create an alias called 'name' that executes 'command'. The command must *not* be enclosed in quotes. Replaceable parameters can be indicated by %1, %2, and so on, while %* is replaced by all the parameters. If no command is given, the ...
371,735
def novatel_diag_send(self, timeStatus, receiverStatus, solStatus, posType, velType, posSolAge, csFails, force_mavlink1=False): return self.send(self.novatel_diag_encode(timeStatus, receiverStatus, solStatus, posType, velType, posSolAge, csFails), force_mavlink1=force_mavlink1)
Transmits the diagnostics data from the Novatel OEMStar GPS timeStatus : The Time Status. See Table 8 page 27 Novatel OEMStar Manual (uint8_t) receiverStatus : Status Bitfield. See table 69 page 350 Novatel OEMstar Manual (uint32_t) solStatus ...
371,736
def serialize(self, subject, *objects_or_combinators): ec_s = rdflib.BNode() if self.operator is not None: if subject is not None: yield subject, self.predicate, ec_s yield from oc(ec_s) yield from self._list.serialize(ec_s, self.operator, *ob...
object_combinators may also be URIRefs or Literals
371,737
def in_telephones(objet, pattern): objet = objet or [] if pattern == or not objet: return False return max(bool(re.search(pattern, t)) for t in objet)
abstractSearch dans une liste de téléphones.
371,738
def replace_greek_tex(self, name): name = name.replace(, ) name = name.replace(, ) for greek_txt, tex in self.greek2tex.items(): if greek_txt in name: name = name.replace(greek_txt, "{B}".format(B=tex)) retu...
Replace text representing greek letters with greek letters.
371,739
def json(self): if self.fresh(): return self.__cached_json self.__last_read_time = time.time() self.__cached_json = self._router.get_instance(org_id=self.organizationId, instance_id=self.instanceId).json() return self.__cached_json
return __cached_json, if accessed withing 300 ms. This allows to optimize calls when many parameters of entity requires withing short time.
371,740
def _initGP(self): if self._inference==: signalPos = sp.where(sp.arange(self.n_randEffs)!=self.noisPos)[0][0] gp = GP2KronSum(Y=self.Y, F=self.sample_designs, A=self.trait_designs, Cg=self.trait_covars[signalPos], Cn=self.trait_covars[self.noisPos], ...
Internal method for initialization of the GP inference objetct
371,741
def is_client_ip_address_whitelisted(request: AxesHttpRequest): if settings.AXES_NEVER_LOCKOUT_WHITELIST and is_ip_address_in_whitelist(request.axes_ip_address): return True if settings.AXES_ONLY_WHITELIST and is_ip_address_in_whitelist(request.axes_ip_address): return True return Fa...
Check if the given request refers to a whitelisted IP.
371,742
def divide(self, layer=WORDS, by=SENTENCES): if not self.is_tagged(layer): self.tag(layer) if not self.is_tagged(by): self.tag(by) return divide(self[layer], self[by])
Divide the Text into pieces by keeping references to original elements, when possible. This is not possible only, if the _element_ is a multispan. Parameters ---------- element: str The element to collect and distribute in resulting bins. by: str Each re...
371,743
def pvfactors_timeseries( solar_azimuth, solar_zenith, surface_azimuth, surface_tilt, timestamps, dni, dhi, gcr, pvrow_height, pvrow_width, albedo, n_pvrows=3, index_observed_pvrow=1, rho_front_pvrow=0.03, rho_back_pvrow=0.05, horizon_band_angle=15., run_parallel_calculat...
Calculate front and back surface plane-of-array irradiance on a fixed tilt or single-axis tracker PV array configuration, and using the open-source "pvfactors" package. Please refer to pvfactors online documentation for more details: https://sunpower.github.io/pvfactors/ Parameters ---------- ...
371,744
def _update_state(self, change): self._block_updates = True try: self.position = self.axis.Location() self.direction = self.axis.Direction() finally: self._block_updates = False
Keep position and direction in sync with axis
371,745
def load(self, wishlist, calibration=None, resolution=None, polarization=None, level=None, generate=True, unload=True, **kwargs): dataset_keys = set(wishlist) needed_datasets = (self.wishlist | dataset_keys) - \ set(self.datasets.keys()) unknown = s...
Read and generate requested datasets. When the `wishlist` contains `DatasetID` objects they can either be fully-specified `DatasetID` objects with every parameter specified or they can not provide certain parameters and the "best" parameter will be chosen. For example, if a dataset is a...
371,746
def _to_topology(self, atom_list, chains=None, residues=None): from mdtraj.core.topology import Topology if isinstance(chains, string_types): chains = [chains] if isinstance(chains, (list, set)): chains = tuple(chains) if isinstance(residues, string_typ...
Create a mdtraj.Topology from a Compound. Parameters ---------- atom_list : list of mb.Compound Atoms to include in the topology chains : mb.Compound or list of mb.Compound Chain types to add to the topology residues : str of list of str Label...
371,747
async def _create_transaction(self, msg, *args, **kwargs): recv_msgs, get_key, _1, _2, _3 = self._msgs_registered[msg.__msgtype__] key = get_key(msg) if key in self._transactions[recv_msgs[0]]: for recv_msg in recv_msgs: self._transactions[recv_...
Create a transaction with the distant server :param msg: message to be sent :param args: args to be sent to the coroutines given to `register_transaction` :param kwargs: kwargs to be sent to the coroutines given to `register_transaction`
371,748
def to_dict(self): return { "timestamp": int(self.timestamp), "timezone": self.timezone, "time_of_day": self.time_of_day, "day_of_week": self.day_of_week, "day_of_month": self.day_of_month, "month_of_year": self.month_of_year, "utc_iso": self.utc_iso }
Returns the Time instance as a usable dictionary for craftai
371,749
def _req_rep_retry(self, request): retries_left = self.RETRIES while retries_left: self._logger.log(1, , request) self._send_request(request) socks = dict(self._poll.poll(self.TIMEOUT)) if socks.get(self._socket) == zmq.POLLIN: res...
Returns response and number of retries
371,750
def get_value(cls, bucket, key): obj = cls.get(bucket, key) return obj.value if obj else None
Get tag value.
371,751
def _list_machines(self): try: req = self.request(self.mist_client.uri++self.id+) machines = req.get().json() except: machines = {} if machines: for machine in machines: self._machines[machine[]] = Machine(mac...
Request a list of all added machines. Populates self._machines dict with mist.client.model.Machine instances
371,752
def to_timepoints(self, unit=, offset=None): unit = Period.from_cfunits(unit) if offset is None: offset = 0. else: try: offset = Period(offset)/unit except TypeError: offset = offset step = self.stepsize/unit ...
Return an |numpy.ndarray| representing the starting time points of the |Timegrid| object. The following examples identical with the ones of |Timegrid.from_timepoints| but reversed. By default, the time points are given in hours: >>> from hydpy import Timegrid >>> timeg...
371,753
def repartition(self, num_partitions, repartition_function=None): from heronpy.streamlet.impl.repartitionbolt import RepartitionStreamlet if repartition_function is None: repartition_function = lambda x: x repartition_streamlet = RepartitionStreamlet(num_partitions, repartition_function, self) ...
Return a new Streamlet containing all elements of the this streamlet but having num_partitions partitions. Note that this is different from num_partitions(n) in that new streamlet will be created by the repartition call. If repartiton_function is not None, it is used to decide which parititons (from 0 t...
371,754
def map_to_subset(self, file, outfile=None, ontology=None, subset=None, class_map=None, relations=None): if subset is not None: logging.info("Creating mapping for subset: {}".format(subset)) class_map = ontology.create_slim_mapping(subset=subset, relations=relations) if...
Map a file to a subset, writing out results You can pass either a subset name (e.g. goslim_generic) or a dictionary with ready-made mappings Arguments --------- file: file Name or file object for input assoc file outfile: file Name or file object for out...
371,755
def merge(self, other): for attr in self.attrs: if not getattr(other, attr, None) is None: setattr(self, attr, getattr(other, attr)) if other.raw: if not self.raw: self.raw = {} self.raw.update(other.raw)
Copy properties from other into self, skipping ``None`` values. Also merges the raw data. Args: other (SkypeObj): second object to copy fields from
371,756
def get_series_episodes(self, id, page=1): params = {: page} r = self.session.get(self.base_url + .format(id), params=params) if r.status_code == 404: return None r.raise_for_status() return r.json()
Get series episodes
371,757
def _simplify(elements): simplified = [] previous = None for element in elements: if element == "..": raise FormicError("Invalid glob:" " Cannot have in a glob: {0}".format( "/".join(ele...
Simplifies and normalizes the list of elements removing redundant/repeated elements and normalising upper/lower case so case sensitivity is resolved here.
371,758
def to_kwargs(triangles): triangles = np.asanyarray(triangles, dtype=np.float64) if not util.is_shape(triangles, (-1, 3, 3)): raise ValueError() vertices = triangles.reshape((-1, 3)) faces = np.arange(len(vertices)).reshape((-1, 3)) kwargs = {: vertices, : faces} ret...
Convert a list of triangles to the kwargs for the Trimesh constructor. Parameters --------- triangles : (n, 3, 3) float Triangles in space Returns --------- kwargs : dict Keyword arguments for the trimesh.Trimesh constructor Includes keys 'vertices' and 'faces' Examp...
371,759
def infer(examples, alt_rules=None): date_classes = _tag_most_likely(examples) if alt_rules: date_classes = _apply_rewrites(date_classes, alt_rules) else: date_classes = _apply_rewrites(date_classes, RULES) date_string = for date_class in date_classes: date_string += ...
Returns a datetime.strptime-compliant format string for parsing the *most likely* date format used in examples. examples is a list containing example date strings.
371,760
def add_column(self, tablename: str, fieldspec: FIELDSPEC_TYPE) -> int: sql = "ALTER TABLE {} ADD COLUMN {}".format( tablename, self.fielddefsql_from_fieldspec(fieldspec)) log.info(sql) return self.db_exec_literal(sql)
Adds a column to an existing table.
371,761
def unicode_dict(_dict): r = {} for k, v in iteritems(_dict): r[unicode_obj(k)] = unicode_obj(v) return r
Make sure keys and values of dict is unicode.
371,762
def take(self, axis, n): if not axis: partitions = self.partitions bin_lengths = self.block_lengths else: partitions = self.partitions.T bin_lengths = self.block_widths if n < 0: length_bins = np.cumsum(bin_lengths[::-...
Take the first (or last) n rows or columns from the blocks Note: Axis = 0 will be equivalent to `head` or `tail` Axis = 1 will be equivalent to `front` or `back` Args: axis: The axis to extract (0 for extracting rows, 1 for extracting columns) n: The number of row...
371,763
def getAdjEdges(self, networkId, nodeId, verbose=None): response=api(url=self.___url++str(networkId)++str(nodeId)+, method="GET", verbose=verbose, parse_params=False) return response
Returns a list of connected edges as SUIDs for the node specified by the `nodeId` and `networkId` parameters. :param networkId: SUID of the network containing the node :param nodeId: SUID of the node :param verbose: print more :returns: 200: successful operation
371,764
def verify_hash_type(self): if self.config[].lower() in [, ]: log.warning( , self.config[], self.__class__.__name__ )
Verify and display a nag-messsage to the log if vulnerable hash-type is used. :return:
371,765
def add_to_products(self, products=None, all_products=False): if all_products: if products: raise ArgumentError("When adding to all products, do not specify specific products") plist = "all" else: if not products: raise Argumen...
Add user group to some product license configuration groups (PLCs), or all of them. :param products: list of product names the user should be added to :param all_products: a boolean meaning add to all (don't specify products in this case) :return: the Group, so you can do Group(...).add_to_produ...
371,766
def _todict(cls): return dict((getattr(cls, attr), attr) for attr in dir(cls) if not attr.startswith())
generate a dict keyed by value
371,767
def model_config_from_estimator(instance_type, estimator, task_id, task_type, role=None, image=None, name=None, model_server_workers=None, vpc_config_override=vpc_utils.VPC_CONFIG_DEFAULT): update_estimator_from_task(estimator, task_id, task_type) if isinstance(estimator, sa...
Export Airflow model config from a SageMaker estimator Args: instance_type (str): The EC2 instance type to deploy this Model to. For example, 'ml.p2.xlarge' estimator (sagemaker.model.EstimatorBase): The SageMaker estimator to export Airflow config from. It has to be an estimator associ...
371,768
def ChunkedTransformerLM(vocab_size, feature_depth=512, feedforward_depth=2048, num_layers=6, num_heads=8, dropout=0.1, chunk_selector=None, max_...
Transformer language model operating on chunks. The input to this model is a sequence presented as a list or tuple of chunks: (chunk1, chunk2, chunks3, ..., chunkN). Each chunk should have the same shape (batch, chunk-length) and together they represent a long sequence that's a concatenation chunk1,chunk2,....
371,769
def _parse_commit(self, ref): lineno = self.lineno mark = self._get_mark_if_any() author = self._get_user_info(b, b, False) more_authors = [] while True: another_author = self._get_user_info(b, b, False) if another_author is not None: ...
Parse a commit command.
371,770
def from_symmop(cls, symmop, time_reversal): magsymmop = cls(symmop.affine_matrix, time_reversal, symmop.tol) return magsymmop
Initialize a MagSymmOp from a SymmOp and time reversal operator. Args: symmop (SymmOp): SymmOp time_reversal (int): Time reversal operator, +1 or -1. Returns: MagSymmOp object
371,771
def _cmd_up(self): revision = self._get_revision() if not self._rev: self._log(0, "upgrading current revision") else: self._log(0, "upgrading from revision %s" % revision) for rev in self._revisions[int(revision) - 1:]: sql_files = glob.glob(o...
Upgrade to a revision
371,772
def extra_space_exists(str1: str, str2: str) -> bool: ls1, ls2 = len(str1), len(str2) if str1.isdigit(): if str2 in [, ]: return True if ls2 > 2 and str2[0] == and str2[1:].isdigit(): return True if str2.isdigit(): if str1 in...
Return True if a space shouldn't exist between two items
371,773
def _count_extra_actions(self, game_image): proportional = self._bonus_tools[] t, l, b, r = proportional.region_in(game_image) token_region = game_image[t:b, l:r] game_h, game_w = game_image.shape[0:2] token_h = int(round(game_h * 27.0 / 960)) t...
Count the number of extra actions for player in this turn.
371,774
def remove_secondary_linked_files(self, file_path=None, relpath=None, mimetype=None, time_origin=None, assoc_with=None): for attrib in self.linked_file_descriptors[:]: if file_path is not None and attrib[] != file_p...
Remove all secondary linked files that match all the criteria, criterias that are ``None`` are ignored. :param str file_path: Path of the file. :param str relpath: Relative filepath. :param str mimetype: Mimetype of the file. :param int time_origin: Time origin. :param s...
371,775
def DeleteOldRuns(self, cutoff_timestamp=None): if cutoff_timestamp is None: raise ValueError("cutoff_timestamp can't be None") return data_store.REL_DB.DeleteOldCronJobRuns( cutoff_timestamp=cutoff_timestamp)
Deletes runs that were started before the timestamp given.
371,776
def getDuration(self): starttime = self.getStartProcessDate() if not starttime: return 0 endtime = self.getDateVerified() or DateTime() duration = (endtime - starttime) * 24 * 60 return duration
Returns the time in minutes taken for this analysis. If the analysis is not yet 'ready to process', returns 0 If the analysis is still in progress (not yet verified), duration = date_verified - date_start_process Otherwise: duration = current_datetime - date_start_process...
371,777
def compile_id_list(self, polygon_id_list, nr_of_polygons): def all_equal(iterable): x = None for x in iterable: break for y in iterable: if x != y: return False return True ...
sorts the polygons_id list from least to most occurrences of the zone ids (->speed up) only 4.8% of all shortcuts include polygons from more than one zone but only for about 0.4% sorting would be beneficial (zones have different frequencies) in most of those cases there are only two types of zon...
371,778
def _WsdlHasMethod(self, method_name): try: self._method_bindings.get(method_name) return True except ValueError: return False
Determine if a method is in the wsdl. Args: method_name: The name of the method. Returns: True if the method is in the wsdl, otherwise False.
371,779
def get_all_outcome_links_for_context_accounts(self, account_id, outcome_group_style=None, outcome_style=None): path = {} data = {} params = {} path["account_id"] = account_id if outcome_style is not None: para...
Get all outcome links for context.
371,780
def connect(self): "Connect to a host on a given (SSL) port." sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((self.host, self.port)) boto.log.debug("wrapping ssl socket; CA certificate file=%s", self.ca_certs) self.sock = ssl.wrap_socket(sock, keyfile=self.k...
Connect to a host on a given (SSL) port.
371,781
def get_appstruct(self): result = [] for k in self._get_keys(): result.append((k, getattr(self, k))) return result
return list of tuples keys and values corresponding to this model's data
371,782
def _negotiate_SOCKS4(self, dest_addr, dest_port): proxy_type, addr, port, rdns, username, password = self.proxy writer = self.makefile("wb") reader = self.makefile("rb", 0) try: remote_resolve = False try: addr_bytes = soc...
Negotiates a connection through a SOCKS4 server.
371,783
def readGraph(edgeList, nodeList = None, directed = False, idKey = , eSource = , eDest = ): progArgs = (0, "Starting to reading graphs") if metaknowledge.VERBOSE_MODE: progKwargs = { : False} else: progKwargs = { : True} with _ProgressBar(*progArgs, **progKwargs) as PBar: if...
Reads the files given by _edgeList_ and _nodeList_ and creates a networkx graph for the files. This is designed only for the files produced by metaknowledge and is meant to be the reverse of [writeGraph()](#metaknowledge.graphHelpers.writeGraph), if this does not produce the desired results the networkx builtin [n...
371,784
def SensorShare(self, sensor_id, parameters): if not parameters[][]: parameters[].pop() if not parameters[][]: parameters[].pop() if self.__SenseApiCall__("/sensors/{0}/users".format(sensor_id), "POST", parameters = parameters): return Tr...
Share a sensor with a user @param sensor_id (int) - Id of sensor to be shared @param parameters (dictionary) - Additional parameters for the call @return (bool) - Boolean indicating whether the ShareSensor call was successful
371,785
def find_matching_builtin(self, node): for path in EQUIVALENT_ITERATORS.keys(): correct_alias = {path_to_node(path)} if self.aliases[node.func] == correct_alias: return path
Return matched keyword. If the node alias on a correct keyword (and only it), it matches.
371,786
def redact_http_basic_auth(output): url_re = redacted = r if sys.version_info >= (2, 7): return re.sub(url_re, redacted, output, flags=re.IGNORECASE) else: if re.search(url_re, output.lower()): return re.sub(url...
Remove HTTP user and password
371,787
def _load_schemas(self): types = (, , , , ) for type in types: schema_path = os.path.join(os.path.split(__file__)[0], % type) self._schema[type] = json.load(open(schema_path)) self._schema[type][][settings.LEVEL_FIELD...
load all schemas into schema dict
371,788
def triple_apply(self, triple_apply_fn, mutated_fields, input_fields=None): sourcedestsourcedestdegreedegreedegreedegree__src_id__dst_idcid__idcidcidcidcid assert inspect.isfunction(triple_apply_fn), "Input must be a function" if not (type(mutated_fields) is list or type(mutated_fields) is str)...
Apply a transform function to each edge and its associated source and target vertices in parallel. Each edge is visited once and in parallel. Modification to vertex data is protected by lock. The effect on the returned SGraph is equivalent to the following pseudocode: >>> PARALLEL FOR (...
371,789
def _set_switchport_basic(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=switchport_basic.switchport_basic, is_container=, presence=False, yang_name="switchport-basic", rest_name="", parent=self, path_helper=self._path_helper, extmethods=self._extmet...
Setter method for switchport_basic, mapped from YANG variable /interface/ethernet/switchport_basic (container) If this variable is read-only (config: false) in the source YANG file, then _set_switchport_basic is considered as a private method. Backends looking to populate this variable should do so via ...
371,790
def get_memory_info(self): rss, vms = _psutil_bsd.get_process_memory_info(self.pid)[:2] return nt_meminfo(rss, vms)
Return a tuple with the process' RSS and VMS size.
371,791
def contains(self, x, ctrs, kdtree=None): return self.overlap(x, ctrs, kdtree=kdtree) > 0
Check if the set of balls contains `x`. Uses a K-D Tree to perform the search if provided.
371,792
def load_edbfile(file=None): import ephem,string,math if file is None: import tkFileDialog try: file=tkFileDialog.askopenfilename() except: return if file is None or file == : return f=open(file) lines=f.readlines() f.close() for line in...
Load the targets from a file
371,793
def to_CAG(self): G = nx.DiGraph() for (name, attrs) in self.nodes(data=True): if attrs["type"] == "variable": for pred_fn in self.predecessors(name): if not any( fn_type in pred_fn for fn_type in (...
Export to a Causal Analysis Graph (CAG) PyGraphviz AGraph object. The CAG shows the influence relationships between the variables and elides the function nodes.
371,794
def run_rnaseq_ann_filter(data): data = to_single_data(data) if dd.get_vrn_file(data): eff_file = effects.add_to_vcf(dd.get_vrn_file(data), data)[0] if eff_file: data = dd.set_vrn_file(data, eff_file) ann_file = population.run_vcfanno(dd.get_vrn_file(data), data) ...
Run RNA-seq annotation and filtering.
371,795
def template(self, lambda_arn, role_arn, output=None, json=False): if not lambda_arn: raise ClickException("Lambda ARN is required to template.") if not role_arn: raise ClickException("Role ARN is required to template.") self.zappa.credentials_arn = role_arn ...
Only build the template file.
371,796
def parse_sphinx_searchindex(searchindex): if hasattr(searchindex, ): searchindex = searchindex.decode() query = pos = searchindex.find(query) if pos < 0: raise ValueError() sel = _select_block(searchindex[pos:], , ) objects = _parse_dict_recursive(sel) ...
Parse a Sphinx search index Parameters ---------- searchindex : str The Sphinx search index (contents of searchindex.js) Returns ------- filenames : list of str The file names parsed from the search index. objects : dict The objects parsed from the search index.
371,797
def convert(source, ext=COMPLETE, fmt=HTML, dname=None): if dname and not ext & COMPATIBILITY: if os.path.isfile(dname): dname = os.path.abspath(os.path.dirname(dname)) source, _ = _expand_source(source, dname, fmt) _MMD_LIB.markdown_to_string.argtypes = [ctypes.c_char_p, ctypes...
Converts a string of MultiMarkdown text to the requested format. Transclusion is performed if the COMPATIBILITY extension is not set, and dname is set to a valid directory Keyword arguments: source -- string containing MultiMarkdown text ext -- extension bitfield to pass to conversion process f...
371,798
def get_src_or_dst_prompt(mode): _words = {"read": "from", "write": "to"} prompt = "Where would you like to {} your file(s) {}?\n" \ "1. Desktop ({})\n" \ "2. Downloads ({})\n" \ "3. Current ({})\n" \ "4. Browse".format(mode, _words[mode], ...
String together the proper prompt based on the mode :param str mode: "read" or "write" :return str prompt: The prompt needed
371,799
def deleted_records(endpoint): @utils.for_each_value def _deleted_records(self, key, value): deleted_recid = maybe_int(value.get()) if deleted_recid: return get_record_ref(deleted_recid, endpoint) return _deleted_records
Populate the ``deleted_records`` key.