Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
339,100
def import_graph(self, t_input=None, scope=, forget_xy_shape=True): graph = tf.get_default_graph() assert graph.unique_name(scope, False) == scope, ( ) % scope t_input, t_prep_input = self.create_input(t_input, forget_xy_shape) tf.import_graph_def( self.graph_def, {self.inp...
Import model GraphDef into the current graph.
339,101
def file_exists(self) -> bool: cfg_path = self.file_path assert cfg_path return path.isfile(cfg_path)
Check if the settings file exists or not
339,102
def _vard(ins): output = [] output.append( % ins.quad[1]) q = eval(ins.quad[2]) for x in q: if x[0] == : size_t = if x[1] == else output.append(.format(size_t, x.lstrip())) continue x = x.upper() assert RE_HEXA.match(x), ...
Defines a memory space with a default set of bytes/words in hexadecimal (starting with a number) or literals (starting with #). Numeric values with more than 2 digits represents a WORD (2 bytes) value. E.g. '01' => 0, '001' => 1, 0 bytes Literal values starts with # (1 byte) or ## (2 bytes) E.g. '#l...
339,103
def _update_from_globals(xtag, xmlglobals, container): for child in list(xtag): _update_from_globals(child, xmlglobals, xtag) if container is None: return def update_tag(xtag, gtag): for attr, value in gtag.attr.items...
Updates the attributes of the specified XML tag using the globals dictionary for those tags that are supported.
339,104
def get_category(self, metric): tags = .join( % (k, v) for k, v in sorted(metric.metric_name.tags.items())) return .join(x for x in [self._prefix, metric.metric_name.group, tags] if x)
Return a string category for the metric. The category is made up of this reporter's prefix and the metric's group and tags. Examples: prefix = 'foo', group = 'bar', tags = {'a': 1, 'b': 2} returns: 'foo.bar.a=1,b=2' prefix = 'foo', group = 'bar', tags = Non...
339,105
def get_store_credit_transaction_by_id(cls, store_credit_transaction_id, **kwargs): kwargs[] = True if kwargs.get(): return cls._get_store_credit_transaction_by_id_with_http_info(store_credit_transaction_id, **kwargs) else: (data) = cls._get_store_credit_transact...
Find StoreCreditTransaction Return single instance of StoreCreditTransaction by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_store_credit_transaction_by_id(store_credit_transaction_id, ...
339,106
def plantuml(desc): classes, relations, inherits = desc result = [ , , ] for cls in classes: class_desc = [] class_desc += [(i[1], i[0]) for i in cls[]] class_desc += [(, i) for i in cls[]] cla...
Generate plantuml class diagram :param desc: result of sadisplay.describe function Return plantuml class diagram string
339,107
def _cachedSqlType(cls): if not hasattr(cls, "_cached_sql_type"): cls._cached_sql_type = cls.sqlType() return cls._cached_sql_type
Cache the sqlType() into class, because it's heavy used in `toInternal`.
339,108
def get_free_tcp_port(self, project, port_range_start=None, port_range_end=None): if port_range_start is None and port_range_end is None: port_range_start = self._console_port_range[0] port_range_end = self._console_port_range[1] port = self.find_unused_port(p...
Get an available TCP port and reserve it :param project: Project instance
339,109
def nextCmd(snmpEngine, authData, transportTarget, contextData, *varBinds, **options): def __cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): lookupMib, deferred = cbCtx if (options.get(, False) an...
Performs SNMP GETNEXT query. Based on passed parameters, prepares SNMP GETNEXT packet (:RFC:`1905#section-4.2.2`) and schedules its transmission by :mod:`twisted` I/O framework at a later point of time. Parameters ---------- snmpEngine : :class:`~pysnmp.hlapi.SnmpEngine` Class instance...
339,110
def get_bin_indices(self, values): return tuple([self.get_axis_bin_index(values[ax_i], ax_i) for ax_i in range(self.dimensions)])
Returns index tuple in histogram of bin which contains value
339,111
def create_heroku_connect_schema(using=DEFAULT_DB_ALIAS): connection = connections[using] with connection.cursor() as cursor: cursor.execute(_SCHEMA_EXISTS_QUERY, [settings.HEROKU_CONNECT_SCHEMA]) schema_exists = cursor.fetchone()[0] if schema_exists: return False ...
Create Heroku Connect schema. Note: This function is only meant to be used for local development. In a production environment the schema will be created by Heroku Connect. Args: using (str): Alias for database connection. Returns: bool: ``True`` if the schema was c...
339,112
def format_action(nonterminal: str, right_hand_side: str, is_string: bool = False, is_number: bool = False, keywords_to_uppercase: List[str] = None) -> str: keywords_to_uppercase = keywords_to_uppercase or [] if right_hand_side.upper()...
This function formats an action as it appears in models. It splits productions based on the special `ws` and `wsp` rules, which are used in grammars to denote whitespace, and then rejoins these tokens a formatted, comma separated list. Importantly, note that it `does not` split on spaces in the gram...
339,113
def process_log_event(event, context): init() serialized = event[].pop() data = json.loads(zlib.decompress( base64.b64decode(serialized), 16 + zlib.MAX_WBITS)) timestamps = [e[] for e in data[]] start = min(timestamps) - 1000 * 15 end = max(timestamps) + 1000 * 5 events =...
Format log events and relay via sns/email
339,114
def validateField(cls, fieldName, value) : try : valValue = Collection.validateField(fieldName, value) except SchemaViolation as e: if fieldName == "_from" or fieldName == "_to" : return True else : raise e return valVa...
checks if 'value' is valid for field 'fieldName'. If the validation is unsuccessful, raises a SchemaViolation or a ValidationError. for nested dicts ex: {address : { street: xxx} }, fieldName can take the form address.street
339,115
def get_precinctsreportingpct(self, obj): if obj.division.level == \ obj.candidate_election.election.division.level: return obj.candidate_election.election.meta.precincts_reporting_pct return None
Precincts reporting percent if vote is top level result else ``None``.
339,116
def set_def_acl(self, acl_or_str, key_name=, headers=None): if isinstance(acl_or_str, Policy): raise InvalidAclError() elif isinstance(acl_or_str, ACL): self.set_def_xml_acl(acl_or_str.to_xml(), key_name, headers=headers) else: self.set_def_canned_acl...
sets or changes a bucket's default object acl
339,117
def handle_error(self, failure): self.logger.error(repr(failure)) if failure.check(HttpError): response = failure.value.response self.logger.error(u, response.url) self.logger.error(u, response.status) if response.status in (401, 403): ...
Provides basic error information for bad requests. If the error was an HttpError or DNSLookupError, it prints more specific information.
339,118
def ip_acl_ip_access_list_standard_hide_ip_acl_std_seq_action(self, **kwargs): config = ET.Element("config") ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list") ip = ET.SubElement(ip_acl, "ip") access_list = ET.SubElement(ip, "access-lis...
Auto Generated Code
339,119
def get_new_driver(self, browser=None, headless=None, servername=None, port=None, proxy=None, agent=None, switch_to=True, cap_file=None, disable_csp=None): if self.browser == "remote" and self.servername == "localhost": raise Exception( ...
This method spins up an extra browser for tests that require more than one. The first browser is already provided by tests that import base_case.BaseCase from seleniumbase. If parameters aren't specified, the method uses the same as the default driver. @Params ...
339,120
def update_list_widget(self): radio_button_checked_id = self.input_button_group.checkedId() if radio_button_checked_id > -1: selected_dict = list(self._parameter.options.values())[ radio_button_checked_id] if selected_dict.get() == MULTI...
Update list widget when radio button is clicked.
339,121
def VORPS(cpu, dest, src, src2): res = dest.write(src.read() | src2.read())
Performs a bitwise logical OR operation on the source operand (second operand) and second source operand (third operand) and stores the result in the destination operand (first operand).
339,122
def update_global_variables_list_store(self): self.list_store_iterators = {} self.list_store.clear() keys = self.model.global_variable_manager.get_all_keys() keys.sort() for key in keys: iter = self.list_store.append([key, ...
Updates the global variable list store Triggered after creation or deletion of a variable has taken place.
339,123
def _format_pair_with_equals(explode, separator, escape, key, value): if not value: return key + return _format_pair(explode, separator, escape, key, value)
Format a key, value pair including the equals sign when there is no value
339,124
def get_interface_detail_output_interface_port_role(self, **kwargs): config = ET.Element("config") get_interface_detail = ET.Element("get_interface_detail") config = get_interface_detail output = ET.SubElement(get_interface_detail, "output") interface = ET.SubElement(out...
Auto Generated Code
339,125
def print_wordfreq(freqs, n=10): words, counts = freqs.keys(), freqs.values() items = zip(counts, words) items.sort(reverse=True) for (count, word) in items[:n]: print(word, count)
Print the n most common words and counts in the freqs dict.
339,126
def pattern_from_template(templates, name): if name not in templates: echo("No template named \"%s\"" % name) sys.exit(1) return templates[name]
Return pattern for name Arguments: templates (dict): Current templates name (str): Name of name
339,127
def remove(module, details=False): t actually support "uninstall"-like functionality, this function will attempt to do what it can, with what it has from CPAN. Until this function is declared stable, USE AT YOUR OWN RISK! CLI Example: .. code-block:: bash salt cpan.remove Old::Package ...
Attempt to remove a Perl module that was installed from CPAN. Because the ``cpan`` command doesn't actually support "uninstall"-like functionality, this function will attempt to do what it can, with what it has from CPAN. Until this function is declared stable, USE AT YOUR OWN RISK! CLI Example: ...
339,128
def begin(self): return Range(self.source_buffer, self.begin_pos, self.begin_pos, expanded_from=self.expanded_from)
Returns a zero-length range located just before the beginning of this range.
339,129
def parse_sql(self, asql): import sqlparse statements = sqlparse.parse(sqlparse.format(asql, strip_comments=True)) parsed_statements = [] for statement in statements: statement_str = statement.to_unicode().strip() for preprocessor in self._backend.sql_...
Executes all sql statements from asql. Args: library (library.Library): asql (str): ambry sql query - see https://github.com/CivicKnowledge/ambry/issues/140 for details.
339,130
def get(self, name=None): return self.__app.recipes.get(name, self._plugin)
Gets a list of all recipes, which are registered by the current plugin. If a name is provided, only the requested recipe is returned or None. :param: name: Name of the recipe
339,131
def writePatternLine(self, step_milliseconds, color, pos, led_number=0): if ( self.dev == None ): return self.setLedN(led_number) red, green, blue = self.color_to_rgb(color) r, g, b = self.cc(red, green, blue) step_time = int(step_milliseconds / 10) th = (step_t...
Write a color & step time color pattern line to RAM :param step_milliseconds: how long for this pattern line to take :param color: LED color :param pos: color pattern line number (0-15) :param led_number: LED to adjust, 0=all, 1=LEDA, 2=LEDB
339,132
def get_roles(username): * info = sendline(.format(username)) roles = re.search(r, info, re.MULTILINE) if roles: roles = roles.group(1).strip().split() else: roles = [] return roles
Get roles that the username is assigned from switch .. code-block: bash salt '*' onyx.cmd get_roles username=admin
339,133
def _get_request_args(method, **kwargs): args = [ (, api_key), (, ), (, method), (, ), ] if kwargs: for key, value in kwargs.iteritems(): args.append((key, value)) args.sort(key=lambda tup: tup[0]) api_sig = _get_api_sig(args) args.append(...
Use `method` and other settings to produce a flickr API arguments. Here also use json as the return type. :param method: The method provided by flickr, ex: flickr.photosets.getPhotos :type method: str :param kwargs: Other settings :type kwargs: dict :return: An argument list used fo...
339,134
def strsplit(self, pattern): fr = H2OFrame._expr(expr=ExprNode("strsplit", self, pattern)) fr._ex._cache.nrows = self.nrow return fr
Split the strings in the target column on the given regular expression pattern. :param str pattern: The split pattern. :returns: H2OFrame containing columns of the split strings.
339,135
def _refreshNodeFromTarget(self): tableModel = self.tableInspector.model if tableModel.rowCount() >= RESET_HEADERS_AT_SIZE: self.autoRowHeightCti.data = False self.model.emitDataChanged(self.autoRowHeightCti) self.autoRowHeightCti.enable = False ...
Refreshes the TableInspectorCti from the TableInspector target it monitors. Disables auto-sizing of the header sizes for very large headers (> 10000 elements). Otherwise the resizing may take to long and the program will hang.
339,136
def postprocess_html(html, metadata): if metadata.get() and metadata[] == : html = html.replace(, ) html = html.replace(, ) return html
Returns processed HTML to fit into the slide template format.
339,137
def fit_transform(self, data: List[str]) -> List[List[int]]: tokenized_data = self.fit(data, return_tokenized_data=True) logging.warning(f) now = get_time() indexed_data = self.indexer.tokenized_texts_to_sequences(tokenized_data) logging.warning(f)...
Apply cleaner and tokenzier to raw data, build vocabulary and return transfomred dataset that is a List[List[int]]. This will use process-based-threading on all available cores. ex: >>> data = [["The quick brown fox"], ["jumps over the lazy dog"]] >>> pp = preprocess(maxlen=5, ...
339,138
def _blend_layers(self, imagecontent, z_x_y): (z, x, y) = z_x_y result = self._tile_image(imagecontent) for (layer, opacity) in self._layers: try: overlay = self._tile_image(layer.tile((z, x, y))) except (IOError, Downloa...
Merge tiles of all layers into the specified tile path
339,139
def format_keyval_to_metadata(keytype, scheme, key_value, private=False): securesystemslib.formats.KEYTYPE_SCHEMA.check_match(keytype) securesystemslib.formats.SCHEME_SCHEMA.check_match(scheme) securesystemslib.formats.KEYVAL_SCHEMA.check_match(key_value) if private is True: ...
<Purpose> Return a dictionary conformant to 'securesystemslib.formats.KEY_SCHEMA'. If 'private' is True, include the private key. The dictionary returned has the form: {'keytype': keytype, 'scheme' : scheme, 'keyval': {'public': '...', 'private': '...'}} or if 'private' ...
339,140
def gold_parameter(time_residual): gold = np.exp(-1 * time_residual * time_residual / (2 * 1.5 * 1.5)) / len(time_residual) gold = np.sum(gold)
stolen from thomas
339,141
def set_keep_alive(self, sock, after_idle_sec=5, interval_sec=60, max_fails=5): if platform.system() == "Darwin": TCP_KEEPALIVE = 0x10 sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) sock.setsockopt(socket.IPPR...
This function instructs the TCP socket to send a heart beat every n seconds to detect dead connections. It's the TCP equivalent of the IRC ping-pong protocol and allows for better cleanup / detection of dead TCP connections. It activates after 1 second (after_idle_sec) of idleness, then...
339,142
def create_marker(self, category, start, finish, marker=None, **kwargs): kwargs = kwargs if marker is None else marker if category not in self._categories: raise ValueError("category argument not a valid category: {}".format(category)) if start < self._start or finish > self...
Create a new marker in the TimeLine with the specified options :param category: Category identifier, key as given in categories dictionary upon initialization :type category: Any :param start: Start time for the marker :type start: float :param finish: Finish time fo...
339,143
def parse_csv(file_stream, expected_columns=None): reader = unicodecsv.DictReader(file_stream, encoding="utf-8") if expected_columns and set(expected_columns) - set(reader.fieldnames): raise ValidationError(ValidationMessages.MISSING_EXPECTED_COLUMNS.format( expected_columns=", ".join(...
Parse csv file and return a stream of dictionaries representing each row. First line of CSV file must contain column headers. Arguments: file_stream: input file expected_columns (set[unicode]): columns that are expected to be present Yields: dict: CSV line parsed into a dictiona...
339,144
def hostgroup_get(name=None, groupids=None, hostids=None, **kwargs): s docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see modules docstring) :return: Array with host groups details, False if no convenient host group found or on failure. CLI Examp...
.. versionadded:: 2016.3.0 Retrieve host groups according to the given parameters .. note:: This function accepts all standard hostgroup.get properities: keyword argument names differ depending on your zabbix version, see here__. .. __: https://www.zabbix.com/documentation/2.2/manual/...
339,145
def build_query(self, sql, lookup): for key, val in six.iteritems(lookup): sql = sql.replace("$" + key, val) return sql
Modify table and field name variables in a sql string with a dict. This seems to be discouraged by psycopg2 docs but it makes small adjustments to large sql strings much easier, making prepped queries much more versatile. USAGE sql = 'SELECT $myInputField FROM $myInputTable' ...
339,146
def AgregarItemDetalleAjuste(self, nro_item_ajustar, **kwargs): "Agrega el detalle de item a un ajuste de liquidación" d = {: nro_item_ajustar, : []} self.solicitud[].append(d) return True
Agrega el detalle de item a un ajuste de liquidación
339,147
def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width): if width < 1: space_left = 1 else: space_left = width - cur_len elif not cur_line: cur_line.append(reversed_chunks.pop())
_handle_long_word(chunks : [string], cur_line : [string], cur_len : int, width : int) Handle a chunk of text (most likely a word, not whitespace) that is too long to fit in any line.
339,148
def timeit(stat_tracker_func, name): def _timeit(func): def wrapper(*args, **kw): start_time = time.time() result = func(*args, **kw) stop_time = time.time() stat_tracker_func(name, stop_time - start_time) return result return wrapper...
Pass in a function and the name of the stat Will time the function that this is a decorator to and send the `name` as well as the value (in seconds) to `stat_tracker_func` `stat_tracker_func` can be used to either print out the data or save it
339,149
def get(self): if isinstance(self.red, SoftInt): red = self.red.get() else: red = self.red if isinstance(self.green, SoftInt): green = self.green.get() else: green = self.green if isinstance(self.blue, SoftInt): ...
Get an rgb color tuple according to the probability distribution. Returns: tuple(int, int, int): A ``(red, green, blue)`` tuple. Example: >>> color = SoftColor(([(0, 1), (255, 10)],), ... ([(0, 1), (255, 10)],), ... ([...
339,150
def reverse_transform(self, col): output = pd.DataFrame() output[self.col_name] = self.get_category(col[self.col_name]) return output
Converts data back into original format. Args: col(pandas.DataFrame): Data to transform. Returns: pandas.DataFrame
339,151
def set_api_server_info(host=None, port=None, protocol=None): global APISERVER_PROTOCOL, APISERVER_HOST, APISERVER_PORT, APISERVER if host is not None: APISERVER_HOST = host if port is not None: APISERVER_PORT = port if protocol is not None: APISERVER_PROTOCOL = protocol ...
:param host: API server hostname :type host: string :param port: API server port. If not specified, *port* is guessed based on *protocol*. :type port: string :param protocol: Either "http" or "https" :type protocol: string Overrides the current settings for which API server to communicate w...
339,152
def Sx(mt, x): n = len(mt.Nx) sum1 = 0 for j in range(x, n): k = mt.Nx[j] sum1 += k return sum1
Return the Sx
339,153
def get_ms_item(xml, service, parent_id): cls = MS_TYPE_TO_CLASS.get(xml.findtext(ns_tag(, ))) out = cls.from_xml(xml, service, parent_id) return out
Return the music service item that corresponds to xml. The class is identified by getting the type from the 'itemType' tag
339,154
def discover_handler_classes(handlers_package): if handlers_package is None: return sys.path.insert(0, os.getcwd()) package = import_module(handlers_package) if hasattr(package, ): for _, modname, _ in pkgutil.iter_modules(package.__path__): import_module(.f...
Looks for handler classes within handler path module. Currently it's not looking deep into nested module. :param handlers_package: module path to handlers :type handlers_package: string :return: list of handler classes
339,155
def error(self, msg, *args, **kwargs) -> Task: return self._make_log_task(logging.ERROR, msg, args, **kwargs)
Log msg with severity 'ERROR'. To pass exception information, use the keyword argument exc_info with a true value, e.g. await logger.error("Houston, we have a major problem", exc_info=1)
339,156
def get_flag_status(self, name): f = self.get_flags(name) if not f: return None assert len(f) <= 1 return f[0][]
Return a flag 'status' field This method works only for simple flags that have only a 'status' field with no "requestee" info, and no multiple values. For more complex flags, use get_flags() to get extended flag value information.
339,157
def check_for_invalid_columns(problems, table, df): r = cs.PROTOFEED_REF valid_columns = r.loc[r[] == table, ].values for col in df.columns: if col not in valid_columns: problems.append([, .format(col), table, []]) return problems
Check for invalid columns in the given ProtoFeed DataFrame. Parameters ---------- problems : list A four-tuple containing 1. A problem type (string) equal to ``'error'`` or ``'warning'``; ``'error'`` means the ProtoFeed is violated; ``'warning'`` means ther...
339,158
def _set_id_variable_by_entity_key(self) -> Dict[str, str]: if self.id_variable_by_entity_key is None: self.id_variable_by_entity_key = dict( (entity.key, entity.key + ) for entity in self.tax_benefit_system.entities) log.debug("Use default id_variable names:\n ...
Identify and set the good ids for the different entities
339,159
def TimeFromTicks(ticks, tz=None): dt = datetime.datetime.fromtimestamp(ticks, tz=tz) return dt.timetz()
Construct a DB-API time value from the given ticks value. :type ticks: float :param ticks: a number of seconds since the epoch; see the documentation of the standard Python time module for details. :type tz: :class:`datetime.tzinfo` :param tz: (Optional) time zone to use for conversion...
339,160
def root(): logger.debug() old_euid = os.geteuid() os.seteuid(0) yield os.seteuid(old_euid) logger.debug()
Run the enclosed code as root (uid 0) Usage: with root(): ...
339,161
def checkstyle(self, sources): failure_count = 0 for filename in sources: failure_count += self._check_file(filename) return failure_count
Iterate over sources and run checker on each file. Files can be suppressed with a --suppress option which takes an xml file containing file paths that have exceptions and the plugins they need to ignore. :param sources: iterable containing source file names. :return: (int) number of failures
339,162
def _g(self, x, tau): return tau ** 2 * (tau ** 2 + 1) ** -2 * ( (tau ** 2 + 1 + 2 * (x ** 2 - 1)) * self.F(x) + tau * np.pi + (tau ** 2 - 1) * np.log(tau) + np.sqrt(tau ** 2 + x ** 2) * (-np.pi + self.L(x, tau) * (tau ** 2 - 1) * tau ** -1))
analytic solution of integral for NFW profile to compute deflection angel and gamma :param x: R/Rs :type x: float >0
339,163
def save_token(self, access_token): self.access_tokens[access_token.token] = access_token unique_token_key = self._unique_token_key(access_token.client_id, access_token.grant_type, access_token....
Stores an access token and additional data in memory. :param access_token: An instance of :class:`oauth2.datatype.AccessToken`.
339,164
def rebuild(self, **kwargs): t really ever be needed. ' self.nodes = [] self.node_types = [] self.id_dict = {} self.type_dict = {} self.add_node(self.root)
Repopulate the node-tracking data structures. Shouldn't really ever be needed.
339,165
def bulk_index(cls, documents, id_field=, es=None, index=None): if es is None: es = cls.get_es() if index is None: index = cls.get_index() documents = (dict(d, _id=d[id_field]) for d in documents) bulk_index( es, documents, ...
Adds or updates a batch of documents. :arg documents: List of Python dicts representing individual documents to be added to the index .. Note:: This must be serializable into JSON. :arg id_field: The name of the field to use as the document id. This...
339,166
def dn(self,x,M_change = 12): y = signal.lfilter(self.b,[1],x) y = ssd.downsample(y,M_change) return y
Downsample and filter the signal
339,167
def port_profile_vlan_profile_switchport_access_mac_group_vlan_classification_access_vlan_access_mac_group(self, **kwargs): config = ET.Element("config") port_profile = ET.SubElement(config, "port-profile", xmlns="urn:brocade.com:mgmt:brocade-port-profile") name_key = ET.SubElement(port...
Auto Generated Code
339,168
def from_json(cls, data, result=None): if data.get("type") != cls._type_value: raise exception.ElementDataWrongType( type_expected=cls._type_value, type_provided=data.get("type") ) tags = data.get("tags", {}) way_id = data.get("i...
Create new Way element from JSON data :param data: Element data from JSON :type data: Dict :param result: The result this element belongs to :type result: overpy.Result :return: New instance of Way :rtype: overpy.Way :raises overpy.exception.ElementDataWrongType:...
339,169
def generate_table(self): gso_table = self._gso_table gso_df = self.df columns = list(gso_df.columns) selected = gso_df[self.columns] col_index = [(col, columns.index(col)) for col in self.columns] keys = np.empty(selected.shape, dtype=np.uint64) for o, ...
Generates the GSO lookup table for the DataFRame Returns ------- gso_table : OrderedDict Ordered dictionary using the string found as keys and their lookup position (v,o) as values gso_df : DataFrame DataFrame where strl columns have been converted to...
339,170
def verifyArguments(self, arg): for l in arg: if not type(l) == list and \ not type(l) == type(Numeric.array([0.0])) and \ not type(l) == tuple and \ not type(l) == dict: return 0 if type(l) == dict: fo...
Verifies that arguments to setInputs and setTargets are appropriately formatted.
339,171
def recall_checksum(self, cache_file): checksum_file = % cache_file try: with open(checksum_file) as handle: contents = handle.read() return contents.strip() except IOError as e: if e.errno == errno.ENOENT: ...
Get the checksum of the input used to generate a binary distribution archive. :param cache_file: The pathname of the binary distribution archive (a string). :returns: The checksum (a string) or :data:`None` (when no checksum is available).
339,172
def s3_get_dir_backup(aws_access_key_id, aws_secret_access_key, bucket_name, s3_folder, zip_backups_dir, project): matches = [] pat = dir_zip_pat % project print( % (pat, bucket_name)) bucket = s3_bucket(aws_access_key_id, aws_secret_access_key, bucket_name) bucketlist = bucket.list() for ...
get last uploaded directory backup :param aws_access_key_id: :param aws_secret_access_key: :param bucket_name: :param s3_folder: :param zip_backups_dir: :param project: :return:
339,173
def send_command( self, command_string, expect_string=None, delay_factor=1, max_loops=500, auto_find_prompt=True, strip_prompt=True, strip_command=True, normalize=True, use_textfsm=False, ): loop_delay = 0.2 ...
Execute command_string on the SSH channel using a pattern-based mechanism. Generally used for show commands. By default this method will keep waiting to receive data until the network device prompt is detected. The current network device prompt will be determined automatically. :param c...
339,174
def clear(self): for root, dirs, files in os.walk(self._root_dir, topdown=False): for file in files: os.unlink(os.path.join(root, file)) os.rmdir(root) root_dir = os.path.abspath( os.path.join(self._root_dir, os.pardir)) self....
Clears all data from the data store permanently
339,175
def _sortObjects(orderby=, **kwargs): o = [] for m in kwargs.values(): for l in iter(m): o.append(l) o = list(set(o)) sortfunc = _sortByCreated if orderby == else _sortByModified if six.PY2: o.sort(sortfunc) else: o.sort(key=functools.cmp_to_key(sor...
Sorts lists of objects and combines them into a single list
339,176
def _parseupload(self, node): if not isinstance(node,ElementTree._Element): try: node = clam.common.data.parsexmlstring(node) except: raise Exception(node) if node.tag != : raise Exception("Not a valid CLAM upload response") ...
Parse CLAM Upload XML Responses. For internal use
339,177
async def read(self, keys: List[str]) -> dict: try: if not self.__container_exists: self.__create_db_and_container() if len(keys) > 0: parameters = [ {: f, : f} for i, key in en...
Read storeitems from storage. :param keys: :return dict:
339,178
def _download_file_from_drive(filename, url): confirm_token = None confirm_token = None session = requests.Session() response = session.get(url, stream=True) for k, v in response.cookies.items(): if k.startswith("download_warning"): confirm_token = v i...
Download filename from google drive unless it's already in directory. Args: filename (str): Name of the file to download to (do nothing if it already exists). url (str): URL to download from.
339,179
def generate_observations_from_state(self, state_index, nobs): observations = self.sigmas[state_index] * np.random.randn(nobs) + self.means[state_index] return observations
Generate synthetic observation data from a given state. Parameters ---------- state_index : int Index of the state from which observations are to be generated. nobs : int The number of observations to generate. Returns ------- observation...
339,180
def update(self): assert self.binded and self.params_initialized and self.optimizer_initialized self._params_dirty = True self._curr_module.update()
Updates parameters according to installed optimizer and the gradient computed in the previous forward-backward cycle. When KVStore is used to update parameters for multi-device or multi-machine training, a copy of the parameters are stored in KVStore. Note that for `row_sparse` parameters, ...
339,181
def biasFromLocations(locs, preferOrigin=True): dims = {} locs.sort() for l in locs: for d in l.keys(): if not d in dims: dims[d] = [] v = l[d] if type(v)==tuple: dims[d].append(v[0]) dims[d].append(v[1]) ...
Find the vector that translates the whole system to the origin.
339,182
def iter_comments(self, number=-1): url = self._build_url(, base_url=self._api) return self._iter(int(number), url, IssueComment)
Iterate over the comments on this issue. :param int number: (optional), number of comments to iterate over :returns: iterator of :class:`IssueComment <github3.issues.comment.IssueComment>`\ s
339,183
def spammer_view(request): context = RequestContext(request, {}) template = Template("") response = HttpResponse(template.render(context)) response.set_cookie(COOKIE_KEY, value=COOKIE_SPAM, httponly=True, expires=datetime.now()+timedelta(days=3650)) if D...
View for setting cookies on spammers.
339,184
def _parse_vcs_section(self, cfg_handler): if in cfg_handler: cfg = cfg_handler[] if in cfg: self.vcs_engine = cfg[] if in cfg: self.vcs_tag_params = list(filter(None, cfg[].split("\n"))) if in cfg: self...
Parse [vcs] section :param cfg_handler: :return:
339,185
def lonlat_point(self, lon, lat): self._set_query(self.spatial_query, longitude=lon, latitude=lat) return self
Add a latitude/longitude point to the query. This adds a request for a (`lon`, `lat`) point. This modifies the query in-place, but returns `self` so that multiple queries can be chained together on one line. This replaces any existing spatial queries that have been set. Parame...
339,186
def check_AP_deriv(abf,n=10): timePoints=get_AP_timepoints(abf)[:10] if len(timePoints)==0: return swhlab.plot.new(abf,True,title="AP velocity (n=%d)"%n,xlabel="ms",ylabel="V/S") pylab.axhline(-50,color=,lw=2,ls="--",alpha=.2) pylab.axhline(-100,color=,lw=2,ls="--",alpha=.2) Ys=abf...
X
339,187
def formMarkup(self, realm, return_to=None, immediate=False, form_tag_attrs=None): message = self.getMessage(realm, return_to, immediate) return message.toFormMarkup(self.endpoint.server_url, form_tag_attrs)
Get html for a form to submit this request to the IDP. @param form_tag_attrs: Dictionary of attributes to be added to the form tag. 'accept-charset' and 'enctype' have defaults that can be overridden. If a value is supplied for 'action' or 'method', it will be replaced. ...
339,188
def main(): logging.basicConfig(level=logging.DEBUG) app = QtWidgets.QApplication(sys.argv) window = QtWidgets.QMainWindow() ui = example_ui.Ui_MainWindow() ui.setupUi(window) ui.bt_delay_popup.addActions([ ui.actionAction, ui.actionAction_C ]) ui.bt_insta...
Application entry point
339,189
def _set_mac_learn_disable(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=mac_learn_disable.mac_learn_disable, is_container=, presence=False, yang_name="mac-learn-disable", rest_name="disable", parent=self, path_helper=self._path_helper, extmethods=s...
Setter method for mac_learn_disable, mapped from YANG variable /interface/port_channel/mac_learning/mac_learn_disable (container) If this variable is read-only (config: false) in the source YANG file, then _set_mac_learn_disable is considered as a private method. Backends looking to populate this variable s...
339,190
def parse_parameter_array(self, tup_tree): self.check_node(tup_tree, , (, ), (,), (,)) attrl = attrs(tup_tree) array_size = attrl.get(, None) if array_size is not None: array_size = int(array_size) qualifiers = self.li...
:: <!ELEMENT PARAMETER.ARRAY (QUALIFIER*)> <!ATTLIST PARAMETER.ARRAY %CIMName; %CIMType; #REQUIRED %ArraySize;>
339,191
def SelectFieldPrompt(field_name, context_str, *options): option_format_str = option_dict = {} print(context_str) print(.format( field_name) ) for cnt, option in enumerate(options): option_dict[.format(cnt + 1)] = option if not callable(option): print(op...
Prompts user to pick from provided options. It is possible to provide a function as an option although it is not yet tested. This could allow a user to be prompted to provide their own value rather than the listed options. Args: field_name (string): Name of the field. context_str (string)...
339,192
def sapm(effective_irradiance, temp_cell, module): s I-V curve (Voc, Isc, Ix, Ixx, Vmp/Imp) according to SAND2004-3535. Assumes a reference cell temperature of 25 C. Parameters ---------- effective_irradiance : numeric Effective irradiance (suns). temp_cell : numeric The cell t...
The Sandia PV Array Performance Model (SAPM) generates 5 points on a PV module's I-V curve (Voc, Isc, Ix, Ixx, Vmp/Imp) according to SAND2004-3535. Assumes a reference cell temperature of 25 C. Parameters ---------- effective_irradiance : numeric Effective irradiance (suns). temp_cell ...
339,193
def parse_iso8601_str(string): datetime_obj = datetime.datetime.strptime(string, "%Y-%m-%dT%H:%M:%SZ") return int(calendar.timegm(datetime_obj.utctimetuple()))
Parse a fixed ISO8601 datetime string. .. Note:: This function only parses dates in the format ``%Y-%m-%dT%H:%M:%SZ``. You must use a library like ``dateutils`` to properly parse dates and times. Returns: float: A UNIX timestamp.
339,194
def open_magnet(self): if sys.platform.startswith(): subprocess.Popen([, self.magnet], stdout=subprocess.PIPE, stderr=subprocess.PIPE) elif sys.platform.startswith(): os.startfile(self.magnet) elif sys.platform.startswith(): ...
Open magnet according to os.
339,195
def _joint_sample_n(self, n, seed=None): with tf.name_scope("sample_n_joint"): stream = seed_stream.SeedStream( seed, salt="LinearGaussianStateSpaceModel_sample_n_joint") sample_and_batch_shape = distribution_util.prefer_static_value( tf.concat([[n], self.batch_shape_tensor()]...
Draw a joint sample from the prior over latents and observations.
339,196
def _reject_neg(pos_lst: List, neg_lst: List) -> List: pos_lst.sort() neg_lst.sort() result = [] pivot_pos = pos_lst[0] pivot_neg = neg_lst[0] while pos_lst: if pivot_pos[1] <= pivot_neg[0]: result.append(pivot_pos) po...
Reject some positive matches according to negative matches Args: pos_lst: List neg_lst: List Returns: List
339,197
def editcomponent(self, data): data = data.copy() self._component_data_convert(data, update=True) return self._proxy.Component.update(data)
A method to edit a component in Bugzilla. Takes a dict, with mandatory elements of product. component, and initialowner. All other elements are optional and use the same names as the addcomponent() method.
339,198
def make_content_node(channeldir, rel_path, filename, metadata): file_key, file_ext = os.path.splitext(filename) ext = file_ext[1:] kind = None if ext in content_kinds.MAPPING: kind = content_kinds.MAPPING[ext] elif in metadata: kind = content_kinds.EXERCISE else: ...
Create ContentNode based on the file extention and metadata provided.
339,199
def TK_askPassword(title="input",msg="type here:"): root = tkinter.Tk() root.withdraw() root.attributes("-topmost", True) root.lift() value=tkinter.simpledialog.askstring(title,msg) root.destroy() return value
use the GUI to ask for a string.