Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
343,800
def clear_content(self): content_child_elms = self[1:] if self.rPr is not None else self[:] for child in content_child_elms: self.remove(child)
Remove all child elements except the ``<w:rPr>`` element if present.
343,801
def postComponents(self, name, status, **kwargs): kwargs[] = name kwargs[] = status return self.__postRequest(, kwargs)
Create a new component. :param name: Name of the component :param status: Status of the component; 1-4 :param description: (optional) Description of the component :param link: (optional) A hyperlink to the component :param order: (optional) Order of the component :param ...
343,802
def from_dict(cls, data): auth_info = AuthenticationInformation.from_dict( data.get("auth_info", {}) ) instance = cls( auth_info=auth_info, requester=data.get("requester"), requester_name=data.get("requester_name"), subject_id=...
:type data: dict[str, str] :rtype: satosa.internal.InternalData :param data: A dict representation of an InternalData object :return: An InternalData object
343,803
def Iwik(dW, h, n=5): N = dW.shape[0] m = dW.shape[1] if dW.ndim < 3: dW = dW.reshape((N, -1, 1)) if dW.shape[2] != 1 or dW.ndim > 3: raise(ValueError) if m == 1: return (np.zeros((N, 1, 1)), (dW*dW - h)/2.0) Pm0 = _P(m) Km0 = _K(m) M = m*(m-1)//2 Atilde...
matrix I approximating repeated Ito integrals for each of N time intervals, using the method of Wiktorsson (2001). Args: dW (array of shape (N, m)): giving m independent Weiner increments for each time step N. (You can make this array using sdeint.deltaW()) h (float): the time step size ...
343,804
def create_api_v4_ipv6(self): return ApiV4IPv6( self.networkapi_url, self.user, self.password, self.user_ldap)
Get an instance of Api V4 IPv6 services facade.
343,805
def subintf_real_ip_check_gw_port(self, gw_port, ip_addr, netmask): if gw_port is not None: found = False for i in range(len(gw_port[])): target_ip = gw_port[][i][] if ip_addr == target_ip: found = True brea...
checks running-cfg derived ip_addr and netmask against neutron-db gw_port
343,806
def _get_result_wrapper(self, query): cursor = RowsCursor(self._rows, self._cursor.description) return query._get_cursor_wrapper(cursor)
Get result wrapper class.
343,807
async def get_nym(self, target_did: str = None) -> str: LOGGER.debug(, target_did) if target_did and not ok_did(target_did): LOGGER.debug(, target_did) raise BadIdentifier(.format(target_did)) if not (target_did or self.did): LOGGER.debug(, self.na...
Get json cryptonym (including current verification key) for input (anchor) DID from ledger. Return empty production {} if the ledger has no such cryptonym. Raise BadLedgerTxn on failure. Raise WalletState if target DID is default (own DID) value but wallet does not have it (neither created nor ...
343,808
def merge(filehandle_1, filehandle_2, output_filehandle): line2 = filehandle_2.readline() for line1 in filehandle_1.readlines(): while line2 != and line2 <= line1: output_filehandle.write(line2) line2 = filehandle_2.readline() output_filehandle.write(line1) whil...
Merges together two files maintaining sorted order.
343,809
def iter_points(x): if isinstance(x, (list, tuple)): if len(x): if isinstance(x[0], (list, tuple)): out = [] for y in x: out += iter_points(y) return out else: return [x] else: ...
Iterates over a list representing a feature, and returns a list of points, whatever the shape of the array (Point, MultiPolyline, etc).
343,810
def generateResourceFiles(srcpath, outpath=, buildpath=, build=True): for filename in os.listdir(srcpath): rscpath = os.path.join(srcpath, filename) if os.path.isdir(rscpath): generateResourceFile(rscpath, outpath, buildpath, build)
Generates a Qt resource file based on the given source path. This will take all the files and folders within the source and generate a new XML representation of that path. An optional outpath can be provided as the generated resource path, by default it will be called the name of the source path. ...
343,811
def create_workflows_dict(self, ast): workflows = self.find_asts(ast, ) for workflow in workflows: self.parse_workflow(workflow) return self.workflows_dictionary
Parse each "Workflow" in the AST. This will create self.workflows_dictionary, where each called job is a tuple key of the form: (priority#, job#, name, alias). :return: Creates the self.workflows_dictionary necessary for much of the parser. Returning it is only necessary for unittests.
343,812
def getAsWkt(self, session): statement = .format(self.geometryColumnName, self.tableName, self.id) result = session.execute(statement) for row in result: return row.wkt
Retrieve the geometry in Well Known Text format. This method is a veneer for an SQL query that calls the ``ST_AsText()`` function on the geometry column. Args: session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound to PostGIS enabled database. Returns: ...
343,813
def scatter(x,Ns,start): xI = np.real(x[start::Ns]) xQ = np.imag(x[start::Ns]) return xI, xQ
Sample a baseband digital communications waveform at the symbol spacing. Parameters ---------- x : ndarray of the input digital comm signal Ns : number of samples per symbol (bit) start : the array index to start the sampling Returns ------- xI : ndarray of the real part of x following...
343,814
def registerLoggers(info, error, debug): global log_info global log_error global log_debug log_info = info log_error = error log_debug = debug
Add logging functions to this module. Functions will be called on various severities (log, error, or debug respectively). Each function must have the signature: fn(message, **kwargs) If Python str.format()-style placeholders are in message, kwargs will be interpolated.
343,815
def append_step(self, title, description, timestamp=None, data=None): step = ProvenanceStep(title, description, timestamp, data) self._steps.append(step) return step.time
Append a new provenance step. :param title: the title of the ProvenanceStep :type title: str :param description: the description of the ProvenanceStep :type description: str :param timestamp: the time of the ProvenanceStep :type timestamp: datetime, None, str ...
343,816
def _make_hostport(conn, default_host, default_port, default_user=, default_password=None): parsed = urllib.parse.urlparse( % conn) return Connection( parsed.hostname or default_host, parsed.port or default_port, parsed.username if parsed.username is not None else default_user, ...
Convert a '[user[:pass]@]host:port' string to a Connection tuple. If the given connection is empty, use defaults. If no port is given, use the default. Args: conn (str): the string describing the target hsot/port default_host (str): the host to use if ``conn`` is empty default_port...
343,817
def reverse_ip_whois(self, query=None, ip=None, country=None, server=None, include_total_count=False, page=1, **kwargs): if (ip and query) or not (ip or query): raise ValueError() return self._results(, , query=query, ip=ip, country=country, ...
Pass in an IP address or a list of free text query terms.
343,818
def _get_media(media_types): get_mapped_media = (lambda x: maps.VIRTUAL_MEDIA_TYPES_MAP[x] if x in maps.VIRTUAL_MEDIA_TYPES_MAP else None) return list(map(get_mapped_media, media_types))
Helper method to map the media types.
343,819
def mmf(x, alpha, beta, kappa, delta): return alpha - (alpha - beta) / (1. + (kappa * x)**delta)
Morgan-Mercer-Flodin http://www.pisces-conservation.com/growthhelp/index.html?morgan_mercer_floden.htm Parameters ---------- x: int alpha: float beta: float kappa: float delta: float Returns ------- float alpha - (alpha - beta) / (1. + (kappa * x)**delta)
343,820
def replace_close(x, xhat, rtol=default_rtol, atol=default_atol, copy=True): s isclose(), and the atol and rtol options are passed along. The x and xhat arguments may be lists/arrays. The optional argument copy may also be set to False to chop x in-place. ' if rtol is None: rtol = default_rtol ...
replace_close(x, xhat) yields x if x is not close to xhat and xhat otherwise. Closeness is determined by numpy's isclose(), and the atol and rtol options are passed along. The x and xhat arguments may be lists/arrays. The optional argument copy may also be set to False to chop x in-place.
343,821
def _perform_request(self, request, parser=None, parser_args=None, operation_context=None, expected_errors=None): operation_context = operation_context or _OperationContext() retry_context = RetryContext() retry_context.is_emulated = self.is_emulated if hasattr(request...
Sends the request and return response. Catches HTTPError and hands it to error handler
343,822
def extend_webfont_settings(webfont_settings): if not webfont_settings.get(, False): raise IcomoonSettingsError(("Webfont settings miss the required key " "item ")) if not webfont_settings.get(, False): webfont_settings[] = None return webfont_setti...
Validate a webfont settings and optionally fill missing ``csspart_path`` option. Args: webfont_settings (dict): Webfont settings (an item value from ``settings.ICOMOON_WEBFONTS``). Returns: dict: Webfont settings
343,823
def help(route): r help_text = getRouteHelp(route.split() if route else []) if help_text is None: err(t help :(\n%s' % help_text
r"""Displays help for the given route. Args: route (str): A route that resolves a member.
343,824
def list_features(ctx, dataset, reverse, start, limit, output): stdout = click.open_file(output, ) service = ctx.obj.get() res = service.list_features(dataset, reverse, start, limit) if res.status_code == 200: click.echo(res.text, file=stdout) else: raise MapboxCLIException(re...
Get features of a dataset. Prints the features of the dataset as a GeoJSON feature collection. $ mapbox datasets list-features dataset-id All endpoints require authentication. An access token with `datasets:read` scope is required, see `mapbox --help`.
343,825
def set( cls, key, value, execution_date, task_id, dag_id, session=None): session.expunge_all() enable_pickling = configuration.getboolean(, ) if enable_pickling: value = pickle.dumps(value)...
Store an XCom value. TODO: "pickling" has been deprecated and JSON is preferred. "pickling" will be removed in Airflow 2.0. :return: None
343,826
def publish(self, topic, message): if not self.connections: raise NSQNoConnections() conn = random.choice(list(self.connections)) conn.publish(topic, message)
Use :class:`~gnsq.Producer` instead. .. deprecated:: 1.0.0
343,827
def _CopyTimeFromString(self, time_string): time_string_length = len(time_string) if time_string_length < 8: raise ValueError() if time_string[2] != or time_string[5] != : raise ValueError() try: hours = int(time_string[0:2], 10) except ValueError: raise ValueEr...
Copies a time from a string. Args: time_string (str): time value formatted as: hh:mm:ss.######[+-]##:## Where # are numeric digits ranging from 0 to 9 and the seconds fraction can be either 3 or 6 digits. The seconds fraction and time zone offset are optional. Re...
343,828
def create_entity(self, **kwargs): data = kwargs headers = kwargs.get(, {}) if in data: del data[] return self._create("/entities", data=data, coerce=self.get_entity, headers=headers)
kwargs expected: 'who': kwargs.get('who') 'why': kwargs.get('why') 'uri': kwargs.get('uri') 'ip_addresses': kwargs.get('ip_addresses', {}) 'label': kwargs.get('label') 'agent_id': kwargs.get('agent_id') 'metadata': kwargs.get('extra', {...
343,829
def format_close(code: int, reason: str) -> str: if 3000 <= code < 4000: explanation = "registered" elif 4000 <= code < 5000: explanation = "private use" else: explanation = CLOSE_CODES.get(code, "unknown") result = f"code = {code} ({explanation}), " if reason: ...
Display a human-readable version of the close code and reason.
343,830
def from_fs_path(path): scheme = params, query, fragment = , , path, netloc = _normalize_win_path(path) return urlunparse((scheme, netloc, path, params, query, fragment))
Returns a URI for the given filesystem path.
343,831
def get_api_docs(routes): routes = map(_get_tuple_from_route, routes) documentation = [] for url, rh, methods in sorted(routes, key=lambda a: a[0]): if issubclass(rh, APIHandler): documentation.append(_get_route_doc(url, rh, methods)) documentation = ( "**This documenta...
Generates GitHub Markdown formatted API documentation using provided schemas in RequestHandler methods and their docstrings. :type routes: [(url, RequestHandler), ...] :param routes: List of routes (this is ideally all possible routes of the app) :rtype: str :returns: generated GFM-formatt...
343,832
def _incr_counter(self, *args): if len(args) == 2: group_name, count = args print( % (group_name, count), file=sys.stderr) else: group, name, count = args print( % (group, name, count), file=sys.stderr)
Increments a Hadoop counter. Note that this seems to be a bit slow, ~1 ms Don't overuse this function by updating very frequently.
343,833
def to_python(self) -> typing.List: self.clean() result = [] for obj in self.media: if isinstance(obj, base.TelegramObject): obj = obj.to_python() result.append(obj) return result
Get object as JSON serializable :return:
343,834
def do_aprint(self, statement): self.poutput(.format(statement)) self.poutput(.format(statement.raw)) self.poutput(.format(statement.argv)) self.poutput(.format(statement.command))
Print the argument string this basic command is called with.
343,835
def stiel_thodos_dense(T, MW, Tc, Pc, Vc, Zc, Vm, kg): r gamma = 210*(Tc*MW**3./(Pc/1E5)**4)**(1/6.) rhor = Vc/Vm if rhor < 0.5: term = 1.22E-2*(exp(0.535*rhor) - 1.) elif rhor < 2: term = 1.14E-2*(exp(0.67*rhor) - 1.069) else: term = 2.60E-3*(exp(1.155*rhor) + 2...
r'''Estimates the thermal conductivity of a gas at high pressure as a function of temperature using difference method of Stiel and Thodos [1]_ as shown in [2]_. if \rho_r < 0.5: .. math:: (\lambda-\lambda^\circ)\Gamma Z_c^5=1.22\times 10^{-2} [\exp(0.535 \rho_r)-1] if 0.5 < \rho_r < 2.0: ...
343,836
def getchar(echo=False): f = _getchar if f is None: from ._termui_impl import getchar as f return f(echo)
Fetches a single character from the terminal and returns it. This will always return a unicode character and under certain rare circumstances this might return more than one character. The situations which more than one character is returned is when for whatever reason multiple characters end up in th...
343,837
def as_dotgraph(self, digraph_kwargs=None, id_prefix=None, node_formatter=None, edge_formatter=None): digraph_kwargs = digraph_kwargs or {} id_prefix = id_prefix or node_formatter = node_formatter or (lambda token: {}) edge_formatter = edge_formatter or (la...
Returns this sentence as a graphviz.Digraph. Requires the graphviz Python package and graphviz itself. There are several ways to customize. Graph level keyword arguments can be passed as a dictionary to digraph_kwargs. If you're viewing multiple Sentences in the same graph, you'll need t...
343,838
def _from_match(match): addr_beg, addr_end, r, w, x, p, offset, dev, inode, pathname = match.groups() return MemoryRegion(addr_beg=int(addr_beg, 16), addr_end=int(addr_end, 16), readable=(r == "r"), writable=(w ...
Create a MemoryRegion object from a string in the format found in /proc/$PID/maps
343,839
def re_rect(FlowRate, Width, DistCenter, Nu, openchannel): ut.check_range([FlowRate, ">0", "Flow rate"], [Nu, ">0", "Nu"]) return (4 * FlowRate * radius_hydraulic(Width, DistCenter, openchannel).magnitude / (Width * DistCenter * Nu))
Return the Reynolds Number for a rectangular channel.
343,840
def sim(src, tar, method=sim_levenshtein): if callable(method): return method(src, tar) else: raise AttributeError( + str(method))
Return a similarity of two strings. This is a generalized function for calling other similarity functions. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison method : function Specifies the similarity metric (:py:func:`si...
343,841
def get_attachments_by_name(self, name, check_regex, find_first=False): attachments = [] for part in self.mail.walk(): mail_part = MailPart(part) if mail_part.is_attachment(): found_attachment = mail_part.has_matching_name(name) if check_regex \ ...
Gets all attachments by name for the mail. :param name: The name of the attachment to look for. :type name: str :param check_regex: Checks the name for a regular expression. :type check_regex: bool :param find_first: If set to True it will only find the first match and then quit...
343,842
def translate(conic, vector): T = N.identity(len(conic)) T[:-1,-1] = -vector return conic.transform(T)
Translates a conic by a vector
343,843
def to_array(self): array = super(InlineQueryResultCachedSticker, self).to_array() array[] = u(self.type) array[] = u(self.id) array[] = u(self.sticker_file_id) if self.reply_markup is not None: array[] = self.reply_markup.to_array() if se...
Serializes this InlineQueryResultCachedSticker to a dictionary. :return: dictionary representation of this object. :rtype: dict
343,844
def purge_note(note_id, **kwargs): note_i = _get_note(note_id) db.DBSession.delete(note_i) db.DBSession.flush()
Remove a note from the DB permenantly
343,845
def build_eval_path(self, epoch, iteration): if iteration is not None: eval_fname = f else: eval_fname = f eval_path = os.path.join(self.save_path, eval_fname) return eval_path
Appends index of the current epoch and index of the current iteration to the name of the file with results. :param epoch: index of the current epoch :param iteration: index of the current iteration
343,846
def updatePollVote(self, poll_id, option_ids=[], new_options=[]): data = {"question_id": poll_id} for i, option_id in enumerate(option_ids): data["selected_options[{}]".format(i)] = option_id for i, option_text in enumerate(new_options): data["new_options[{}]"....
Updates a poll vote :param poll_id: ID of the poll to update vote :param option_ids: List of the option IDs to vote :param new_options: List of the new option names :param thread_id: User/Group ID to change status in. See :ref:`intro_threads` :param thread_type: See :ref:`intro_...
343,847
def topic_exists(name, region=None, key=None, keyid=None, profile=None): topics = list_topics(region=region, key=key, keyid=keyid, profile=profile) return name in list(topics.values() + topics.keys())
Check to see if an SNS topic exists. CLI example:: salt myminion boto3_sns.topic_exists mytopic region=us-east-1
343,848
def send_message(self, peer: Peer, text: str, reply: int=None, link_preview: bool=None, on_success: callable=None, reply_markup: botapi.ReplyMarkup=None): if isinstance(reply, Message): reply = reply.id botapi.send_message(chat_id=peer.id, text=text, disable_we...
Send message to peer. :param peer: Peer to send message to. :param text: Text to send. :param reply: Message object or message_id to reply to. :param link_preview: Whether or not to show the link preview for this message :param on_success: Callback to call when call is complete. ...
343,849
def is_dir(dirname): if not os.path.isdir(dirname): msg = "{0} is not a directory".format(dirname) raise argparse.ArgumentTypeError(msg) else: return dirname
Checks if a path is an actual directory that exists
343,850
def version(msg): tc = typecode(msg) if tc != 31: raise RuntimeError("%s: Not a status operation message, expecting TC = 31" % msg) msgbin = common.hex2bin(msg) version = common.bin2int(msgbin[72:75]) return version
ADS-B Version Args: msg (string): 28 bytes hexadecimal message string, TC = 31 Returns: int: version number
343,851
def read_epilogue(self): with open(self.filename, "rb") as fp_: fp_.seek(self.mda[]) data = np.fromfile(fp_, dtype=hrit_epilogue, count=1) self.epilogue.update(recarray2dict(data))
Read the epilogue metadata.
343,852
def _get_token(self, req): self._validate_auth_scheme(req) try: return naked(req.auth.split()[1]) except IndexError: desc = \ \ raise InvalidAuthSyntax(**{ : desc, : self._get...
Get the token from the Authorization header If the header is actually malformed where Bearer Auth was indicated by the request then an InvalidAuthSyntax exception is raised. Otherwise an AuthRequired exception since it's unclear in this scenario if the requestor was even aware A...
343,853
def random_color(_min=MIN_COLOR, _max=MAX_COLOR): return color(random.randint(_min, _max))
Returns a random color between min and max.
343,854
def fetch(self): params = values.of({}) payload = self._version.fetch( , self._uri, params=params, ) return DocumentPermissionInstance( self._version, payload, service_sid=self._solution[], doc...
Fetch a DocumentPermissionInstance :returns: Fetched DocumentPermissionInstance :rtype: twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionInstance
343,855
def reply(self, obj, result, command_exec_status=, info_messages=[], warning_messages=[], error_messages=[]): with self._connection_lock: if True: del obj[] obj[] = result obj[] = command_exec_status obj[] = inf...
Build a response from a previouslsy received command message, send it and return number of sent bytes. :param result: Used to send back the result of the command execution to the debugger client. :type result: dict See send() above for others paramete...
343,856
def patch_default_retcodes(): import luigi.retcodes retcode = luigi.retcodes.retcode retcode.already_running._default = 10 retcode.missing_data._default = 20 retcode.not_run._default = 30 retcode.task_failed._default = 40 retcode.scheduling_error._default = 50 retcode.unhandled_ex...
Sets the default luigi return codes in ``luigi.retcodes.retcode`` to: - already_running: 10 - missing_data: 20 - not_run: 30 - task_failed: 40 - scheduling_error: 50 - unhandled_exception: 60
343,857
def readProtocolVersion(self, data): data.readType(self._version) if not self._version.value in [ProtocolVersion.RFB003003, ProtocolVersion.RFB003007, ProtocolVersion.RFB003008]: self._version.value = ProtocolVersion.UNKNOWN
Read protocol version @param data: Stream may contain protocol version string (ProtocolVersion)
343,858
def ce_init(self): retval = 0.0; correct = 0; totalCount = 0 for layer in self.layers: if layer.active: if layer.type == : layer.error = self.errorFunction(layer.target, layer.activation) totalCount += layer.size ...
Initializes error computation. Calculates error for output layers and initializes hidden layer error to zero.
343,859
def find_salt_bridges(self): charge_definitions = {"ARG":"name C* and around 1.4 (name N* and not name N)", "LYS":"name N* and not name N", "HIS":"name N* and not name N", "ASP":"name C* and around 1.4 (name...
First the atom names of protein charge centers are found as these can be different in different forcefields. Then a Euclidian distance is measured between charged ligand atoms and respective inverted charge centres on protein. If the distance s lower than threshold (5.5 angstrom) the interaction is reco...
343,860
def venv_resolve_deps( deps, which, project, pre=False, clear=False, allow_global=False, pypi_mirror=None, dev=False, pipfile=None, lockfile=None, keep_outdated=False ): from .vendor.vistir.misc import fs_str from .vendor.vistir.compat import Path, JSONDecodeErr...
Resolve dependencies for a pipenv project, acts as a portal to the target environment. Regardless of whether a virtual environment is present or not, this will spawn a subproces which is isolated to the target environment and which will perform dependency resolution. This function reads the output of that...
343,861
def _adjust_n_years(other, n, month, reference_day): if n > 0: if other.month < month or (other.month == month and other.day < reference_day): n -= 1 else: if other.month > month or (other.month == month and o...
Adjust the number of times an annual offset is applied based on another date, and the reference day provided
343,862
def set_password(name, password): * s_file = ret = {} if not os.path.isfile(s_file): return ret lines = [] with salt.utils.files.fopen(s_file, ) as ifile: for line in ifile: comps = line.strip().split() if comps[0] != name: lines.append(li...
Set the password for a named user. The password must be a properly defined hash, the password hash can be generated with this command: ``openssl passwd -1 <plaintext password>`` CLI Example: .. code-block:: bash salt '*' shadow.set_password root $1$UYCIxa628.9qXjpQCjM4a..
343,863
def add_doc(self, doc): if isinstance(doc, HelloDoc) and doc.validate(): self.docs.append(doc) else: if not doc.validate(): raise Exception("HelloDoc Errors %s" % (doc.errors,)) else: raise Exception("add_doc doc must be an ins...
Simple dict of {'name': '@filename.pdf'}
343,864
def _add_value_enum(self, var, tag): if var[][0] == : numvalues_tag = etree.SubElement(tag, ) numvalues_tag.text = str(int(var[][-1][-1]) + 1) else: valueenum_tag = etree.SubElement(tag, ) valueenum_tag.text = for value in var...
supports adding variables to the xml Parameters --------------- var: The SubElement variable tag: The SubElement tag to which enum value is to be added Return --------------- None
343,865
def match(self, url: str) -> RouteResolved: url = normalize_url(url) parts = self._deconstruct_url(url) return self._match(parts)
Match a URL to a registered pattern. :param url: URL :return: Matched route :raises kua.RouteError: If there is no match
343,866
def download(date_array, tag, sat_id, data_path=None, user=None, password=None): import subprocess if user is None: print () user = if password is None: print () password = a = subprocess.check_output(["globalDownload.py", "--verbose", ...
Downloads data from Madrigal. The user's names should be provided in field user. John Malkovich should be entered as John+Malkovich The password field should be the user's email address. These parameters are passed to Madrigal when downloading. The affiliation field is set to pysat ...
343,867
def attach(cls, tuning_job_name, sagemaker_session=None, job_details=None, estimator_cls=None): sagemaker_session = sagemaker_session or Session() if job_details is None: job_details = sagemaker_session.sagemaker_client \ .describe_hyper_parameter_tuning_job(HyperPa...
Attach to an existing hyperparameter tuning job. Create a HyperparameterTuner bound to an existing hyperparameter tuning job. After attaching, if there exists a best training job (or any other completed training job), that can be deployed to create an Amazon SageMaker Endpoint and return a ``Pr...
343,868
def override_to_local_variable(enable=True): if enable: def custom_getter(getter, name, *args, **kwargs): _replace_global_by_local(kwargs) return getter(name, *args, **kwargs) with custom_getter_scope(custom_getter): yield else: yield
Returns: a context where all variables will be created as local.
343,869
def get_config(section, option, allow_empty_option=True, default=""): try: value = config.get(section, option) if value is None or len(value) == 0: if allow_empty_option: return "" else: return default else: return valu...
Get data from configs
343,870
def model_constructors(vk, model): model[] = [] structs = [x for x in vk[][][] if x.get() in {, }] def parse_len(member): mlen = member.get() if not mlen: return None if in mlen: mlen = mlen.split()[0] if in mlen or in mlen: ...
Fill the model with constructors model['constructors'] = [{'name': 'x', 'members': [{'name': 'y'}].}]
343,871
def check_wlcalib_sp(sp, crpix1, crval1, cdelt1, wv_master, coeff_ini=None, naxis1_ini=None, min_nlines_to_refine=0, interactive=False, threshold=0, nwinwidth_initial=7, nwinwidth_refined=5, ...
Check wavelength calibration of the provided spectrum. Parameters ---------- sp : numpy array Wavelength calibrated spectrum. crpix1: float CRPIX1 keyword. crval1: float CRVAL1 keyword. cdelt1: float CDELT1 keyword. wv_master: numpy array Array with t...
343,872
def drawRoundRect(self, x, y, w, h, r, color=None, aa=False): md.draw_round_rect(self.set, x, y, w, h, r, color, aa)
Draw a rounded rectangle with top-left corner at (x, y), width w, height h, and corner radius r :param aa: if True, use Bresenham's algorithm for line drawing; otherwise use Xiaolin Wu's algorithm
343,873
def signup(request): if request.method == : return render(request, , {}, help_text=signup.__doc__) elif request.method == : if request.user.is_authenticated() and hasattr(request.user, "userprofile"): return render_json(request, { : _(), : ...
Create a new user with the given credentials. GET parameters: html turn on the HTML version of the API POST parameters (JSON): username: user's name email: user's e-mail password: user's password password_check: ...
343,874
def write(entries): try: with open(get_rc_path(), ) as rc: rc.writelines(entries) except IOError: print()
Write an entire rc file.
343,875
def get_owasp_top_10_url(owasp_version, risk_id): owasp_version = int(owasp_version) if owasp_version == 2013: return OWASP_TOP10_2013_URL_FMT % risk_id if owasp_version == 2010: return OWASP_TOP10_2010_URL_FMT % risk_id
Similar to get_wasc_url() but for OWASP Top 10
343,876
def marshmallow_loader(schema_class): def json_loader(): request_json = request.get_json() context = {} pid_data = request.view_args.get() if pid_data: pid, _ = pid_data.data context[] = pid result = schema_class(context=context).load(request_js...
Marshmallow loader for JSON requests.
343,877
def decompress(self, value): if value: try: pk = self.queryset.get(recurrence_rule=value).pk except self.queryset.model.DoesNotExist: pk = None return [pk, None, value] return [None, None, None]
Return the primary key value for the ``Select`` widget if the given recurrence rule exists in the queryset.
343,878
def chroma(chromagram, times, fs, **kwargs): n_octaves = 7 base_note = 24 mean = 72 std = 6 notes = np.arange(12*n_octaves) + base_note shepard_weight = np.exp(-(notes - mean)**2./(2.*std**2.)) gram = np.tile(chromagram.T, n_octaves).T gram = ...
Reverse synthesis of a chromagram (semitone matrix) Parameters ---------- chromagram : np.ndarray, shape=(12, times.shape[0]) Chromagram matrix, where each row represents a semitone [C->Bb] i.e., ``chromagram[3, j]`` is the magnitude of D# from ``times[j]`` to ``times[j + 1]`` t...
343,879
def cprint( text, fg=Color.normal, bg=Color.normal, fg_dark=False, bg_dark=False, underlined=False, parse=False, ): if parse: color_re = Color.color_re() lines = text.splitlines() count = len(lines) for i, line in enumerate(lines): ...
Print string in to stdout using colored font. See L{set_color} for more details about colors. Args: text (str): Text that needs to be printed.
343,880
def set_stream_id(self, stream_id): stream_id = validate_type(stream_id, type(None), *six.string_types) if stream_id is not None: stream_id = stream_id.lstrip() self._stream_id = stream_id
Set the stream id associated with this data point
343,881
def add_choice(self, text, name=, identifier=None): if not utilities.is_string(text): raise InvalidArgument() choice_display_text = self._choice_text_metadata[][0] choice_display_text[] = text if identifier is None: identifier = str(ObjectId()) ch...
stub
343,882
async def read_portrait_landscape(self, callback=None): register = self.MMA8452Q_Register[] await self.board.i2c_read_request(self.address, register, 1, Constants.I2C_READ | Constants.I2C_END_TX_MASK, ...
This function reads the portrait/landscape status register of the MMA8452Q. It will return either PORTRAIT_U, PORTRAIT_D, LANDSCAPE_R, LANDSCAPE_L, or LOCKOUT. LOCKOUT indicates that the sensor is in neither p or ls. :param callback: Callback function :returns: See above.
343,883
def _psql_cmd(*args, **kwargs): (user, host, port, maintenance_db) = _connection_defaults( kwargs.get(), kwargs.get(), kwargs.get(), kwargs.get()) _PSQL_BIN = _find_pg_binary() cmd = [_PSQL_BIN, , , , ] if user: c...
Return string with fully composed psql command. Accepts optional keyword arguments: user, host, port and maintenance_db, as well as any number of positional arguments to be added to the end of the command.
343,884
def hacking_has_correct_license(physical_line, filename, lines, line_number): return (column, "H103: Header does not match Apache 2.0 " "License notice")
Check for Apache 2.0 license. H103 header does not match Apache 2.0 License notice
343,885
def edit(self, typeValue, connectionString, move=True, runAsync=False): url = self._url + "/edit" params = { "f" : "json", "type" : typeValue, "connectionString" : connectionString, "move" : move, ...
You can use this operation to update the configuration store. Typically, this operation is used to change the location of the store. When ArcGIS Server is installed, the default configuration store uses local paths. As the site grows (more server machines are added), the location...
343,886
def image_get_root_disk_size(self, image_name): image_info = self.image_query(image_name) if not image_info: raise exception.SDKImageOperationError(rs=20, img=image_name) disk_size_units = image_info[0][].split()[0] return disk_size_units
Return the root disk units of the specified image image_name: the unique image name in db Return the disk units in format like 3339:CYL or 467200:BLK
343,887
def update_actualremoterelieve_v1(self): con = self.parameters.control.fastaccess der = self.parameters.derived.fastaccess flu = self.sequences.fluxes.fastaccess d_smooth = der.highestremotesmoothpar d_highest = con.highestremotedischarge d_value = smoothutils.smooth_min1( flu.actua...
Constrain the actual relieve discharge to a remote location. Required control parameter: |HighestRemoteDischarge| Required derived parameter: |HighestRemoteSmoothPar| Updated flux sequence: |ActualRemoteRelieve| Basic equation - discontinous: :math:`ActualRemoteRelieve = min(...
343,888
def clear(self, flush=True): if self.enabled: self.manager.write(flush=flush, position=self.position)
Args: flush(bool): Flush stream after clearing progress bar (Default:True) Clear progress bar
343,889
def get_descendants(self): return self.__class__.get_tree(self).exclude(pk=self.pk)
:returns: A queryset of all the node's descendants as DFS, doesn't include the node itself
343,890
def display_video_hooks(hook_args): predictions = hook_args.predictions max_outputs = hook_args.decode_hparams.max_display_outputs max_decodes = hook_args.decode_hparams.max_display_decodes with tf.Graph().as_default(): _, best_decodes = video_metrics.compute_video_metrics_from_predictions( pred...
Hooks to display videos at decode time.
343,891
def executeSQL(self, sql, args=()): sql = self._execSQL(sql, args) result = self.cursor.lastRowID() if self.executedThisTransaction is not None: self.executedThisTransaction.append((result, sql, args)) return result
For use with UPDATE or INSERT statements.
343,892
def get_fields_dict(self): fields = [] for field_name in self.model_admin.get_inspect_view_fields(): fields.append(self.get_dict_for_field(field_name)) return fields
Return a list of `label`/`value` dictionaries to represent the fiels named by the model_admin class's `get_inspect_view_fields` method
343,893
def cellCenters(self): vcen = vtk.vtkCellCenters() vcen.SetInputData(self.polydata(True)) vcen.Update() return vtk_to_numpy(vcen.GetOutput().GetPoints().GetData())
Get the list of cell centers of the mesh surface. .. hint:: |delaunay2d| |delaunay2d.py|_
343,894
def __update_order_seed(self, optic_descriptor, neighbors_descriptors, order_seed): for neighbor_descriptor in neighbors_descriptors: index_neighbor = neighbor_descriptor[0] current_reachable_distance = neighbor_descriptor[1] if self.__op...
! @brief Update sorted list of reachable objects (from core-object) that should be processed using neighbors of core-object. @param[in] optic_descriptor (optics_descriptor): Core-object whose neighbors should be analysed. @param[in] neighbors_descriptors (list): List of neighbors of...
343,895
def time(hour, minute=0, second=0, microsecond=0): return Time(hour, minute, second, microsecond)
Create a new Time instance.
343,896
def combine_adjacent_lines(line_numbers): combine_template = "{0}-{1}" combined_list = [] line_numbers.append(None) start = line_numbers[0] end = None for line_number in line_numbers[1:]: if (end if end else start) + 1 == line_...
Given a sorted collection of line numbers this will turn them to strings and combine adjacent values [1, 2, 5, 6, 100] -> ["1-2", "5-6", "100"]
343,897
def upload_to_s3(file_path, config): logging.info("Uploading file to S3 bucket: %s", config[]) s3 = boto3.resource() s3_filename = config[] + config[] s3.Bucket(config[]).upload_file( file_path, s3_filename, ExtraArgs={ : , : })
Upload html file to S3
343,898
def _indent(x): lines = x.splitlines() for i, line in enumerate(lines): lines[i] = + line return .join(lines)
Indent a string by 4 characters.
343,899
def init_dict(data, index, columns, dtype=None): if columns is not None: from pandas.core.series import Series arrays = Series(data, index=columns, dtype=object) data_names = arrays.index missing = arrays.isnull() if index is None: ...
Segregate Series based on type and coerce into matrices. Needs to handle a lot of exceptional cases.