code
stringlengths
51
2.34k
sequence
stringlengths
186
3.94k
docstring
stringlengths
11
171
def target_heating_level(self): try: if self.side == 'left': level = self.device.device_data['leftTargetHeatingLevel'] elif self.side == 'right': level = self.device.device_data['rightTargetHeatingLevel'] return level except TypeError: return None
module function_definition identifier parameters identifier block try_statement block if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement assignment identifier subscript attribute attribute identifier identifier identifier string string_start string_content string_end elif_clause comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement assignment identifier subscript attribute attribute identifier identifier identifier string string_start string_content string_end return_statement identifier except_clause identifier block return_statement none
Return target heating level.
def __reverse(self, **kwargs): start_point = kwargs.pop('start_point') return Location4D(latitude=start_point.latitude, longitude=start_point.longitude, depth=start_point.depth)
module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end return_statement call identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier
If we hit the bathymetry, set the location to where we came from.
def to_datetime(time): if type(time) == IntType or type(time) == LongType: time = datetime.fromtimestamp(time // 1000) return time
module function_definition identifier parameters identifier block if_statement boolean_operator comparison_operator call identifier argument_list identifier identifier comparison_operator call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator identifier integer return_statement identifier
Convert `time` to a datetime.
def __create_password(): salt = b64encode(API.__generate_string(32)) password = b64encode(API.__generate_string(64)) return b64encode(sha1(password + salt).digest())
module function_definition identifier parameters block expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list integer expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list integer return_statement call identifier argument_list call attribute call identifier argument_list binary_operator identifier identifier identifier argument_list
Create a password for the user.
def label(self, t): if self.labels is None: return None prev_label = None for l in self.labels: if l.time > t: break prev_label = l if prev_label is None: return None return prev_label.name
module function_definition identifier parameters identifier identifier block if_statement comparison_operator attribute identifier identifier none block return_statement none expression_statement assignment identifier none for_statement identifier attribute identifier identifier block if_statement comparison_operator attribute identifier identifier identifier block break_statement expression_statement assignment identifier identifier if_statement comparison_operator identifier none block return_statement none return_statement attribute identifier identifier
Get the label of the song at a given time in seconds
def func_args(func)->bool: "Return the arguments of `func`." code = func.__code__ return code.co_varnames[:code.co_argcount]
module function_definition identifier parameters identifier type identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier attribute identifier identifier return_statement subscript attribute identifier identifier slice attribute identifier identifier
Return the arguments of `func`.
def _find_snapshot(self, name): remote_snapshots = self._get_snapshots(self.client) for remote in reversed(remote_snapshots): if remote["Name"] == name or \ re.match(name, remote["Name"]): return remote return None
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier for_statement identifier call identifier argument_list identifier block if_statement boolean_operator comparison_operator subscript identifier string string_start string_content string_end identifier line_continuation call attribute identifier identifier argument_list identifier subscript identifier string string_start string_content string_end block return_statement identifier return_statement none
Find snapshot on remote by name or regular expression
def parse_userinfo(cls, userinfo): username, sep, password = userinfo.partition(':') return username, password
module function_definition identifier parameters identifier identifier block expression_statement assignment pattern_list identifier identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end return_statement expression_list identifier identifier
Parse the userinfo and return username and password.
def remove_rule_entry(self, rule_info): temp_list = list(self.rule_info) for rule in temp_list: if (rule.ip == rule_info.get('ip') and rule.mac == rule_info.get('mac') and rule.port == rule_info.get('port')): LOG.debug('Removed rule info %s from the list', rule_info) self.rule_info.remove(rule)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier for_statement identifier identifier block if_statement parenthesized_expression boolean_operator boolean_operator comparison_operator attribute identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end comparison_operator attribute identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end comparison_operator attribute identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier
Remove host data object from rule_info list.
def collect_outs(self): for outfile in self.rule.output_files or []: outfile_built = os.path.join(self.buildroot, outfile) if not os.path.exists(outfile_built): raise error.TargetBuildFailed( self.address, 'Output file is missing: %s' % outfile) metahash = self._metahash() log.debug('[%s]: Metahash: %s', self.address, metahash.hexdigest()) self.cachemgr.putfile(outfile_built, self.buildroot, metahash)
module function_definition identifier parameters identifier block for_statement identifier boolean_operator attribute attribute identifier identifier identifier list block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier identifier if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block raise_statement call attribute identifier identifier argument_list attribute identifier identifier binary_operator string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list identifier attribute identifier identifier identifier
Collect and store the outputs from this rule.
def update_local(self): stats = self.get_init_value() stats['total'] = cpu_percent.get() cpu_times_percent = psutil.cpu_times_percent(interval=0.0) for stat in ['user', 'system', 'idle', 'nice', 'iowait', 'irq', 'softirq', 'steal', 'guest', 'guest_nice']: if hasattr(cpu_times_percent, stat): stats[stat] = getattr(cpu_times_percent, stat) cpu_stats = psutil.cpu_stats() time_since_update = getTimeSinceLastUpdate('cpu') if not hasattr(self, 'cpu_stats_old'): self.cpu_stats_old = cpu_stats else: for stat in cpu_stats._fields: if getattr(cpu_stats, stat) is not None: stats[stat] = getattr(cpu_stats, stat) - getattr(self.cpu_stats_old, stat) stats['time_since_update'] = time_since_update stats['cpucore'] = self.nb_log_core self.cpu_stats_old = cpu_stats return stats
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier float for_statement identifier list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end block if_statement call identifier argument_list identifier identifier block expression_statement assignment subscript identifier identifier call identifier argument_list identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list string string_start string_content string_end if_statement not_operator call identifier argument_list identifier string string_start string_content string_end block expression_statement assignment attribute identifier identifier identifier else_clause block for_statement identifier attribute identifier identifier block if_statement comparison_operator call identifier argument_list identifier identifier none block expression_statement assignment subscript identifier identifier binary_operator call identifier argument_list identifier identifier call identifier argument_list attribute identifier identifier identifier expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier expression_statement assignment attribute identifier identifier identifier return_statement identifier
Update CPU stats using psutil.
def _get_prefixes(self): prefixes = { "@": "o", "+": "v", } feature_prefixes = self.server.features.get('PREFIX') if feature_prefixes: modes = feature_prefixes[1:len(feature_prefixes)//2] symbols = feature_prefixes[len(feature_prefixes)//2+1:] prefixes = dict(zip(symbols, modes)) return prefixes
module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end if_statement identifier block expression_statement assignment identifier subscript identifier slice integer binary_operator call identifier argument_list identifier integer expression_statement assignment identifier subscript identifier slice binary_operator binary_operator call identifier argument_list identifier integer integer expression_statement assignment identifier call identifier argument_list call identifier argument_list identifier identifier return_statement identifier
Get the possible nick prefixes and associated modes for a client.
def _add_gateway_responses(self): if not self.gateway_responses: return if self.gateway_responses and not self.definition_body: raise InvalidResourceException( self.logical_id, "GatewayResponses works only with inline Swagger specified in " "'DefinitionBody' property") for responses_key, responses_value in self.gateway_responses.items(): for response_key in responses_value.keys(): if response_key not in GatewayResponseProperties: raise InvalidResourceException( self.logical_id, "Invalid property '{}' in 'GatewayResponses' property '{}'".format(response_key, responses_key)) if not SwaggerEditor.is_valid(self.definition_body): raise InvalidResourceException( self.logical_id, "Unable to add Auth configuration because " "'DefinitionBody' does not contain a valid Swagger") swagger_editor = SwaggerEditor(self.definition_body) gateway_responses = {} for response_type, response in self.gateway_responses.items(): gateway_responses[response_type] = ApiGatewayResponse( api_logical_id=self.logical_id, response_parameters=response.get('ResponseParameters', {}), response_templates=response.get('ResponseTemplates', {}), status_code=response.get('StatusCode', None) ) if gateway_responses: swagger_editor.add_gateway_responses(gateway_responses) self.definition_body = swagger_editor.swagger
module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block return_statement if_statement boolean_operator attribute identifier identifier not_operator attribute identifier identifier block raise_statement call identifier argument_list attribute identifier identifier concatenated_string string string_start string_content string_end string string_start string_content string_end for_statement pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list block for_statement identifier call attribute identifier identifier argument_list block if_statement comparison_operator identifier identifier block raise_statement call identifier argument_list attribute identifier identifier call attribute string string_start string_content string_end identifier argument_list identifier identifier if_statement not_operator call attribute identifier identifier argument_list attribute identifier identifier block raise_statement call identifier argument_list attribute identifier identifier concatenated_string string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement assignment identifier dictionary for_statement pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list block expression_statement assignment subscript identifier identifier call identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier call attribute identifier identifier argument_list string string_start string_content string_end dictionary keyword_argument identifier call attribute identifier identifier argument_list string string_start string_content string_end dictionary keyword_argument identifier call attribute identifier identifier argument_list string string_start string_content string_end none if_statement identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier attribute identifier identifier
Add Gateway Response configuration to the Swagger file, if necessary
def generate_admin_metadata(name, creator_username=None): if not dtoolcore.utils.name_is_valid(name): raise(DtoolCoreInvalidNameError()) if creator_username is None: creator_username = dtoolcore.utils.getuser() datetime_obj = datetime.datetime.utcnow() admin_metadata = { "uuid": str(uuid.uuid4()), "dtoolcore_version": __version__, "name": name, "type": "protodataset", "creator_username": creator_username, "created_at": dtoolcore.utils.timestamp(datetime_obj) } return admin_metadata
module function_definition identifier parameters identifier default_parameter identifier none block if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block raise_statement parenthesized_expression call identifier argument_list if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier dictionary pair string string_start string_content string_end call identifier argument_list call attribute identifier identifier argument_list pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end identifier pair string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list identifier return_statement identifier
Return admin metadata as a dictionary.
def _delUserFromGroup(self, username, group="Clients"): portal_groups = api.portal.get_tool("portal_groups") group = portal_groups.getGroupById(group) group.removeMember(username)
module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier
Remove user from the group
def clear(self): super(XToolBar, self).clear() if self.isCollapsable(): self._collapseButton = QToolButton(self) self._collapseButton.setAutoRaise(True) self._collapseButton.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.addWidget(self._collapseButton) self.refreshButton() self._collapseButton.clicked.connect(self.toggleCollapsed) elif self._collapseButton: self._collapseButton.setParent(None) self._collapseButton.deleteLater() self._collapseButton = None
module function_definition identifier parameters identifier block expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list if_statement call attribute identifier identifier argument_list block expression_statement assignment attribute identifier identifier call identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list true expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list attribute identifier identifier elif_clause attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list none expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier none
Clears out this toolbar from the system.
def ydtick(self, dtick, index=1): self.layout['yaxis' + str(index)]['dtick'] = dtick return self
module function_definition identifier parameters identifier identifier default_parameter identifier integer block expression_statement assignment subscript subscript attribute identifier identifier binary_operator string string_start string_content string_end call identifier argument_list identifier string string_start string_content string_end identifier return_statement identifier
Set the tick distance.
def parse_http_scheme(uri): regex = re.compile( r'^(?:http)s?://', flags=re.IGNORECASE ) match = regex.match(uri) return match.group(0) if match else 'http://'
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement conditional_expression call attribute identifier identifier argument_list integer identifier string string_start string_content string_end
match on http scheme if no match is found will assume http
def headTail_breaks(values, cuts): values = np.array(values) mean = np.mean(values) cuts.append(mean) if len(values) > 1: return headTail_breaks(values[values >= mean], cuts) return cuts
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier if_statement comparison_operator call identifier argument_list identifier integer block return_statement call identifier argument_list subscript identifier comparison_operator identifier identifier identifier return_statement identifier
head tail breaks helper function
def create_bitcoind_service_proxy( rpc_username, rpc_password, server='127.0.0.1', port=8332, use_https=False): protocol = 'https' if use_https else 'http' uri = '%s://%s:%s@%s:%s' % (protocol, rpc_username, rpc_password, server, port) return AuthServiceProxy(uri)
module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_content string_end default_parameter identifier integer default_parameter identifier false block expression_statement assignment identifier conditional_expression string string_start string_content string_end identifier string string_start string_content string_end expression_statement assignment identifier binary_operator string string_start string_content string_end tuple identifier identifier identifier identifier identifier return_statement call identifier argument_list identifier
create a bitcoind service proxy
def HH(n): if (n<=0):return Context('1') else: LL1=LL(n-1) HH1=HH(n-1) r1 = C1(3**(n-1),2**(n-1)) - LL1 - HH1 r2 = HH1 - HH1 - HH1 return r1 + r2
module function_definition identifier parameters identifier block if_statement parenthesized_expression comparison_operator identifier integer block return_statement call identifier argument_list string string_start string_content string_end else_clause block expression_statement assignment identifier call identifier argument_list binary_operator identifier integer expression_statement assignment identifier call identifier argument_list binary_operator identifier integer expression_statement assignment identifier binary_operator binary_operator call identifier argument_list binary_operator integer parenthesized_expression binary_operator identifier integer binary_operator integer parenthesized_expression binary_operator identifier integer identifier identifier expression_statement assignment identifier binary_operator binary_operator identifier identifier identifier return_statement binary_operator identifier identifier
constructs the HH context
def migrate(app_name=None, revision=None): "Syncs and migrates the database using South." cmd = ['python bin/manage.py syncdb --migrate'] if app_name: cmd.append(app_name) if revision: cmd.append(revision) verun(' '.join(cmd))
module function_definition identifier parameters default_parameter identifier none default_parameter identifier none block expression_statement string string_start string_content string_end expression_statement assignment identifier list string string_start string_content string_end if_statement identifier block expression_statement call attribute identifier identifier argument_list identifier if_statement identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier
Syncs and migrates the database using South.
def __check_field(self, key): if not self._props.get(key): raise KeyError( 'The field "%s" does not exist on "%s"' % ( key, self.__class__.__name__, ), )
module function_definition identifier parameters identifier identifier block if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end tuple identifier attribute attribute identifier identifier identifier
Raises a KeyError if the field doesn't exist.
def describe(cls, sha1): cmd = [ 'git', 'describe', '--all', '--long', sha1 ] out = None try: out = subprocess.check_output( cmd, stderr=subprocess.STDOUT, universal_newlines=True) except subprocess.CalledProcessError as e: if e.output.find('No tags can describe') != -1: return '' raise out = out.strip() out = re.sub(r'^(heads|tags|remotes)/', '', out) out = re.sub(r'-g[0-9a-f]{7,}$', '', out) return out
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end identifier expression_statement assignment identifier none try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier true except_clause as_pattern attribute identifier identifier as_pattern_target identifier block if_statement comparison_operator call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end unary_operator integer block return_statement string string_start string_end raise_statement expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end identifier return_statement identifier
Returns a human-readable representation of the given SHA1.
def asynchronous(function, event): thread = Thread(target=synchronous, args=(function, event)) thread.daemon = True thread.start()
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier tuple identifier identifier expression_statement assignment attribute identifier identifier true expression_statement call attribute identifier identifier argument_list
Runs the function asynchronously taking care of exceptions.
def _get_ordering(son): def fmt(field, direction): return '{0}{1}'.format({-1: '-', 1: '+'}[direction], field) if '$orderby' in son: return ', '.join(fmt(f, d) for f, d in son['$orderby'].items())
module function_definition identifier parameters identifier block function_definition identifier parameters identifier identifier block return_statement call attribute string string_start string_content string_end identifier argument_list subscript dictionary pair unary_operator integer string string_start string_content string_end pair integer string string_start string_content string_end identifier identifier if_statement comparison_operator string string_start string_content string_end identifier block return_statement call attribute string string_start string_content string_end identifier generator_expression call identifier argument_list identifier identifier for_in_clause pattern_list identifier identifier call attribute subscript identifier string string_start string_content string_end identifier argument_list
Helper function to extract formatted ordering from dict.
def render_it(self, kind, num, with_tag=False, glyph=''): all_cats = MPost.query_recent(num, kind=kind) kwd = { 'with_tag': with_tag, 'router': router_post[kind], 'glyph': glyph } return self.render_string('modules/info/list_equation.html', recs=all_cats, kwd=kwd)
module function_definition identifier parameters identifier identifier identifier default_parameter identifier false default_parameter identifier string string_start string_end block expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end subscript identifier identifier pair string string_start string_content string_end identifier return_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier identifier
render, no user logged in
def ini2value(ini_content): from mo_future import ConfigParser, StringIO buff = StringIO(ini_content) config = ConfigParser() config._read(buff, "dummy") output = {} for section in config.sections(): output[section]=s = {} for k, v in config.items(section): s[k]=v return wrap(output)
module function_definition identifier parameters identifier block import_from_statement dotted_name identifier dotted_name identifier dotted_name identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list expression_statement call attribute identifier identifier argument_list identifier string string_start string_content string_end expression_statement assignment identifier dictionary for_statement identifier call attribute identifier identifier argument_list block expression_statement assignment subscript identifier identifier assignment identifier dictionary for_statement pattern_list identifier identifier call attribute identifier identifier argument_list identifier block expression_statement assignment subscript identifier identifier identifier return_statement call identifier argument_list identifier
INI FILE CONTENT TO Data
def inFocus(self): previous_flags = self.window.flags() self.window.setFlags(previous_flags | QtCore.Qt.WindowStaysOnTopHint)
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator identifier attribute attribute identifier identifier identifier
Set GUI on-top flag
def GetAttributeNs(self, localName, namespaceURI): ret = libxml2mod.xmlTextReaderGetAttributeNs(self._o, localName, namespaceURI) return ret
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier identifier identifier return_statement identifier
Provides the value of the specified attribute
def credit_card_number(self, card_type=None): card = self._credit_card_type(card_type) prefix = self.random_element(card.prefixes) number = self._generate_number(self.numerify(prefix), card.length) return number
module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier attribute identifier identifier return_statement identifier
Returns a valid credit card number.
def encode_date_optional_time(obj): if isinstance(obj, datetime.datetime): return timezone("UTC").normalize(obj.astimezone(timezone("UTC"))).strftime('%Y-%m-%dT%H:%M:%SZ') raise TypeError("{0} is not JSON serializable".format(repr(obj)))
module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier attribute identifier identifier block return_statement call attribute call attribute call identifier argument_list string string_start string_content string_end identifier argument_list call attribute identifier identifier argument_list call identifier argument_list string string_start string_content string_end identifier argument_list string string_start string_content string_end raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list call identifier argument_list identifier
ISO encode timezone-aware datetimes
def build_command_parser(): parser = argparse.ArgumentParser( description='Transform Pylint JSON report to HTML') parser.add_argument( 'filename', metavar='FILENAME', type=argparse.FileType('r'), nargs='?', default=sys.stdin, help='Pylint JSON report input file (or stdin)') parser.add_argument( '-o', '--output', metavar='FILENAME', type=argparse.FileType('w'), default=sys.stdout, help='Pylint HTML report output file (or stdout)') parser.add_argument( '-f', '--input-format', metavar='FORMAT', choices=[SIMPLE_JSON, EXTENDED_JSON], action='store', dest='input_format', default='json', help='Pylint JSON Report input type (json or jsonextended)') return parser
module function_definition identifier parameters block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier attribute identifier identifier keyword_argument identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier attribute identifier identifier keyword_argument identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier list identifier identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end return_statement identifier
Build command parser using ``argparse`` module.
def deleted(self): 'Return datetime.datetime or None if the file isnt deleted' _d = self.folder.attrib.get('deleted', None) if _d is None: return None return dateutil.parser.parse(str(_d))
module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end none if_statement comparison_operator identifier none block return_statement none return_statement call attribute attribute identifier identifier identifier argument_list call identifier argument_list identifier
Return datetime.datetime or None if the file isnt deleted
def hash_fasta(seq, ignore_case=False, ignore_N=False, ignore_stop=False, checksum="MD5"): if ignore_stop: seq = seq.rstrip("*") if ignore_case: seq = seq.upper() if ignore_N: if not all(c.upper() in 'ATGCN' for c in seq): seq = re.sub('X', '', seq) else: seq = re.sub('N', '', seq) if checksum == "MD5": hashed = md5(seq).hexdigest() elif checksum == "GCG": hashed = seguid(seq) return hashed
module function_definition identifier parameters identifier default_parameter identifier false default_parameter identifier false default_parameter identifier false default_parameter identifier string string_start string_content string_end block if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement identifier block if_statement not_operator call identifier generator_expression comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end for_in_clause identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end identifier else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end identifier if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier call attribute call identifier argument_list identifier identifier argument_list elif_clause comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list identifier return_statement identifier
Generates checksum of input sequence element
def store_db_obj(cls, in_obj, out_obj): cls.ip_db_obj['in'] = in_obj cls.ip_db_obj['out'] = out_obj
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end identifier expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end identifier
Store the IP DB object.
def machine(self): machine_id = self.safe_data['machine-id'] if machine_id: return self.model.machines.get(machine_id, None) else: return None
module function_definition identifier parameters identifier block expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end if_statement identifier block return_statement call attribute attribute attribute identifier identifier identifier identifier argument_list identifier none else_clause block return_statement none
Get the machine object for this unit.
def _get_recursive_difference(self, type): if type == 'intersect': return [recursive_diff(item['old'], item['new']) for item in self._intersect] elif type == 'added': return [recursive_diff({}, item) for item in self._added] elif type == 'removed': return [recursive_diff(item, {}, ignore_missing_keys=False) for item in self._removed] elif type == 'all': recursive_list = [] recursive_list.extend([recursive_diff(item['old'], item['new']) for item in self._intersect]) recursive_list.extend([recursive_diff({}, item) for item in self._added]) recursive_list.extend([recursive_diff(item, {}, ignore_missing_keys=False) for item in self._removed]) return recursive_list else: raise ValueError('The given type for recursive list matching ' 'is not supported.')
module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier string string_start string_content string_end block return_statement list_comprehension call identifier argument_list subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end for_in_clause identifier attribute identifier identifier elif_clause comparison_operator identifier string string_start string_content string_end block return_statement list_comprehension call identifier argument_list dictionary identifier for_in_clause identifier attribute identifier identifier elif_clause comparison_operator identifier string string_start string_content string_end block return_statement list_comprehension call identifier argument_list identifier dictionary keyword_argument identifier false for_in_clause identifier attribute identifier identifier elif_clause comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier list expression_statement call attribute identifier identifier argument_list list_comprehension call identifier argument_list subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end for_in_clause identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list list_comprehension call identifier argument_list dictionary identifier for_in_clause identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list list_comprehension call identifier argument_list identifier dictionary keyword_argument identifier false for_in_clause identifier attribute identifier identifier return_statement identifier else_clause block raise_statement call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end
Returns the recursive diff between dict values
def to_unix(cls, timestamp): if not isinstance(timestamp, datetime.datetime): raise TypeError('Time.milliseconds expects a datetime object') base = time.mktime(timestamp.timetuple()) return base
module function_definition identifier parameters identifier identifier block if_statement not_operator call identifier argument_list identifier attribute identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list return_statement identifier
Wrapper over time module to produce Unix epoch time as a float
def split_stock_str(stock_str_param): stock_str = str(stock_str_param) split_loc = stock_str.find(".") if 0 <= split_loc < len( stock_str) - 1 and stock_str[0:split_loc] in MKT_MAP: market_str = stock_str[0:split_loc] market_code = MKT_MAP[market_str] partial_stock_str = stock_str[split_loc + 1:] return RET_OK, (market_code, partial_stock_str) else: error_str = ERROR_STR_PREFIX + "format of %s is wrong. (US.AAPL, HK.00700, SZ.000001)" % stock_str return RET_ERROR, error_str
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement boolean_operator comparison_operator integer identifier binary_operator call identifier argument_list identifier integer comparison_operator subscript identifier slice integer identifier identifier block expression_statement assignment identifier subscript identifier slice integer identifier expression_statement assignment identifier subscript identifier identifier expression_statement assignment identifier subscript identifier slice binary_operator identifier integer return_statement expression_list identifier tuple identifier identifier else_clause block expression_statement assignment identifier binary_operator identifier binary_operator string string_start string_content string_end identifier return_statement expression_list identifier identifier
split the stock string
def on_batch_begin(self, batch_info: BatchInfo): cycle_length = self.cycle_lengths[batch_info.local_epoch_number - 1] cycle_start = self.cycle_starts[batch_info.local_epoch_number - 1] numerator = (batch_info.local_epoch_number - cycle_start - 1) * batch_info.batches_per_epoch + batch_info.batch_number denominator = cycle_length * batch_info.batches_per_epoch interpolation_number = numerator / denominator if cycle_start == 0 and numerator < self.init_iter: lr = self.init_lr else: if isinstance(self.max_lr, list): lr = [interp.interpolate_single(max_lr, min_lr, interpolation_number, how=self.interpolate) for max_lr, min_lr in zip(self.max_lr, self.min_lr)] else: lr = interp.interpolate_single(self.max_lr, self.min_lr, interpolation_number, how=self.interpolate) self.set_lr(lr)
module function_definition identifier parameters identifier typed_parameter identifier type identifier block expression_statement assignment identifier subscript attribute identifier identifier binary_operator attribute identifier identifier integer expression_statement assignment identifier subscript attribute identifier identifier binary_operator attribute identifier identifier integer expression_statement assignment identifier binary_operator binary_operator parenthesized_expression binary_operator binary_operator attribute identifier identifier identifier integer attribute identifier identifier attribute identifier identifier expression_statement assignment identifier binary_operator identifier attribute identifier identifier expression_statement assignment identifier binary_operator identifier identifier if_statement boolean_operator comparison_operator identifier integer comparison_operator identifier attribute identifier identifier block expression_statement assignment identifier attribute identifier identifier else_clause block if_statement call identifier argument_list attribute identifier identifier identifier block expression_statement assignment identifier list_comprehension call attribute identifier identifier argument_list identifier identifier identifier keyword_argument identifier attribute identifier identifier for_in_clause pattern_list identifier identifier call identifier argument_list attribute identifier identifier attribute identifier identifier else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier identifier keyword_argument identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier
Set proper learning rate
def vtmlrender(vtmarkup, plain=None, strict=False, vtmlparser=VTMLParser()): if isinstance(vtmarkup, VTMLBuffer): return vtmarkup.plain() if plain else vtmarkup try: vtmlparser.feed(vtmarkup) vtmlparser.close() except: if strict: raise buf = VTMLBuffer() buf.append_str(str(vtmarkup)) return buf else: buf = vtmlparser.getvalue() return buf.plain() if plain else buf finally: vtmlparser.reset()
module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier false default_parameter identifier call identifier argument_list block if_statement call identifier argument_list identifier identifier block return_statement conditional_expression call attribute identifier identifier argument_list identifier identifier try_statement block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list except_clause block if_statement identifier block raise_statement expression_statement assignment identifier call identifier argument_list expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier return_statement identifier else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list return_statement conditional_expression call attribute identifier identifier argument_list identifier identifier finally_clause block expression_statement call attribute identifier identifier argument_list
Look for vt100 markup and render vt opcodes into a VTMLBuffer.
def _head_length(self, port): if not port: return 0. parent_state_v = self.get_parent_state_v() if parent_state_v is port.parent: return port.port_size[1] return max(port.port_size[1] * 1.5, self._calc_line_width() / 1.3)
module function_definition identifier parameters identifier identifier block if_statement not_operator identifier block return_statement float expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator identifier attribute identifier identifier block return_statement subscript attribute identifier identifier integer return_statement call identifier argument_list binary_operator subscript attribute identifier identifier integer float binary_operator call attribute identifier identifier argument_list float
Distance from the center of the port to the perpendicular waypoint
def do_gen(argdict): site = make_site_obj(argdict) try: st = time.time() site.generate() et = time.time() print "Generated Site in %f seconds."% (et-st) except ValueError as e: print "Cannot generate. You are not within a simplystatic \ tree and you didn't specify a directory."
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list print_statement binary_operator string string_start string_content string_end parenthesized_expression binary_operator identifier identifier except_clause as_pattern identifier as_pattern_target identifier block print_statement string string_start string_content escape_sequence string_end
Generate the whole site.
def _parse_statistic(data, scale): i = 0 for byte in bytearray(data): i = (i << 8) + byte if i == 32768: return None if scale == 0: return i return float(i) / (scale * 10)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier integer for_statement identifier call identifier argument_list identifier block expression_statement assignment identifier binary_operator parenthesized_expression binary_operator identifier integer identifier if_statement comparison_operator identifier integer block return_statement none if_statement comparison_operator identifier integer block return_statement identifier return_statement binary_operator call identifier argument_list identifier parenthesized_expression binary_operator identifier integer
Parse binary statistics returned from the history API
def actions(self, state): rows = string_to_list(state) row_e, col_e = find_location(rows, 'e') actions = [] if row_e > 0: actions.append(rows[row_e - 1][col_e]) if row_e < 2: actions.append(rows[row_e + 1][col_e]) if col_e > 0: actions.append(rows[row_e][col_e - 1]) if col_e < 2: actions.append(rows[row_e][col_e + 1]) return actions
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier string string_start string_content string_end expression_statement assignment identifier list if_statement comparison_operator identifier integer block expression_statement call attribute identifier identifier argument_list subscript subscript identifier binary_operator identifier integer identifier if_statement comparison_operator identifier integer block expression_statement call attribute identifier identifier argument_list subscript subscript identifier binary_operator identifier integer identifier if_statement comparison_operator identifier integer block expression_statement call attribute identifier identifier argument_list subscript subscript identifier identifier binary_operator identifier integer if_statement comparison_operator identifier integer block expression_statement call attribute identifier identifier argument_list subscript subscript identifier identifier binary_operator identifier integer return_statement identifier
Returns a list of the pieces we can move to the empty space.
def _serialize(self, include_run_logs=False, strict_json=False): result = {'dagobah_id': self.dagobah_id, 'created_jobs': self.created_jobs, 'jobs': [job._serialize(include_run_logs=include_run_logs, strict_json=strict_json) for job in self.jobs]} if strict_json: result = json.loads(json.dumps(result, cls=StrictJSONEncoder)) return result
module function_definition identifier parameters identifier default_parameter identifier false default_parameter identifier false block expression_statement assignment identifier dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end list_comprehension call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier for_in_clause identifier attribute identifier identifier if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier keyword_argument identifier identifier return_statement identifier
Serialize a representation of this Dagobah object to JSON.
def _describe_tree(self, prefix, with_transform): extra = ': "%s"' % self.name if self.name is not None else '' if with_transform: extra += (' [%s]' % self.transform.__class__.__name__) output = '' if len(prefix) > 0: output += prefix[:-3] output += ' +--' output += '%s%s\n' % (self.__class__.__name__, extra) n_children = len(self.children) for ii, child in enumerate(self.children): sub_prefix = prefix + (' ' if ii+1 == n_children else ' |') output += child._describe_tree(sub_prefix, with_transform) return output
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier conditional_expression binary_operator string string_start string_content string_end attribute identifier identifier comparison_operator attribute identifier identifier none string string_start string_end if_statement identifier block expression_statement augmented_assignment identifier parenthesized_expression binary_operator string string_start string_content string_end attribute attribute attribute identifier identifier identifier identifier expression_statement assignment identifier string string_start string_end if_statement comparison_operator call identifier argument_list identifier integer block expression_statement augmented_assignment identifier subscript identifier slice unary_operator integer expression_statement augmented_assignment identifier string string_start string_content string_end expression_statement augmented_assignment identifier binary_operator string string_start string_content escape_sequence string_end tuple attribute attribute identifier identifier identifier identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier for_statement pattern_list identifier identifier call identifier argument_list attribute identifier identifier block expression_statement assignment identifier binary_operator identifier parenthesized_expression conditional_expression string string_start string_content string_end comparison_operator binary_operator identifier integer identifier string string_start string_content string_end expression_statement augmented_assignment identifier call attribute identifier identifier argument_list identifier identifier return_statement identifier
Helper function to actuall construct the tree
def _make_c_string_check(string): if isinstance(string, bytes): if b"\x00" in string: raise InvalidDocument("BSON keys / regex patterns must not " "contain a NUL character") try: _utf_8_decode(string, None, True) return string + b"\x00" except UnicodeError: raise InvalidStringData("strings in documents must be valid " "UTF-8: %r" % string) else: if "\x00" in string: raise InvalidDocument("BSON keys / regex patterns must not " "contain a NUL character") return _utf_8_encode(string)[0] + b"\x00"
module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier identifier block if_statement comparison_operator string string_start string_content escape_sequence string_end identifier block raise_statement call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end try_statement block expression_statement call identifier argument_list identifier none true return_statement binary_operator identifier string string_start string_content escape_sequence string_end except_clause identifier block raise_statement call identifier argument_list binary_operator concatenated_string string string_start string_content string_end string string_start string_content string_end identifier else_clause block if_statement comparison_operator string string_start string_content escape_sequence string_end identifier block raise_statement call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end return_statement binary_operator subscript call identifier argument_list identifier integer string string_start string_content escape_sequence string_end
Make a 'C' string, checking for embedded NUL characters.
def build_from_issues(gh_token, body): if body["action"] in ["opened", "edited"]: github_con = Github(gh_token) repo = github_con.get_repo(body['repository']['full_name']) issue = repo.get_issue(body['issue']['number']) text = body['issue']['body'] comment = issue return WebhookMetadata(repo, issue, text, comment) return None
module function_definition identifier parameters identifier identifier block if_statement comparison_operator subscript identifier string string_start string_content string_end list string string_start string_content string_end string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list subscript subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list subscript subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier subscript subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier identifier return_statement call identifier argument_list identifier identifier identifier identifier return_statement none
Create a WebhookMetadata from an opening issue text.
def setVisible(self, value): if self.timer is not None: if value: self.timer.start(self._interval) else: self.timer.stop() super(BaseTimerStatus, self).setVisible(value)
module function_definition identifier parameters identifier identifier block if_statement comparison_operator attribute identifier identifier none block if_statement identifier block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier else_clause block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list identifier
Override Qt method to stops timers if widget is not visible.
def create_logger(name, formatter=None, handler=None, level=None): logger = logging.getLogger(name) logger.handlers = [] if handler is None: handler = logging.StreamHandler(sys.stdout) if formatter is not None: handler.setFormatter(formatter) if level is None: level = logging.DEBUG handler.setLevel(level) logger.setLevel(level) logger.addHandler(handler) return logger
module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier list if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier if_statement comparison_operator identifier none block expression_statement call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier none block expression_statement assignment identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier return_statement identifier
Returns a new logger for the specified name.
def _threeDdot_simple(M,a): "Return Ma, where M is a 3x3 transformation matrix, for each pixel" result = np.empty(a.shape,dtype=a.dtype) for i in range(a.shape[0]): for j in range(a.shape[1]): A = np.array([a[i,j,0],a[i,j,1],a[i,j,2]]).reshape((3,1)) L = np.dot(M,A) result[i,j,0] = L[0] result[i,j,1] = L[1] result[i,j,2] = L[2] return result
module function_definition identifier parameters identifier identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier attribute identifier identifier for_statement identifier call identifier argument_list subscript attribute identifier identifier integer block for_statement identifier call identifier argument_list subscript attribute identifier identifier integer block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list list subscript identifier identifier identifier integer subscript identifier identifier identifier integer subscript identifier identifier identifier integer identifier argument_list tuple integer integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement assignment subscript identifier identifier identifier integer subscript identifier integer expression_statement assignment subscript identifier identifier identifier integer subscript identifier integer expression_statement assignment subscript identifier identifier identifier integer subscript identifier integer return_statement identifier
Return Ma, where M is a 3x3 transformation matrix, for each pixel
def comments(self, update=True): if not self._comments: if self.count == 0: return self._continue_comments(update) children = [x for x in self.children if 't1_{0}'.format(x) not in self.submission._comments_by_id] if not children: return None data = {'children': ','.join(children), 'link_id': self.submission.fullname, 'r': str(self.submission.subreddit)} if self.submission._comment_sort: data['where'] = self.submission._comment_sort url = self.reddit_session.config['morechildren'] response = self.reddit_session.request_json(url, data=data) self._comments = response['data']['things'] if update: for comment in self._comments: comment._update_submission(self.submission) return self._comments
module function_definition identifier parameters identifier default_parameter identifier true block if_statement not_operator attribute identifier identifier block if_statement comparison_operator attribute identifier identifier integer block return_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier list_comprehension identifier for_in_clause identifier attribute identifier identifier if_clause comparison_operator call attribute string string_start string_content string_end identifier argument_list identifier attribute attribute identifier identifier identifier if_statement not_operator identifier block return_statement none expression_statement assignment identifier dictionary pair string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list identifier pair string string_start string_content string_end attribute attribute identifier identifier identifier pair string string_start string_content string_end call identifier argument_list attribute attribute identifier identifier identifier if_statement attribute attribute identifier identifier identifier block expression_statement assignment subscript identifier string string_start string_content string_end attribute attribute identifier identifier identifier expression_statement assignment identifier subscript attribute attribute identifier identifier identifier string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier identifier expression_statement assignment attribute identifier identifier subscript subscript identifier string string_start string_content string_end string string_start string_content string_end if_statement identifier block for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier return_statement attribute identifier identifier
Fetch and return the comments for a single MoreComments object.
def _shape_list(tensor): shape = tensor.get_shape().as_list() dynamic_shape = tf.shape(tensor) for i in range(len(shape)): if shape[i] is None: shape[i] = dynamic_shape[i] return shape
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier for_statement identifier call identifier argument_list call identifier argument_list identifier block if_statement comparison_operator subscript identifier identifier none block expression_statement assignment subscript identifier identifier subscript identifier identifier return_statement identifier
Return a list of the tensor's shape, and ensure no None values in list.
def _submit_metrics(self, metrics, metric_name_and_type_by_property): for metric in metrics: if ( metric.name not in metric_name_and_type_by_property and metric.name.lower() not in metric_name_and_type_by_property ): continue if metric_name_and_type_by_property.get(metric.name): metric_name, metric_type = metric_name_and_type_by_property[metric.name] elif metric_name_and_type_by_property.get(metric.name.lower()): metric_name, metric_type = metric_name_and_type_by_property[metric.name.lower()] else: continue try: func = getattr(self, metric_type.lower()) except AttributeError: raise Exception(u"Invalid metric type: {0}".format(metric_type)) func(metric_name, metric.value, metric.tags)
module function_definition identifier parameters identifier identifier identifier block for_statement identifier identifier block if_statement parenthesized_expression boolean_operator comparison_operator attribute identifier identifier identifier comparison_operator call attribute attribute identifier identifier identifier argument_list identifier block continue_statement if_statement call attribute identifier identifier argument_list attribute identifier identifier block expression_statement assignment pattern_list identifier identifier subscript identifier attribute identifier identifier elif_clause call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list block expression_statement assignment pattern_list identifier identifier subscript identifier call attribute attribute identifier identifier identifier argument_list else_clause block continue_statement try_statement block expression_statement assignment identifier call identifier argument_list identifier call attribute identifier identifier argument_list except_clause identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement call identifier argument_list identifier attribute identifier identifier attribute identifier identifier
Resolve metric names and types and submit it.
def getLeaves(self): result = list() if not self._next_stages: result.append(self) else: for stage in self._next_stages: leaves = stage.getLeaves() result += leaves return result
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list if_statement not_operator attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier else_clause block for_statement identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement augmented_assignment identifier identifier return_statement identifier
Return the downstream leaf stages of this stage.
def download_script(script_file_name): return "Sorry! Temporarily disabled." if script_file_name[:-3] in registered_modules: loaded_module = registered_modules[script_file_name[:-3]] package_path = os.sep.join(loaded_module.__package__.split('.')[1:]) return send_from_directory(directory=os.path.join( app.config['SCRIPTS_DIR'], package_path), filename=script_file_name) else: return "ERROR"
module function_definition identifier parameters identifier block return_statement string string_start string_content string_end if_statement comparison_operator subscript identifier slice unary_operator integer identifier block expression_statement assignment identifier subscript identifier subscript identifier slice unary_operator integer expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list subscript call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end slice integer return_statement call identifier argument_list keyword_argument identifier call attribute attribute identifier identifier identifier argument_list subscript attribute identifier identifier string string_start string_content string_end identifier keyword_argument identifier identifier else_clause block return_statement string string_start string_content string_end
Send a script directly from the scripts directory
def compare_trees(dir1, dir2): paths1 = DirPaths(dir1).walk() paths2 = DirPaths(dir2).walk() return unique_venn(paths1, paths2)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute call identifier argument_list identifier identifier argument_list expression_statement assignment identifier call attribute call identifier argument_list identifier identifier argument_list return_statement call identifier argument_list identifier identifier
Parse two directories and return lists of unique files
def flat_model(tree): names = [] for columns in viewvalues(tree): for col in columns: if isinstance(col, dict): col_name = list(col)[0] names += [col_name + '__' + c for c in flat_model(col)] else: names.append(col) return names
module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement identifier call identifier argument_list identifier block for_statement identifier identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier subscript call identifier argument_list identifier integer expression_statement augmented_assignment identifier list_comprehension binary_operator binary_operator identifier string string_start string_content string_end identifier for_in_clause identifier call identifier argument_list identifier else_clause block expression_statement call attribute identifier identifier argument_list identifier return_statement identifier
Flatten the tree into a list of properties adding parents as prefixes.
def getAttrs(self, node): attrs = {} for k,v in node._attrs.items(): attrs[k] = v.value return attrs
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary for_statement pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list block expression_statement assignment subscript identifier identifier attribute identifier identifier return_statement identifier
Return a Collection of all attributes
def winapi_result( result ): if not result: raise WinApiException("%d (%x): %s" % (ctypes.GetLastError(), ctypes.GetLastError(), ctypes.FormatError())) return result
module function_definition identifier parameters identifier block if_statement not_operator identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end tuple call attribute identifier identifier argument_list call attribute identifier identifier argument_list call attribute identifier identifier argument_list return_statement identifier
Validate WINAPI BOOL result, raise exception if failed
def clear(self): while True: try: session = self._sessions.get(block=False) except queue.Empty: break else: session.delete()
module function_definition identifier parameters identifier block while_statement true block try_statement block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier false except_clause attribute identifier identifier block break_statement else_clause block expression_statement call attribute identifier identifier argument_list
Delete all sessions in the pool.
def _get_metadata(self, file_id, metadata_fields=''): title = '%s._get_metadata' % self.__class__.__name__ if not metadata_fields: metadata_fields = ','.join(self.object_file.keys()) else: field_list = metadata_fields.split(',') for field in field_list: if not field in self.object_file.keys(): raise ValueError('%s(metadata_fields="%s") is not a valid drive file field' % (title, field)) try: metadata_details = self.drive.get(fileId=file_id, fields=metadata_fields).execute() except: raise DriveConnectionError(title) return metadata_details
module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_end block expression_statement assignment identifier binary_operator string string_start string_content string_end attribute attribute identifier identifier identifier if_statement not_operator identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list call attribute attribute identifier identifier identifier argument_list else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end for_statement identifier identifier block if_statement not_operator comparison_operator identifier call attribute attribute identifier identifier identifier argument_list block raise_statement call identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier try_statement block expression_statement assignment identifier call attribute call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier identifier argument_list except_clause block raise_statement call identifier argument_list identifier return_statement identifier
a helper method for retrieving the metadata of a file
def command_update(self): if len(self.args) == 1 and self.args[0] == "update": Update().repository(only="") elif (len(self.args) == 2 and self.args[0] == "update" and self.args[1].startswith("--only=")): repos = self.args[1].split("=")[-1].split(",") for rp in repos: if rp not in self.meta.repositories: repos.remove(rp) Update().repository(repos) else: usage("")
module function_definition identifier parameters identifier block if_statement boolean_operator comparison_operator call identifier argument_list attribute identifier identifier integer comparison_operator subscript attribute identifier identifier integer string string_start string_content string_end block expression_statement call attribute call identifier argument_list identifier argument_list keyword_argument identifier string string_start string_end elif_clause parenthesized_expression boolean_operator boolean_operator comparison_operator call identifier argument_list attribute identifier identifier integer comparison_operator subscript attribute identifier identifier integer string string_start string_content string_end call attribute subscript attribute identifier identifier integer identifier argument_list string string_start string_content string_end block expression_statement assignment identifier call attribute subscript call attribute subscript attribute identifier identifier integer identifier argument_list string string_start string_content string_end unary_operator integer identifier argument_list string string_start string_content string_end for_statement identifier identifier block if_statement comparison_operator identifier attribute attribute identifier identifier identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute call identifier argument_list identifier argument_list identifier else_clause block expression_statement call identifier argument_list string string_start string_end
Update package lists repositories
def round_rectangle(size, radius, fill): width, height = size rectangle = Image.new('L', size, 255) corner = round_corner(radius, 255) rectangle.paste(corner, (0, 0)) rectangle.paste(corner.rotate(90), (0, height - radius)) rectangle.paste(corner.rotate(180), (width - radius, height - radius)) rectangle.paste(corner.rotate(270), (width - radius, 0)) return rectangle
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment pattern_list identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier integer expression_statement assignment identifier call identifier argument_list identifier integer expression_statement call attribute identifier identifier argument_list identifier tuple integer integer expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list integer tuple integer binary_operator identifier identifier expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list integer tuple binary_operator identifier identifier binary_operator identifier identifier expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list integer tuple binary_operator identifier identifier integer return_statement identifier
Draw a rounded rectangle
def raise_error(self, e, exc_info=None): if not exc_info: exc_info = sys.exc_info() if not isinstance(e, InterfaceError): if not hasattr(builtins, e.__class__.__name__): e = self._create_error(e, exc_info) reraise(e.__class__, e, exc_info[2])
module function_definition identifier parameters identifier identifier default_parameter identifier none block if_statement not_operator identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement not_operator call identifier argument_list identifier identifier block if_statement not_operator call identifier argument_list identifier attribute attribute identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement call identifier argument_list attribute identifier identifier identifier subscript identifier integer
this is just a wrapper to make the passed in exception an InterfaceError
def sqlvm_list( client, resource_group_name=None): if resource_group_name: return client.list_by_resource_group(resource_group_name=resource_group_name) return client.list()
module function_definition identifier parameters identifier default_parameter identifier none block if_statement identifier block return_statement call attribute identifier identifier argument_list keyword_argument identifier identifier return_statement call attribute identifier identifier argument_list
Lists all SQL virtual machines in a resource group or subscription.
def nb_to_q_nums(nb) -> list: def q_num(cell): assert cell.metadata.tags return first(filter(lambda t: 'q' in t, cell.metadata.tags)) return [q_num(cell) for cell in nb['cells']]
module function_definition identifier parameters identifier type identifier block function_definition identifier parameters identifier block assert_statement attribute attribute identifier identifier identifier return_statement call identifier argument_list call identifier argument_list lambda lambda_parameters identifier comparison_operator string string_start string_content string_end identifier attribute attribute identifier identifier identifier return_statement list_comprehension call identifier argument_list identifier for_in_clause identifier subscript identifier string string_start string_content string_end
Gets question numbers from each cell in the notebook
def _init_threads(self): if self._io_thread is None: self._io_thread = Thread(target=self._select) self._io_thread.start() if self._writer_thread is None: self._writer_thread = Thread(target=self._writer) self._writer_thread.start()
module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment attribute identifier identifier call identifier argument_list keyword_argument identifier attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list if_statement comparison_operator attribute identifier identifier none block expression_statement assignment attribute identifier identifier call identifier argument_list keyword_argument identifier attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list
Initializes the IO and Writer threads
def partLon(ID, chart): abc = FORMULAS[ID][0] if chart.isDiurnal() else FORMULAS[ID][1] a = objLon(abc[0], chart) b = objLon(abc[1], chart) c = objLon(abc[2], chart) return c + b - a
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier conditional_expression subscript subscript identifier identifier integer call attribute identifier identifier argument_list subscript subscript identifier identifier integer expression_statement assignment identifier call identifier argument_list subscript identifier integer identifier expression_statement assignment identifier call identifier argument_list subscript identifier integer identifier expression_statement assignment identifier call identifier argument_list subscript identifier integer identifier return_statement binary_operator binary_operator identifier identifier identifier
Returns the longitude of an arabic part.
def write_chunk(cls, sock, chunk_type, payload=b''): chunk = cls.construct_chunk(chunk_type, payload) sock.sendall(chunk)
module function_definition identifier parameters identifier identifier identifier default_parameter identifier string string_start string_end block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list identifier
Write a single chunk to the connected client.
def hide_all(self): self.current = None for _v, (label, widget) in self._propbag.items(): label.grid_remove() widget.grid_remove()
module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier none for_statement pattern_list identifier tuple_pattern identifier identifier call attribute attribute identifier identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list
Hide all properties from property editor.
def unfederate(self, serverId): url = self._url + "/servers/{serverid}/unfederate".format( serverid=serverId) params = {"f" : "json"} return self._get(url=url, param_dict=params, proxy_port=self._proxy_port, proxy_url=self._proxy_ur)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier binary_operator attribute identifier identifier call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end string string_start string_content string_end return_statement call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier
This operation unfederates an ArcGIS Server from Portal for ArcGIS
def lower_folded_outputs(ir_blocks): folds, remaining_ir_blocks = extract_folds_from_ir_blocks(ir_blocks) if not remaining_ir_blocks: raise AssertionError(u'Expected at least one non-folded block to remain: {} {} ' u'{}'.format(folds, remaining_ir_blocks, ir_blocks)) output_block = remaining_ir_blocks[-1] if not isinstance(output_block, ConstructResult): raise AssertionError(u'Expected the last non-folded block to be ConstructResult, ' u'but instead was: {} {} ' u'{}'.format(type(output_block), output_block, ir_blocks)) converted_folds = { base_fold_location.get_location_name()[0]: _convert_folded_blocks(folded_ir_blocks) for base_fold_location, folded_ir_blocks in six.iteritems(folds) } new_output_fields = dict() for output_name, output_expression in six.iteritems(output_block.fields): new_output_expression = output_expression if isinstance(output_expression, FoldedContextField): base_fold_location_name = output_expression.fold_scope_location.get_location_name()[0] folded_ir_blocks = converted_folds[base_fold_location_name] new_output_expression = GremlinFoldedContextField( output_expression.fold_scope_location, folded_ir_blocks, output_expression.field_type) new_output_fields[output_name] = new_output_expression new_ir_blocks = remaining_ir_blocks[:-1] new_ir_blocks.append(ConstructResult(new_output_fields)) return new_ir_blocks
module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier if_statement not_operator identifier block raise_statement call identifier argument_list call attribute concatenated_string string string_start string_content string_end string string_start string_content string_end identifier argument_list identifier identifier identifier expression_statement assignment identifier subscript identifier unary_operator integer if_statement not_operator call identifier argument_list identifier identifier block raise_statement call identifier argument_list call attribute concatenated_string string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end identifier argument_list call identifier argument_list identifier identifier identifier expression_statement assignment identifier dictionary_comprehension pair subscript call attribute identifier identifier argument_list integer call identifier argument_list identifier for_in_clause pattern_list identifier identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list for_statement pattern_list identifier identifier call attribute identifier identifier argument_list attribute identifier identifier block expression_statement assignment identifier identifier if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier subscript call attribute attribute identifier identifier identifier argument_list integer expression_statement assignment identifier subscript identifier identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier identifier attribute identifier identifier expression_statement assignment subscript identifier identifier identifier expression_statement assignment identifier subscript identifier slice unary_operator integer expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier return_statement identifier
Lower standard folded output fields into GremlinFoldedContextField objects.
def registry(attr, base=type): class Registry(base): def __init__(cls, name, bases, attrs): super(Registry, cls).__init__(name, bases, attrs) if not hasattr(cls, '__registry__'): cls.__registry__ = {} key = getattr(cls, attr) if key is not NotImplemented: assert key not in cls.__registry__ cls.__registry__[key] = cls def __dispatch__(cls, key): try: return cls.__registry__[key] except KeyError: raise ValueError('Unknown %s: %s' % (attr, key)) return Registry
module function_definition identifier parameters identifier default_parameter identifier identifier block class_definition identifier argument_list identifier block function_definition identifier parameters identifier identifier identifier identifier block expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list identifier identifier identifier if_statement not_operator call identifier argument_list identifier string string_start string_content string_end block expression_statement assignment attribute identifier identifier dictionary expression_statement assignment identifier call identifier argument_list identifier identifier if_statement comparison_operator identifier identifier block assert_statement comparison_operator identifier attribute identifier identifier expression_statement assignment subscript attribute identifier identifier identifier identifier function_definition identifier parameters identifier identifier block try_statement block return_statement subscript attribute identifier identifier identifier except_clause identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier return_statement identifier
Generates a meta class to index sub classes by their keys.
def songname(song_name): try: song_name = splitext(song_name)[0] except IndexError: pass chars_filter = "()[]{}-:_/=+\"\'" words_filter = ('official', 'lyrics', 'audio', 'remixed', 'remix', 'video', 'full', 'version', 'music', 'mp3', 'hd', 'hq', 'uploaded') song_name = ''.join(map(lambda c: " " if c in chars_filter else c, song_name)) song_name = re.sub('|'.join(re.escape(key) for key in words_filter), "", song_name, flags=re.IGNORECASE) song_name = re.sub(' +', ' ', song_name) return song_name.strip()
module function_definition identifier parameters identifier block try_statement block expression_statement assignment identifier subscript call identifier argument_list identifier integer except_clause identifier block pass_statement expression_statement assignment identifier string string_start string_content escape_sequence escape_sequence string_end expression_statement assignment identifier tuple string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute string string_start string_end identifier argument_list call identifier argument_list lambda lambda_parameters identifier conditional_expression string string_start string_content string_end comparison_operator identifier identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier generator_expression call attribute identifier identifier argument_list identifier for_in_clause identifier identifier string string_start string_end identifier keyword_argument identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end identifier return_statement call attribute identifier identifier argument_list
Improves file name by removing crap words
def _handle_exception(): if sys.stderr: einfo = sys.exc_info() try: traceback.print_exception(einfo[0], einfo[1], einfo[2], None, sys.stderr) except IOError: pass finally: del einfo
module function_definition identifier parameters block if_statement attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list try_statement block expression_statement call attribute identifier identifier argument_list subscript identifier integer subscript identifier integer subscript identifier integer none attribute identifier identifier except_clause identifier block pass_statement finally_clause block delete_statement identifier
Print exceptions raised by subscribers to stderr.
def _get_acceptable_response_type(): if ('Accept' not in request.headers or request.headers['Accept'] in ALL_CONTENT_TYPES): return JSON acceptable_content_types = set( request.headers['ACCEPT'].strip().split(',')) if acceptable_content_types & HTML_CONTENT_TYPES: return HTML elif acceptable_content_types & JSON_CONTENT_TYPES: return JSON else: raise InvalidAPIUsage(406)
module function_definition identifier parameters block if_statement parenthesized_expression boolean_operator comparison_operator string string_start string_content string_end attribute identifier identifier comparison_operator subscript attribute identifier identifier string string_start string_content string_end identifier block return_statement identifier expression_statement assignment identifier call identifier argument_list call attribute call attribute subscript attribute identifier identifier string string_start string_content string_end identifier argument_list identifier argument_list string string_start string_content string_end if_statement binary_operator identifier identifier block return_statement identifier elif_clause binary_operator identifier identifier block return_statement identifier else_clause block raise_statement call identifier argument_list integer
Return the mimetype for this request.
def _read_next(cls, lines: List[str]) -> 'FilePatch': while True: if not lines: raise Exception("illegal file patch format: couldn't find line starting with '---'") line = lines[0] if line.startswith('---'): break lines.pop(0) assert lines[0].startswith('---') assert lines[1].startswith('+++') old_fn = lines.pop(0)[4:].strip() new_fn = lines.pop(0)[4:].strip() hunks = [] while lines: if not lines[0].startswith('@@'): break hunks.append(Hunk._read_next(lines)) return FilePatch(old_fn, new_fn, hunks)
module function_definition identifier parameters identifier typed_parameter identifier type generic_type identifier type_parameter type identifier type string string_start string_content string_end block while_statement true block if_statement not_operator identifier block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier subscript identifier integer if_statement call attribute identifier identifier argument_list string string_start string_content string_end block break_statement expression_statement call attribute identifier identifier argument_list integer assert_statement call attribute subscript identifier integer identifier argument_list string string_start string_content string_end assert_statement call attribute subscript identifier integer identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute subscript call attribute identifier identifier argument_list integer slice integer identifier argument_list expression_statement assignment identifier call attribute subscript call attribute identifier identifier argument_list integer slice integer identifier argument_list expression_statement assignment identifier list while_statement identifier block if_statement not_operator call attribute subscript identifier integer identifier argument_list string string_start string_content string_end block break_statement expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier return_statement call identifier argument_list identifier identifier identifier
Destructively extracts the next file patch from the line buffer.
def sign(self, consumer_secret, method, url, oauth_token_secret=None, **params): key = self._escape(consumer_secret) + b'&' if oauth_token_secret: key += self._escape(oauth_token_secret) return key.decode()
module function_definition identifier parameters identifier identifier identifier identifier default_parameter identifier none dictionary_splat_pattern identifier block expression_statement assignment identifier binary_operator call attribute identifier identifier argument_list identifier string string_start string_content string_end if_statement identifier block expression_statement augmented_assignment identifier call attribute identifier identifier argument_list identifier return_statement call attribute identifier identifier argument_list
Create a signature using PLAINTEXT.
def show_refund(self, refund_id): request = self._get('transactions/refunds/' + str(refund_id)) return self.responder(request)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator string string_start string_content string_end call identifier argument_list identifier return_statement call attribute identifier identifier argument_list identifier
Shows an existing refund transaction.
def _get_document(self, source): scheme_url = source if not source.startswith("http"): scheme_url = "http://%s" % source text = source try: text = urllib.urlopen(scheme_url).read() except: pass else: return (text, scheme_url) try: text = open(source, "r").read() except: pass else: return (text, source) return (text, None)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier identifier if_statement not_operator call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier binary_operator string string_start string_content string_end identifier expression_statement assignment identifier identifier try_statement block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier identifier argument_list except_clause block pass_statement else_clause block return_statement tuple identifier identifier try_statement block expression_statement assignment identifier call attribute call identifier argument_list identifier string string_start string_content string_end identifier argument_list except_clause block pass_statement else_clause block return_statement tuple identifier identifier return_statement tuple identifier none
helper, open a file or url and return the content and identifier
def start_listener(self): if self.sock is not None: self.sock.close() self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.sock.bind(('', self.asterix_settings.port)) self.sock.setblocking(False) print("Started on port %u" % self.asterix_settings.port)
module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier attribute identifier identifier integer expression_statement call attribute attribute identifier identifier identifier argument_list tuple string string_start string_end attribute attribute identifier identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list false expression_statement call identifier argument_list binary_operator string string_start string_content string_end attribute attribute identifier identifier identifier
start listening for packets
def update_tags(self, idlist, tags_add=None, tags_remove=None): tags = {} if tags_add: tags["add"] = self._listify(tags_add) if tags_remove: tags["remove"] = self._listify(tags_remove) d = { "ids": self._listify(idlist), "tags": tags, } return self._proxy.Bug.update_tags(d)
module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier dictionary if_statement identifier block expression_statement assignment subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list identifier if_statement identifier block expression_statement assignment subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end call attribute identifier identifier argument_list identifier pair string string_start string_content string_end identifier return_statement call attribute attribute attribute identifier identifier identifier identifier argument_list identifier
Updates the 'tags' field for a bug.
def _GetDenseDimensions(list_of_lists): if not isinstance(list_of_lists, (list, tuple)): return [] elif not list_of_lists: return [0] else: return [len(list_of_lists)] + _GetDenseDimensions(list_of_lists[0])
module function_definition identifier parameters identifier block if_statement not_operator call identifier argument_list identifier tuple identifier identifier block return_statement list elif_clause not_operator identifier block return_statement list integer else_clause block return_statement binary_operator list call identifier argument_list identifier call identifier argument_list subscript identifier integer
Returns the inferred dense dimensions of a list of lists.
def merge_dicts(dict1, dict2): tmp = dict1.copy() tmp.update(dict2) return tmp
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier return_statement identifier
Merge two dictionaries and return the result
def relative_script(lines): "Return a script that'll work in a relocatable environment." activate = "import os; activate_this=os.path.join(os.path.dirname(os.path.realpath(__file__)), 'activate_this.py'); exec(compile(open(activate_this).read(), activate_this, 'exec'), dict(__file__=activate_this)); del os, activate_this" activate_at = None for idx, line in reversed(list(enumerate(lines))): if line.split()[:3] == ['from', '__future__', 'import']: activate_at = idx + 1 break if activate_at is None: activate_at = 1 return lines[:activate_at] + ['', activate, ''] + lines[activate_at:]
module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier none for_statement pattern_list identifier identifier call identifier argument_list call identifier argument_list call identifier argument_list identifier block if_statement comparison_operator subscript call attribute identifier identifier argument_list slice integer list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end block expression_statement assignment identifier binary_operator identifier integer break_statement if_statement comparison_operator identifier none block expression_statement assignment identifier integer return_statement binary_operator binary_operator subscript identifier slice identifier list string string_start string_end identifier string string_start string_end subscript identifier slice identifier
Return a script that'll work in a relocatable environment.
def writes(notebook, fmt, version=nbformat.NO_CONVERT, **kwargs): metadata = deepcopy(notebook.metadata) rearrange_jupytext_metadata(metadata) fmt = copy(fmt) fmt = long_form_one_format(fmt, metadata) ext = fmt['extension'] format_name = fmt.get('format_name') jupytext_metadata = metadata.get('jupytext', {}) if ext == '.ipynb': jupytext_metadata.pop('text_representation', {}) if not jupytext_metadata: metadata.pop('jupytext', {}) return nbformat.writes(new_notebook(cells=notebook.cells, metadata=metadata), version, **kwargs) if not format_name: format_name = format_name_for_ext(metadata, ext, explicit_default=False) if format_name: fmt['format_name'] = format_name update_jupytext_formats_metadata(metadata, fmt) writer = TextNotebookConverter(fmt) return writer.writes(notebook, metadata)
module function_definition identifier parameters identifier identifier default_parameter identifier attribute identifier identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end dictionary if_statement comparison_operator identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end dictionary if_statement not_operator identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end dictionary return_statement call attribute identifier identifier argument_list call identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier identifier dictionary_splat identifier if_statement not_operator identifier block expression_statement assignment identifier call identifier argument_list identifier identifier keyword_argument identifier false if_statement identifier block expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement call identifier argument_list identifier identifier expression_statement assignment identifier call identifier argument_list identifier return_statement call attribute identifier identifier argument_list identifier identifier
Write a notebook to a string
def rmmod(module, force=False): cmd = ['rmmod'] if force: cmd.append('-f') cmd.append(module) log('Removing kernel module %s' % module, level=INFO) return subprocess.check_call(cmd)
module function_definition identifier parameters identifier default_parameter identifier false block expression_statement assignment identifier list string string_start string_content string_end if_statement identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier expression_statement call identifier argument_list binary_operator string string_start string_content string_end identifier keyword_argument identifier identifier return_statement call attribute identifier identifier argument_list identifier
Remove a module from the linux kernel
def _unzip_file(self, zip_file, out_folder): try: zf = zipfile.ZipFile(zip_file, 'r') zf.extractall(path=out_folder) zf.close() del zf return True except: return False
module function_definition identifier parameters identifier identifier identifier block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list delete_statement identifier return_statement true except_clause block return_statement false
unzips a file to a given folder
def needs(cls, *service_names): def _decorator(cls_): for service_name in service_names: cls_._services_requested[service_name] = "need" return cls_ return _decorator
module function_definition identifier parameters identifier list_splat_pattern identifier block function_definition identifier parameters identifier block for_statement identifier identifier block expression_statement assignment subscript attribute identifier identifier identifier string string_start string_content string_end return_statement identifier return_statement identifier
A class decorator to indicate that an XBlock class needs particular services.
def render_code(code, filetype, pygments_style): if filetype: lexer = pygments.lexers.get_lexer_by_name(filetype) formatter = pygments.formatters.HtmlFormatter(style=pygments_style) return pygments.highlight(code, lexer, formatter) else: return "<pre><code>{}</code></pre>".format(code)
module function_definition identifier parameters identifier identifier identifier block if_statement identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier return_statement call attribute identifier identifier argument_list identifier identifier identifier else_clause block return_statement call attribute string string_start string_content string_end identifier argument_list identifier
Renders a piece of code into HTML. Highlights syntax if filetype is specfied
def uniquify(value, seen_values): id = 1 new_value = value while new_value in seen_values: new_value = "%s%s" % (value, id) id += 1 seen_values.add(new_value) return new_value
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier integer expression_statement assignment identifier identifier while_statement comparison_operator identifier identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end tuple identifier identifier expression_statement augmented_assignment identifier integer expression_statement call attribute identifier identifier argument_list identifier return_statement identifier
Adds value to seen_values set and ensures it is unique
def _call(self, x, out=None): if self.domain == self.range: if out is None: out = 0 * x else: out.lincomb(0, x) else: result = self.range.zero() if out is None: out = result else: out.assign(result) return out
module function_definition identifier parameters identifier identifier default_parameter identifier none block if_statement comparison_operator attribute identifier identifier attribute identifier identifier block if_statement comparison_operator identifier none block expression_statement assignment identifier binary_operator integer identifier else_clause block expression_statement call attribute identifier identifier argument_list integer identifier else_clause block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list if_statement comparison_operator identifier none block expression_statement assignment identifier identifier else_clause block expression_statement call attribute identifier identifier argument_list identifier return_statement identifier
Return the zero vector or assign it to ``out``.
def add_attribute_model(self, name, attr, writeable_func=None, ): return self._field_registry.add_attribute_model( name, attr, writeable_func, self._part)
module function_definition identifier parameters identifier identifier identifier default_parameter identifier none block return_statement call attribute attribute identifier identifier identifier argument_list identifier identifier identifier attribute identifier identifier
Register a pre-existing AttributeModel to be added to the Block
def _init_glyph(self, plot, mapping, properties): ret = super(ColorbarPlot, self)._init_glyph(plot, mapping, properties) if self.colorbar: for k, v in list(self.handles.items()): if not k.endswith('color_mapper'): continue self._draw_colorbar(plot, v, k[:-12]) return ret
module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call attribute call identifier argument_list identifier identifier identifier argument_list identifier identifier identifier if_statement attribute identifier identifier block for_statement pattern_list identifier identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list block if_statement not_operator call attribute identifier identifier argument_list string string_start string_content string_end block continue_statement expression_statement call attribute identifier identifier argument_list identifier identifier subscript identifier slice unary_operator integer return_statement identifier
Returns a Bokeh glyph object and optionally creates a colorbar.
def submit_job(self, job_definition, parameters, job_name=None, queue=None): if job_name is None: job_name = _random_id() response = self._client.submit_job( jobName=job_name, jobQueue=queue or self.get_active_queue(), jobDefinition=job_definition, parameters=parameters ) return response['jobId']
module function_definition identifier parameters identifier identifier identifier default_parameter identifier none default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier boolean_operator identifier call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier return_statement subscript identifier string string_start string_content string_end
Wrap submit_job with useful defaults
def decode(self): report_dict = msgpack.unpackb(self.raw_report, raw=False) events = [IOTileEvent.FromDict(x) for x in report_dict.get('events', [])] readings = [IOTileReading.FromDict(x) for x in report_dict.get('data', [])] if 'device' not in report_dict: raise DataError("Invalid encoded FlexibleDictionaryReport that did not " "have a device key set with the device uuid") self.origin = report_dict['device'] self.report_id = report_dict.get("incremental_id", IOTileReading.InvalidReadingID) self.sent_timestamp = report_dict.get("device_sent_timestamp", 0) self.origin_streamer = report_dict.get("streamer_index") self.streamer_selector = report_dict.get("streamer_selector") self.lowest_id = report_dict.get('lowest_id') self.highest_id = report_dict.get('highest_id') return readings, events
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier false expression_statement assignment identifier list_comprehension call attribute identifier identifier argument_list identifier for_in_clause identifier call attribute identifier identifier argument_list string string_start string_content string_end list expression_statement assignment identifier list_comprehension call attribute identifier identifier argument_list identifier for_in_clause identifier call attribute identifier identifier argument_list string string_start string_content string_end list if_statement comparison_operator string string_start string_content string_end identifier block raise_statement call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end expression_statement assignment attribute identifier identifier subscript identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end integer expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end return_statement expression_list identifier identifier
Decode this report from a msgpack encoded binary blob.
def choice_default_invalidator(self, obj): invalid = [('Question', obj.question_id, True)] for pk in obj.voters.values_list('pk', flat=True): invalid.append(('User', pk, False)) return invalid
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list tuple string string_start string_content string_end attribute identifier identifier true for_statement identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end keyword_argument identifier true block expression_statement call attribute identifier identifier argument_list tuple string string_start string_content string_end identifier false return_statement identifier
Invalidated cached items when the Choice changes.