code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def parsed_file(config_file):
parser = ConfigParser(allow_no_value=True)
parser.readfp(config_file)
return parser | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list keyword_argument identifier true expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Parse an ini-style config file. |
def _post_json(self, instance, space=None, rel_path=None, extra_params=None):
model = type(instance)
if space is None and model not in (Space, Event):
raise Exception(
'In general, `API._post_json` should always '
'be called with a `space` argument.'
)
if 'number' in instance.data:
raise AttributeError(
'You cannot create a ticket which already has a number'
)
if not extra_params:
extra_params = {}
url = '{0}/{1}/{2}?{3}'.format(
settings.API_ROOT_PATH,
settings.API_VERSION,
rel_path or model.rel_path,
urllib.urlencode(extra_params),
)
response = requests.post(
url=url,
data=json.dumps(instance.data),
headers={
'X-Api-Key': self.key,
'X-Api-Secret': self.secret,
'Content-type': "application/json",
},
)
if response.status_code == 201:
instance = model(data=response.json())
instance.api = self
if space:
instance.space = space
return instance
else:
raise Exception(
'Code {0} returned from `{1}`. Response text: "{2}".'.format(
response.status_code,
url,
response.text
)
) | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier call identifier argument_list identifier if_statement boolean_operator comparison_operator identifier none comparison_operator identifier tuple identifier identifier block raise_statement call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end attribute identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end if_statement not_operator identifier block expression_statement assignment identifier dictionary expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier attribute identifier identifier boolean_operator identifier attribute identifier identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier call attribute identifier identifier argument_list attribute identifier identifier keyword_argument 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 string string_start string_content string_end if_statement comparison_operator attribute identifier identifier integer block expression_statement assignment identifier call identifier argument_list keyword_argument identifier call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier identifier if_statement identifier block expression_statement assignment attribute identifier identifier identifier return_statement identifier else_clause block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier identifier attribute identifier identifier | Base level method for updating data via the API |
def on_task_done(self, task):
task['status'] = self.taskdb.SUCCESS
task['lastcrawltime'] = time.time()
if 'schedule' in task:
if task['schedule'].get('auto_recrawl') and 'age' in task['schedule']:
task['status'] = self.taskdb.ACTIVE
next_exetime = task['schedule'].get('age')
task['schedule']['exetime'] = time.time() + next_exetime
self.put_task(task)
else:
del task['schedule']
self.update_task(task)
project = task['project']
self._cnt['5m'].event((project, 'success'), +1)
self._cnt['1h'].event((project, 'success'), +1)
self._cnt['1d'].event((project, 'success'), +1)
self._cnt['all'].event((project, 'success'), +1).event((project, 'pending'), -1)
logger.info('task done %(project)s:%(taskid)s %(url)s', task)
return task | module function_definition identifier parameters identifier identifier block expression_statement assignment subscript identifier string string_start string_content string_end attribute attribute identifier identifier identifier expression_statement assignment subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list if_statement comparison_operator string string_start string_content string_end identifier block if_statement boolean_operator call attribute subscript identifier string string_start string_content string_end identifier argument_list string string_start string_content string_end comparison_operator string string_start string_content string_end subscript identifier string string_start string_content string_end block expression_statement assignment subscript identifier string string_start string_content string_end attribute attribute identifier identifier identifier expression_statement assignment identifier call attribute subscript identifier string string_start string_content string_end identifier argument_list string string_start string_content string_end expression_statement assignment subscript subscript identifier string string_start string_content string_end string string_start string_content string_end binary_operator call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier else_clause block delete_statement subscript identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement call attribute subscript attribute identifier identifier string string_start string_content string_end identifier argument_list tuple identifier string string_start string_content string_end unary_operator integer expression_statement call attribute subscript attribute identifier identifier string string_start string_content string_end identifier argument_list tuple identifier string string_start string_content string_end unary_operator integer expression_statement call attribute subscript attribute identifier identifier string string_start string_content string_end identifier argument_list tuple identifier string string_start string_content string_end unary_operator integer expression_statement call attribute call attribute subscript attribute identifier identifier string string_start string_content string_end identifier argument_list tuple identifier string string_start string_content string_end unary_operator integer identifier argument_list tuple identifier string string_start string_content string_end unary_operator integer expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier return_statement identifier | Called when a task is done and success, called by `on_task_status` |
def _xfs_info_get_kv(serialized):
if serialized.startswith("="):
serialized = serialized[1:].strip()
serialized = serialized.replace(" = ", "=*** ").replace(" =", "=")
opt = []
for tkn in serialized.split(" "):
if not opt or "=" in tkn:
opt.append(tkn)
else:
opt[len(opt) - 1] = opt[len(opt) - 1] + " " + tkn
return [tuple(items.split("=")) for items in opt] | module function_definition identifier parameters identifier block if_statement call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier call attribute subscript identifier slice integer identifier argument_list expression_statement assignment identifier call attribute call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end identifier argument_list string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier list for_statement identifier call attribute identifier identifier argument_list string string_start string_content string_end block if_statement boolean_operator not_operator identifier comparison_operator string string_start string_content string_end identifier block expression_statement call attribute identifier identifier argument_list identifier else_clause block expression_statement assignment subscript identifier binary_operator call identifier argument_list identifier integer binary_operator binary_operator subscript identifier binary_operator call identifier argument_list identifier integer string string_start string_content string_end identifier return_statement list_comprehension call identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end for_in_clause identifier identifier | Parse one line of the XFS info output. |
def _id_for_pc(self, name):
if not name in self.pc2id_lut:
self.c.execute("INSERT INTO pcs (name) VALUES ( ? )", (name,))
self.pc2id_lut[name] = self.c.lastrowid
self.id2pc_lut[self.c.lastrowid] = name
return self.pc2id_lut[name] | module function_definition identifier parameters identifier identifier block if_statement not_operator comparison_operator identifier attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end tuple identifier expression_statement assignment subscript attribute identifier identifier identifier attribute attribute identifier identifier identifier expression_statement assignment subscript attribute identifier identifier attribute attribute identifier identifier identifier identifier return_statement subscript attribute identifier identifier identifier | Given the name of the PC, return the database identifier. |
def _build_index(maf_strm, ref_spec):
idx_strm = StringIO.StringIO()
bound_iter = functools.partial(genome_alignment_iterator,
reference_species=ref_spec)
hash_func = JustInTimeGenomeAlignmentBlock.build_hash
idx = IndexedFile(maf_strm, bound_iter, hash_func)
idx.write_index(idx_strm)
idx_strm.seek(0)
return idx_strm | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call identifier argument_list identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list integer return_statement identifier | Build an index for a MAF genome alig file and return StringIO of it. |
def default(cls):
"Make the current foreground color the default."
wAttributes = cls._get_text_attributes()
wAttributes &= ~win32.FOREGROUND_MASK
wAttributes |= win32.FOREGROUND_GREY
wAttributes &= ~win32.FOREGROUND_INTENSITY
cls._set_text_attributes(wAttributes) | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement augmented_assignment identifier unary_operator attribute identifier identifier expression_statement augmented_assignment identifier attribute identifier identifier expression_statement augmented_assignment identifier unary_operator attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier | Make the current foreground color the default. |
def stop_other_daemons(self):
if self.smbd.running:
self.smbd.stop()
if self.nmbd.running:
self.nmbd.stop() | module function_definition identifier parameters identifier block if_statement attribute attribute identifier identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list if_statement attribute attribute identifier identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list | Stop services already provided by main samba daemon |
def link_text(cls):
link = cls.__name__
if link.endswith('View'):
link = link[:-4]
return link | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier if_statement call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier subscript identifier slice unary_operator integer return_statement identifier | Return link text for this view. |
def _authenticate_x509(credentials, sock_info):
query = SON([('authenticate', 1),
('mechanism', 'MONGODB-X509')])
if credentials.username is not None:
query['user'] = credentials.username
elif sock_info.max_wire_version < 5:
raise ConfigurationError(
"A username is required for MONGODB-X509 authentication "
"when connected to MongoDB versions older than 3.4.")
sock_info.command('$external', query) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list list tuple string string_start string_content string_end integer tuple string string_start string_content string_end string string_start string_content string_end if_statement comparison_operator attribute identifier identifier none block expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier elif_clause comparison_operator attribute identifier identifier integer 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 call attribute identifier identifier argument_list string string_start string_content string_end identifier | Authenticate using MONGODB-X509. |
def _restore_coordinator(self):
transport_info = self.device.get_current_transport_info()
if transport_info is not None:
if transport_info['current_transport_state'] == 'PLAYING':
self.device.pause()
self._restore_queue()
if self.is_playing_queue and self.playlist_position > 0:
if self.playlist_position is not None:
self.playlist_position -= 1
self.device.play_from_queue(self.playlist_position, False)
if self.track_position is not None:
if self.track_position != "":
self.device.seek(self.track_position)
self.device.play_mode = self.play_mode
self.device.cross_fade = self.cross_fade
elif self.is_playing_cloud_queue:
pass
else:
if self.media_uri != "":
self.device.play_uri(
self.media_uri, self.media_metadata, start=False) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list if_statement comparison_operator identifier none block if_statement comparison_operator subscript identifier string string_start string_content string_end string string_start string_content string_end block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list if_statement boolean_operator attribute identifier identifier comparison_operator attribute identifier identifier integer block if_statement comparison_operator attribute identifier identifier none block expression_statement augmented_assignment attribute identifier identifier integer expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier false if_statement comparison_operator attribute identifier identifier none block if_statement comparison_operator attribute identifier identifier string string_start string_end block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement assignment attribute attribute identifier identifier identifier attribute identifier identifier expression_statement assignment attribute attribute identifier identifier identifier attribute identifier identifier elif_clause attribute identifier identifier block pass_statement else_clause block if_statement comparison_operator attribute identifier identifier string string_start string_end block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier attribute identifier identifier keyword_argument identifier false | Do the coordinator-only part of the restore. |
def toList(self):
date = self.date()
sign = '+' if date[0] >= 0 else '-'
date[0] = abs(date[0])
return list(sign) + date | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier conditional_expression string string_start string_content string_end comparison_operator subscript identifier integer integer string string_start string_content string_end expression_statement assignment subscript identifier integer call identifier argument_list subscript identifier integer return_statement binary_operator call identifier argument_list identifier identifier | Returns date as signed list. |
def compute_hash(attributes, ignored_attributes=None):
ignored_attributes = list(ignored_attributes) if ignored_attributes else []
tuple_attributes = _convert(attributes.copy(), ignored_attributes)
hasher = hashlib.sha256(str(tuple_attributes).encode('utf-8', errors='ignore'))
return hasher.hexdigest() | module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier conditional_expression call identifier argument_list identifier identifier list expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list call attribute call identifier argument_list identifier identifier argument_list string string_start string_content string_end keyword_argument identifier string string_start string_content string_end return_statement call attribute identifier identifier argument_list | Computes a hash code for the given dictionary that is safe for persistence round trips |
def vector_to_word(vector):
word = ""
for vec in vector:
word = word + int2char(vec)
return word | module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_end for_statement identifier identifier block expression_statement assignment identifier binary_operator identifier call identifier argument_list identifier return_statement identifier | Convert integer vectors to character vectors. |
def controller_event(self, channel, contr_nr, contr_val):
return self.midi_event(CONTROLLER, channel, contr_nr, contr_val) | module function_definition identifier parameters identifier identifier identifier identifier block return_statement call attribute identifier identifier argument_list identifier identifier identifier identifier | Return the bytes for a MIDI controller event. |
def _parse_src_js_var(self, variable):
src_url = 'http://115.com'
r = self.http.get(src_url)
soup = BeautifulSoup(r.content)
scripts = [script.text for script in soup.find_all('script')]
text = '\n'.join(scripts)
pattern = "%s\s*=\s*(.*);" % (variable.upper())
m = re.search(pattern, text)
if not m:
msg = 'Cannot parse source JavaScript for %s.' % variable
raise APIError(msg)
return json.loads(m.group(1).strip()) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement assignment identifier list_comprehension attribute identifier identifier for_in_clause identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier expression_statement assignment identifier binary_operator string string_start string_content string_end parenthesized_expression call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier if_statement not_operator identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end identifier raise_statement call identifier argument_list identifier return_statement call attribute identifier identifier argument_list call attribute call attribute identifier identifier argument_list integer identifier argument_list | Parse JavaScript variables in the source page |
def execute_query(self, query, values):
retval = self.cursor.execute(query, values)
self.__close_db()
return retval | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list return_statement identifier | Executes a query to the test_db and closes the connection afterwards. |
def returnPorts(self):
if self._gotPorts:
map(portpicker.return_port, self.ports)
self._gotPorts = False
self.ports = [] | module function_definition identifier parameters identifier block if_statement attribute identifier identifier block expression_statement call identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier false expression_statement assignment attribute identifier identifier list | deallocate specific ports on the current machine |
def stopReceivingBoxes(self, reason):
AMP.stopReceivingBoxes(self, reason)
log.removeObserver(self._emit) | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier | Stop observing log events. |
def _get_local_ref(region, ref_file, out_vcf_base):
out_file = "{0}.fa".format(out_vcf_base)
if not file_exists(out_file):
with pysam.Fastafile(ref_file) as in_pysam:
contig, start, end = region
seq = in_pysam.fetch(contig, int(start), int(end))
with open(out_file, "w") as out_handle:
out_handle.write(">{0}-{1}-{2}\n{3}".format(contig, start, end,
str(seq)))
with open(out_file) as in_handle:
in_handle.readline()
size = len(in_handle.readline().strip())
return out_file, size | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier if_statement not_operator call identifier argument_list identifier block with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list identifier as_pattern_target identifier block expression_statement assignment pattern_list identifier identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier call identifier argument_list identifier call identifier argument_list identifier with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier identifier identifier call identifier argument_list identifier with_statement with_clause with_item as_pattern call identifier argument_list identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list call attribute call attribute identifier identifier argument_list identifier argument_list return_statement expression_list identifier identifier | Retrieve a local FASTA file corresponding to the specified region. |
def avg(self):
if len(self.values) > 0:
return sum(self.values) / float(len(self.values))
else:
return None | module function_definition identifier parameters identifier block if_statement comparison_operator call identifier argument_list attribute identifier identifier integer block return_statement binary_operator call identifier argument_list attribute identifier identifier call identifier argument_list call identifier argument_list attribute identifier identifier else_clause block return_statement none | return the mean value |
def _load_score(self):
score = int(self.score_file.read())
self.score_file.seek(0, os.SEEK_SET)
return score | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list integer attribute identifier identifier return_statement identifier | Load the best score from file. |
def create_permissions_from_tuples(model, codename_tpls):
if codename_tpls:
model_cls = django_apps.get_model(model)
content_type = ContentType.objects.get_for_model(model_cls)
for codename_tpl in codename_tpls:
app_label, codename, name = get_from_codename_tuple(
codename_tpl, model_cls._meta.app_label
)
try:
Permission.objects.get(codename=codename, content_type=content_type)
except ObjectDoesNotExist:
Permission.objects.create(
name=name, codename=codename, content_type=content_type
)
verify_codename_exists(f"{app_label}.{codename}") | module function_definition identifier parameters identifier identifier block if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier for_statement identifier identifier block expression_statement assignment pattern_list identifier identifier identifier call identifier argument_list identifier attribute attribute identifier identifier identifier try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier except_clause identifier block expression_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier expression_statement call identifier argument_list string string_start interpolation identifier string_content interpolation identifier string_end | Creates custom permissions on model "model". |
def _clean(self):
found_ids = {}
nodes = [self._nodes[_node.Root.ID]]
while nodes:
node = nodes.pop()
found_ids[node.id] = None
nodes = nodes + node.children
for node_id in self._nodes:
if node_id in found_ids:
continue
logger.error('Dangling node: %s', node_id)
for node_id in found_ids:
if node_id in self._nodes:
continue
logger.error('Unregistered node: %s', node_id) | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary expression_statement assignment identifier list subscript attribute identifier identifier attribute attribute identifier identifier identifier while_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment subscript identifier attribute identifier identifier none expression_statement assignment identifier binary_operator identifier attribute identifier identifier for_statement identifier attribute identifier identifier block if_statement comparison_operator identifier identifier block continue_statement expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier for_statement identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block continue_statement expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier | Recursively check that all nodes are reachable. |
def doc_dict(self):
doc = {
'type': self.value_type,
'description': self.description,
'extended_description': self.details
}
return doc | module function_definition identifier parameters identifier 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 attribute identifier identifier return_statement identifier | Generate the documentation for this field. |
def dl_file(url, dest, chunk_size=6553):
import urllib3
http = urllib3.PoolManager()
r = http.request('GET', url, preload_content=False)
with dest.open('wb') as out:
while True:
data = r.read(chunk_size)
if data is None or len(data) == 0:
break
out.write(data)
r.release_conn() | module function_definition identifier parameters identifier identifier default_parameter identifier integer block import_statement dotted_name identifier 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 identifier keyword_argument identifier false with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list string string_start string_content string_end as_pattern_target identifier block while_statement true block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement boolean_operator comparison_operator identifier none comparison_operator call identifier argument_list identifier integer block break_statement expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list | Download `url` to `dest` |
def node_insert_before(self, node, new_node):
assert(not self.node_is_on_list(new_node))
assert(node is not new_node)
prev = self.node_prev(node)
assert(prev is not None)
self.node_set_prev(node, new_node)
self.node_set_next(new_node, node)
self.node_set_prev(new_node, prev)
self.node_set_next(prev, new_node) | module function_definition identifier parameters identifier identifier identifier block assert_statement parenthesized_expression not_operator call attribute identifier identifier argument_list identifier assert_statement parenthesized_expression comparison_operator identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier assert_statement parenthesized_expression comparison_operator identifier none expression_statement call attribute identifier identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list identifier identifier | Insert the new node before node. |
def iteritems(self):
sorted_data = sorted(self.data.iteritems(), self.cmp, self.key,
self.reverse)
for k,v in sorted_data:
yield k,v | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier for_statement pattern_list identifier identifier identifier block expression_statement yield expression_list identifier identifier | Sort and then iterate the dictionary |
def export_context(target_zip):
from django_productline import utils
context_file = tasks.get_context_path()
return utils.create_or_append_to_zip(context_file, target_zip, 'context.json') | module function_definition identifier parameters identifier block import_from_statement dotted_name identifier dotted_name identifier expression_statement assignment identifier call attribute identifier identifier argument_list return_statement call attribute identifier identifier argument_list identifier identifier string string_start string_content string_end | Append context.json to target_zip |
def authenticate(self, api_key):
self._api_key = api_key
self._session.auth = ('', self._api_key)
return self._verify_api_key() | module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute attribute identifier identifier identifier tuple string string_start string_end attribute identifier identifier return_statement call attribute identifier identifier argument_list | Logs user into Heroku with given api_key. |
def object_to_json(obj):
if isinstance(obj, (datetime.datetime, datetime.date, datetime.time)):
return obj.isoformat()
return str(obj) | module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier tuple attribute identifier identifier attribute identifier identifier attribute identifier identifier block return_statement call attribute identifier identifier argument_list return_statement call identifier argument_list identifier | Convert object that cannot be natively serialized by python to JSON representation. |
def accept_line(event):
" Accept the line regardless of where the cursor is. "
b = event.current_buffer
b.accept_action.validate_and_handle(event.cli, b) | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier identifier | Accept the line regardless of where the cursor is. |
def from_connections(cls, caption, connections):
root = ET.Element('datasource', caption=caption, version='10.0', inline='true')
outer_connection = ET.SubElement(root, 'connection')
outer_connection.set('class', 'federated')
named_conns = ET.SubElement(outer_connection, 'named-connections')
for conn in connections:
nc = ET.SubElement(named_conns,
'named-connection',
name=_make_unique_name(conn.dbclass),
caption=conn.server)
nc.append(conn._connectionXML)
return cls(root) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end 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 string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier string string_start string_content string_end for_statement identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier string string_start string_content string_end keyword_argument identifier call identifier argument_list attribute identifier identifier keyword_argument identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier return_statement call identifier argument_list identifier | Create a new Data Source give a list of Connections. |
def contains_all(self, array):
dtype = getattr(array, 'dtype', None)
if dtype is None:
dtype = np.result_type(*array)
return is_real_dtype(dtype) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end none if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list list_splat identifier return_statement call identifier argument_list identifier | Test if `array` is an array of real numbers. |
def command(state, args):
args = parser.parse_args(args[1:])
aid = state.results.parse_aid(args.aid, default_key='db')
query.update.reset(state.db, aid, args.episode) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list subscript identifier slice integer expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier keyword_argument identifier string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier identifier attribute identifier identifier | Reset anime watched episodes. |
def _find_pair(self, protocol, remote_candidate):
for pair in self._check_list:
if (pair.protocol == protocol and pair.remote_candidate == remote_candidate):
return pair
return None | module function_definition identifier parameters identifier identifier identifier block for_statement identifier attribute identifier identifier block if_statement parenthesized_expression boolean_operator comparison_operator attribute identifier identifier identifier comparison_operator attribute identifier identifier identifier block return_statement identifier return_statement none | Find a candidate pair in the check list. |
def FromReadings(cls, uuid, readings, sent_timestamp=0):
header = struct.pack("<BBHLLL", cls.ReportType, 0, len(readings)*16, uuid, sent_timestamp, 0)
packed_readings = bytearray()
for reading in readings:
packed_reading = struct.pack("<HHLLL", reading.stream, 0, reading.reading_id,
reading.raw_time, reading.value)
packed_readings += bytearray(packed_reading)
return BroadcastReport(bytearray(header) + packed_readings) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier integer block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier integer binary_operator call identifier argument_list identifier integer identifier identifier integer expression_statement assignment identifier call identifier argument_list for_statement identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier integer attribute identifier identifier attribute identifier identifier attribute identifier identifier expression_statement augmented_assignment identifier call identifier argument_list identifier return_statement call identifier argument_list binary_operator call identifier argument_list identifier identifier | Generate a broadcast report from a list of readings and a uuid. |
def find_comprehension_as_statement(node):
return (
isinstance(node, ast.Expr)
and isinstance(node.value, (ast.ListComp,
ast.DictComp,
ast.SetComp))
) | module function_definition identifier parameters identifier block return_statement parenthesized_expression boolean_operator call identifier argument_list identifier attribute identifier identifier call identifier argument_list attribute identifier identifier tuple attribute identifier identifier attribute identifier identifier attribute identifier identifier | Finds a comprehension as a statement |
def _smooth_best_span_estimates(self):
self._smoothed_best_spans = smoother.perform_smooth(self.x,
self._best_span_at_each_point,
MID_SPAN) | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier identifier | Apply a MID_SPAN smooth to the best span estimates at each observation. |
def eof():
@Parser
def eof_parser(text, index=0):
if index >= len(text):
return Value.success(index, None)
else:
return Value.failure(index, 'EOF')
return eof_parser | module function_definition identifier parameters block decorated_definition decorator identifier function_definition identifier parameters identifier default_parameter identifier integer block if_statement comparison_operator identifier call identifier argument_list identifier block return_statement call attribute identifier identifier argument_list identifier none else_clause block return_statement call attribute identifier identifier argument_list identifier string string_start string_content string_end return_statement identifier | Parser EOF flag of a string. |
def read_plain_byte_array(file_obj, count):
return [file_obj.read(struct.unpack(b"<i", file_obj.read(4))[0]) for i in range(count)] | module function_definition identifier parameters identifier identifier block return_statement list_comprehension call attribute identifier identifier argument_list subscript call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list integer integer for_in_clause identifier call identifier argument_list identifier | Read `count` byte arrays using the plain encoding. |
def list(self, node, elem, module, path):
nel, newm, path = self.sample_element(node, elem, module, path)
if path is None:
return
for kn in node.i_key:
self.node_handler.get(kn.keyword, self.ignore)(
kn, nel, newm, path)
self.process_children(node, nel, newm, path, node.i_key)
minel = node.search_one("min-elements")
self.add_copies(node, elem, nel, minel)
if self.annots:
self.list_comment(node, nel, minel) | module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment pattern_list identifier identifier identifier call attribute identifier identifier argument_list identifier identifier identifier identifier if_statement comparison_operator identifier none block return_statement for_statement identifier attribute identifier identifier block expression_statement call call attribute attribute identifier identifier identifier argument_list attribute identifier identifier attribute identifier identifier argument_list identifier identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier identifier identifier identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier identifier identifier identifier if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier identifier identifier | Create sample entries of a list. |
def fetch_entries(self):
data = []
for row in self.get_rows():
if exceeded_limit(self.limit, len(data)):
break
entry = row.find_all('td')
entry_dict = {}
show = entry[0].string
net = entry[1].string
if not self._match_query(show, net):
continue
entry_dict['show'] = show
entry_dict['net'] = net
entry_dict['time'] = entry[2].string
if ',' in entry[3].string:
entry_dict['viewers'] = entry[3].string.replace(',', '.')
else:
entry_dict['viewers'] = '0.' + entry[3].string
entry_dict['rating'] = entry[4].string
data.append(Entry(**entry_dict))
return data | module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement identifier call attribute identifier identifier argument_list block if_statement call identifier argument_list attribute identifier identifier call identifier argument_list identifier block break_statement expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier dictionary expression_statement assignment identifier attribute subscript identifier integer identifier expression_statement assignment identifier attribute subscript identifier integer identifier if_statement not_operator call attribute identifier identifier argument_list identifier identifier block continue_statement 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 identifier expression_statement assignment subscript identifier string string_start string_content string_end attribute subscript identifier integer identifier if_statement comparison_operator string string_start string_content string_end attribute subscript identifier integer identifier block expression_statement assignment subscript identifier string string_start string_content string_end call attribute attribute subscript identifier integer identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end else_clause block expression_statement assignment subscript identifier string string_start string_content string_end binary_operator string string_start string_content string_end attribute subscript identifier integer identifier expression_statement assignment subscript identifier string string_start string_content string_end attribute subscript identifier integer identifier expression_statement call attribute identifier identifier argument_list call identifier argument_list dictionary_splat identifier return_statement identifier | Fetch data and parse it to build a list of cable entries. |
def instances(self):
ist = lib.EnvGetNextInstanceInClass(self._env, self._cls, ffi.NULL)
while ist != ffi.NULL:
yield Instance(self._env, ist)
ist = lib.EnvGetNextInstanceInClass(self._env, self._cls, ist) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier while_statement comparison_operator identifier attribute identifier identifier block expression_statement yield call identifier argument_list attribute identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier identifier | Iterate over the instances of the class. |
def _make_mask(self, data, lon_str=LON_STR, lat_str=LAT_STR):
mask = False
for west, east, south, north in self.mask_bounds:
if west < east:
mask_lon = (data[lon_str] > west) & (data[lon_str] < east)
else:
mask_lon = (data[lon_str] < west) | (data[lon_str] > east)
mask_lat = (data[lat_str] > south) & (data[lat_str] < north)
mask |= mask_lon & mask_lat
return mask | module function_definition identifier parameters identifier identifier default_parameter identifier identifier default_parameter identifier identifier block expression_statement assignment identifier false for_statement pattern_list identifier identifier identifier identifier attribute identifier identifier block if_statement comparison_operator identifier identifier block expression_statement assignment identifier binary_operator parenthesized_expression comparison_operator subscript identifier identifier identifier parenthesized_expression comparison_operator subscript identifier identifier identifier else_clause block expression_statement assignment identifier binary_operator parenthesized_expression comparison_operator subscript identifier identifier identifier parenthesized_expression comparison_operator subscript identifier identifier identifier expression_statement assignment identifier binary_operator parenthesized_expression comparison_operator subscript identifier identifier identifier parenthesized_expression comparison_operator subscript identifier identifier identifier expression_statement augmented_assignment identifier binary_operator identifier identifier return_statement identifier | Construct the mask that defines a region on a given data's grid. |
def save_to_disk(self, filename_pattern=None):
if not self._converter:
raise RuntimeError(
'Must set _converter on subclass or via set_converter before calling '
'save_to_disk.')
pattern = filename_pattern or self._default_filename_pattern
if not pattern:
raise RuntimeError(
'Must specify provide a filename_pattern or set a '
'_default_filename_pattern on subclass.')
def save_to_disk_callback(test_record_obj):
proto = self._convert(test_record_obj)
output_to_file = callbacks.OutputToFile(pattern)
with output_to_file.open_output_file(test_record_obj) as outfile:
outfile.write(proto.SerializeToString())
return save_to_disk_callback | module function_definition identifier parameters identifier default_parameter identifier none block if_statement not_operator attribute identifier 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 identifier boolean_operator identifier attribute identifier identifier if_statement not_operator identifier block raise_statement call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list return_statement identifier | Returns a callback to convert test record to proto and save to disk. |
def _last(self, **spec):
for record in self._entries(spec).order_by(orm.desc(model.Entry.local_date),
orm.desc(model.Entry.id))[:1]:
return entry.Entry(record)
return None | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block for_statement identifier subscript call attribute call attribute identifier identifier argument_list identifier identifier argument_list call attribute identifier identifier argument_list attribute attribute identifier identifier identifier call attribute identifier identifier argument_list attribute attribute identifier identifier identifier slice integer block return_statement call attribute identifier identifier argument_list identifier return_statement none | Get the latest entry in this category, optionally including subcategories |
def schedule(dev):
for d in range(7):
dev.query_schedule(d)
for day in dev.schedule.values():
click.echo("Day %s, base temp: %s" % (day.day, day.base_temp))
current_hour = day.next_change_at
for hour in day.hours:
if current_hour == 0: continue
click.echo("\t[%s-%s] %s" % (current_hour, hour.next_change_at, hour.target_temp))
current_hour = hour.next_change_at | module function_definition identifier parameters identifier block for_statement identifier call identifier argument_list integer block expression_statement call attribute identifier identifier argument_list identifier for_statement identifier call attribute attribute identifier identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple attribute identifier identifier attribute identifier identifier expression_statement assignment identifier attribute identifier identifier for_statement identifier attribute identifier identifier block if_statement comparison_operator identifier integer block continue_statement expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content escape_sequence string_end tuple identifier attribute identifier identifier attribute identifier identifier expression_statement assignment identifier attribute identifier identifier | Gets the schedule from the thermostat. |
def register(self, name, path, plugin, description=None, final_words=None):
if name in self.recipes.keys():
raise RecipeExistsException("Recipe %s was already registered by %s" %
(name, self.recipes["name"].plugin.name))
self.recipes[name] = Recipe(name, path, plugin, description, final_words)
self.__log.debug("Recipe %s registered by %s" % (name, plugin.name))
return self.recipes[name] | module function_definition identifier parameters identifier identifier identifier identifier default_parameter identifier none default_parameter identifier none block if_statement 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 attribute attribute subscript attribute identifier identifier string string_start string_content string_end identifier identifier expression_statement assignment subscript attribute identifier identifier identifier call identifier argument_list identifier identifier identifier identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content string_end tuple identifier attribute identifier identifier return_statement subscript attribute identifier identifier identifier | Registers a new recipe. |
def stop(self):
self.prestop()
if not self._graceful:
self._graceful = True
self.stream.stop_stream()
self.audio.terminate()
msg = 'Stopped'
self.verbose_info(msg, log=False)
if self.log:
self.logging.info(msg)
if self.collect:
if self._data:
print('Collected result:')
print(' min: %10d' % self._data['min'])
print(' max: %10d' % self._data['max'])
print(' avg: %10d' % int(self._data['avg']))
self.poststop() | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list if_statement not_operator attribute identifier identifier block expression_statement assignment attribute identifier identifier true expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier false if_statement attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier if_statement attribute identifier identifier block if_statement attribute identifier identifier block expression_statement call identifier argument_list string string_start string_content string_end expression_statement call identifier argument_list binary_operator string string_start string_content string_end subscript attribute identifier identifier string string_start string_content string_end expression_statement call identifier argument_list binary_operator string string_start string_content string_end subscript attribute identifier identifier string string_start string_content string_end expression_statement call identifier argument_list binary_operator string string_start string_content string_end call identifier argument_list subscript attribute identifier identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list | Stop the stream and terminate PyAudio |
def download_api(branch=None) -> str:
habitica_github_api = 'https://api.github.com/repos/HabitRPG/habitica'
if not branch:
branch = requests.get(habitica_github_api + '/releases/latest').json()['tag_name']
curl = local['curl']['-sL', habitica_github_api + '/tarball/{}'.format(branch)]
tar = local['tar'][
'axzf', '-', '--wildcards', '*/website/server/controllers/api-v3/*', '--to-stdout']
grep = local['grep']['@api']
sed = local['sed']['-e', 's/^[ */]*//g', '-e', 's/ / /g', '-']
return (curl | tar | grep | sed)() | module function_definition identifier parameters default_parameter identifier none type identifier block expression_statement assignment identifier string string_start string_content string_end if_statement not_operator identifier block expression_statement assignment identifier subscript call attribute call attribute identifier identifier argument_list binary_operator identifier string string_start string_content string_end identifier argument_list 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 binary_operator identifier call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier subscript subscript identifier 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 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 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 return_statement call parenthesized_expression binary_operator binary_operator binary_operator identifier identifier identifier identifier argument_list | download API documentation from _branch_ of Habitica\'s repo on Github |
def remove(self, username, user_api, filename=None, force=False):
self.keys = API.__get_keys(filename)
self.username = username
user = user_api.find(username)[0]
if not force:
self.__confirm()
for key in self.__delete_keys():
operation = {'sshPublicKey': [(ldap3.MODIFY_DELETE, [key])]}
self.client.modify(user.entry_dn, operation) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier none default_parameter identifier false block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment identifier subscript call attribute identifier identifier argument_list identifier integer if_statement not_operator identifier block expression_statement call attribute identifier identifier argument_list for_statement identifier call attribute identifier identifier argument_list block expression_statement assignment identifier dictionary pair string string_start string_content string_end list tuple attribute identifier identifier list identifier expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier identifier | Remove specified SSH public key from specified user. |
def to_schema(self):
types = set()
generated_schemas = []
for schema_generator in self._schema_generators:
generated_schema = schema_generator.to_schema()
if len(generated_schema) == 1 and 'type' in generated_schema:
types.add(generated_schema['type'])
else:
generated_schemas.append(generated_schema)
if types:
if len(types) == 1:
(types,) = types
else:
types = sorted(types)
generated_schemas = [{'type': types}] + generated_schemas
if len(generated_schemas) == 1:
(result_schema,) = generated_schemas
elif generated_schemas:
result_schema = {'anyOf': generated_schemas}
else:
result_schema = {}
return result_schema | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier list for_statement identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement boolean_operator comparison_operator call identifier argument_list identifier integer comparison_operator string string_start string_content string_end identifier block expression_statement call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end else_clause block expression_statement call attribute identifier identifier argument_list identifier if_statement identifier block if_statement comparison_operator call identifier argument_list identifier integer block expression_statement assignment tuple_pattern identifier identifier else_clause block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier binary_operator list dictionary pair string string_start string_content string_end identifier identifier if_statement comparison_operator call identifier argument_list identifier integer block expression_statement assignment tuple_pattern identifier identifier elif_clause identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier else_clause block expression_statement assignment identifier dictionary return_statement identifier | Convert the current schema to a `dict`. |
def _get_all_refs(self, dep, handled_refs=None):
if handled_refs is None:
handled_refs = [dep]
else:
if dep in handled_refs:
return []
res = []
if dep in self.future_values_key_item:
res.extend(
self.future_values_key_item[dep]["dependencies"].values())
add = []
for h_d in res:
add.extend(self._get_all_refs(h_d, handled_refs))
res.extend(add)
return list(set(res)) | module function_definition identifier parameters identifier identifier default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier list identifier else_clause block if_statement comparison_operator identifier identifier block return_statement list expression_statement assignment identifier list if_statement comparison_operator identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute subscript subscript attribute identifier identifier identifier string string_start string_content string_end identifier argument_list expression_statement assignment identifier list for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list identifier return_statement call identifier argument_list call identifier argument_list identifier | get al list of all dependencies for the given item "dep" |
def _threaded_start(self):
self.active = True
self.thread = Thread(target=self._main_loop)
self.thread.setDaemon(True)
self.thread.start() | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier true 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 true expression_statement call attribute attribute identifier identifier identifier argument_list | Spawns a worker thread to do the expiration checks |
def flatten(self, obj):
return [self._serialize(f, obj) for f in self.fields] | module function_definition identifier parameters identifier identifier block return_statement list_comprehension call attribute identifier identifier argument_list identifier identifier for_in_clause identifier attribute identifier identifier | Return a list with the field values |
def _value_validate(self, value, rnge, identifier="Given"):
if value is not None and (value < rnge[0] or value > rnge[1]):
raise ValueError('%s value must be between %d and %d.'
% (identifier, rnge[0], rnge[1])) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier string string_start string_content string_end block if_statement boolean_operator comparison_operator identifier none parenthesized_expression boolean_operator comparison_operator identifier subscript identifier integer comparison_operator identifier subscript identifier integer block raise_statement call identifier argument_list binary_operator string string_start string_content string_end tuple identifier subscript identifier integer subscript identifier integer | Make sure a value is within a given range |
def build_traversal(self, traversal):
rhs_label = ':' + traversal.target_class.__label__
lhs_ident = self.build_source(traversal.source)
rhs_ident = traversal.name + rhs_label
self._ast['return'] = traversal.name
self._ast['result_class'] = traversal.target_class
rel_ident = self.create_ident()
stmt = _rel_helper(lhs=lhs_ident, rhs=rhs_ident, ident=rel_ident, **traversal.definition)
self._ast['match'].append(stmt)
if traversal.filters:
self.build_where_stmt(rel_ident, traversal.filters)
return traversal.name | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end attribute attribute identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier binary_operator attribute identifier identifier identifier expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end attribute identifier identifier expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier dictionary_splat attribute identifier identifier expression_statement call attribute subscript attribute identifier identifier string string_start string_content string_end identifier argument_list identifier if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier attribute identifier identifier return_statement attribute identifier identifier | traverse a relationship from a node to a set of nodes |
def _calculate_duration(start_time, finish_time):
if not (start_time and finish_time):
return 0
start = datetime.datetime.fromtimestamp(start_time)
finish = datetime.datetime.fromtimestamp(finish_time)
duration = finish - start
decimals = float(("0." + str(duration.microseconds)))
return duration.seconds + decimals | module function_definition identifier parameters identifier identifier block if_statement not_operator parenthesized_expression boolean_operator identifier identifier block return_statement integer 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 identifier expression_statement assignment identifier binary_operator identifier identifier expression_statement assignment identifier call identifier argument_list parenthesized_expression binary_operator string string_start string_content string_end call identifier argument_list attribute identifier identifier return_statement binary_operator attribute identifier identifier identifier | Calculates how long it took to execute the testcase. |
def render_constants():
generate_file("constant_enums.pxi", cython_enums, pjoin(root, 'zmq', 'backend', 'cython'))
generate_file("constants.pxi", constants_pyx, pjoin(root, 'zmq', 'backend', 'cython'))
generate_file("zmq_constants.h", ifndefs, pjoin(root, 'zmq', 'utils')) | module function_definition identifier parameters block expression_statement call identifier argument_list string string_start string_content string_end identifier call identifier argument_list identifier string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end expression_statement call identifier argument_list string string_start string_content string_end identifier call identifier argument_list identifier string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end expression_statement call identifier argument_list string string_start string_content string_end identifier call identifier argument_list identifier string string_start string_content string_end string string_start string_content string_end | render generated constant files from templates |
def load_ipython_extension(ipython):
from coconut import __coconut__
newvars = {}
for var, val in vars(__coconut__).items():
if not var.startswith("__"):
newvars[var] = val
ipython.push(newvars)
from coconut.convenience import cmd, parse, CoconutException
from coconut.terminal import logger
def magic(line, cell=None):
try:
if cell is None:
code = line
else:
line = line.strip()
if line:
cmd(line, interact=False)
code = cell
compiled = parse(code)
except CoconutException:
logger.display_exc()
else:
ipython.run_cell(compiled, shell_futures=False)
ipython.register_magic_function(magic, "line_cell", "coconut") | module function_definition identifier parameters identifier block import_from_statement dotted_name identifier dotted_name identifier expression_statement assignment identifier dictionary for_statement pattern_list identifier identifier call attribute call identifier argument_list identifier identifier argument_list block if_statement not_operator call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment subscript identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier import_from_statement dotted_name identifier identifier dotted_name identifier dotted_name identifier dotted_name identifier import_from_statement dotted_name identifier identifier dotted_name identifier function_definition identifier parameters identifier default_parameter identifier none block try_statement block if_statement comparison_operator identifier none block expression_statement assignment identifier identifier else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement identifier block expression_statement call identifier argument_list identifier keyword_argument identifier false expression_statement assignment identifier identifier expression_statement assignment identifier call identifier argument_list identifier except_clause identifier block expression_statement call attribute identifier identifier argument_list else_clause block expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier false expression_statement call attribute identifier identifier argument_list identifier string string_start string_content string_end string string_start string_content string_end | Loads Coconut as an IPython extension. |
def D(self, ID, asp):
obj = self.chart.getObject(ID).copy()
obj.relocate(obj.lon - asp)
ID = 'D_%s_%s' % (ID, asp)
return self.G(ID, obj.lat, obj.lon) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute call attribute attribute identifier identifier identifier argument_list identifier identifier argument_list expression_statement call attribute identifier identifier argument_list binary_operator attribute identifier identifier identifier expression_statement assignment identifier binary_operator string string_start string_content string_end tuple identifier identifier return_statement call attribute identifier identifier argument_list identifier attribute identifier identifier attribute identifier identifier | Returns the dexter aspect of an object. |
def relpath(self, path):
return os.path.relpath(path, start=self.path) | module function_definition identifier parameters identifier identifier block return_statement call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier attribute identifier identifier | Return a relative filepath to path from Dir path. |
def invalidate_all(self):
for fname in os.listdir(self.cache_path):
if fname.startswith(self.func.__name__ + "."):
os.remove(os.path.join(self.cache_path, fname)) | module function_definition identifier parameters identifier block for_statement identifier call attribute identifier identifier argument_list attribute identifier identifier block if_statement call attribute identifier identifier argument_list binary_operator attribute attribute identifier identifier identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list attribute identifier identifier identifier | Remove all files caching this function |
def bundle(self, ref, capture_exceptions=False):
from ..orm.exc import NotFoundError
if isinstance(ref, Dataset):
ds = ref
else:
try:
ds = self._db.dataset(ref)
except NotFoundError:
ds = None
if not ds:
try:
p = self.partition(ref)
ds = p._bundle.dataset
except NotFoundError:
ds = None
if not ds:
raise NotFoundError('Failed to find dataset for ref: {}'.format(ref))
b = Bundle(ds, self)
b.capture_exceptions = capture_exceptions
return b | module function_definition identifier parameters identifier identifier default_parameter identifier false block import_from_statement relative_import import_prefix dotted_name identifier identifier dotted_name identifier if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier identifier else_clause block try_statement block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier except_clause identifier block expression_statement assignment identifier none if_statement not_operator identifier block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier attribute attribute identifier identifier identifier except_clause identifier block expression_statement assignment identifier none if_statement not_operator identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment attribute identifier identifier identifier return_statement identifier | Return a bundle build on a dataset, with the given vid or id reference |
def btc_is_p2wsh_address( address ):
wver, whash = segwit_addr_decode(address)
if whash is None:
return False
if len(whash) != 32:
return False
return True | module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier if_statement comparison_operator identifier none block return_statement false if_statement comparison_operator call identifier argument_list identifier integer block return_statement false return_statement true | Is the given address a p2wsh address? |
def underscore(text):
return UNDERSCORE[1].sub(r'\1_\2', UNDERSCORE[0].sub(r'\1_\2', text)).lower() | module function_definition identifier parameters identifier block return_statement call attribute call attribute subscript identifier integer identifier argument_list string string_start string_content string_end call attribute subscript identifier integer identifier argument_list string string_start string_content string_end identifier identifier argument_list | Converts text that may be camelcased into an underscored format |
def _attach_endpoints(self):
for name, value in inspect.getmembers(self):
if inspect.isclass(value) and issubclass(value, self._Endpoint) and (value is not self._Endpoint):
endpoint_instance = value(self.requester)
setattr(self, endpoint_instance.endpoint_base, endpoint_instance)
if not hasattr(endpoint_instance, 'get_endpoints'):
endpoint_instance.get_endpoints = ()
if not hasattr(endpoint_instance, 'post_endpoints'):
endpoint_instance.post_endpoints = ()
if not hasattr(endpoint_instance, 'is_callable'):
endpoint_instance.is_callable = False
for endpoint in (endpoint_instance.get_endpoints + endpoint_instance.post_endpoints):
function = endpoint_instance.create_endpoint_function(endpoint)
function_name = endpoint.replace('/', '_')
setattr(endpoint_instance, function_name, function)
function.__name__ = str(function_name)
function.__doc__ = 'Tells the object to make a request to the {0} endpoint'.format(endpoint) | module function_definition identifier parameters identifier block for_statement pattern_list identifier identifier call attribute identifier identifier argument_list identifier block if_statement boolean_operator boolean_operator call attribute identifier identifier argument_list identifier call identifier argument_list identifier attribute identifier identifier parenthesized_expression comparison_operator identifier attribute identifier identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement call identifier argument_list identifier attribute 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 tuple if_statement not_operator call identifier argument_list identifier string string_start string_content string_end block expression_statement assignment attribute identifier identifier tuple if_statement not_operator call identifier argument_list identifier string string_start string_content string_end block expression_statement assignment attribute identifier identifier false for_statement identifier parenthesized_expression binary_operator attribute identifier identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list 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 expression_statement call identifier argument_list identifier identifier identifier expression_statement assignment attribute identifier identifier call identifier argument_list identifier expression_statement assignment attribute identifier identifier call attribute string string_start string_content string_end identifier argument_list identifier | Dynamically attaches endpoint callables to this client |
def _chunks(l, ncols):
assert isinstance(ncols, int), "ncols must be an integer"
for i in range(0, len(l), ncols):
yield l[i: i+ncols] | module function_definition identifier parameters identifier identifier block assert_statement call identifier argument_list identifier identifier string string_start string_content string_end for_statement identifier call identifier argument_list integer call identifier argument_list identifier identifier block expression_statement yield subscript identifier slice identifier binary_operator identifier identifier | Yield successive n-sized chunks from list, l. |
def write_close(self, code=None):
return self.write(self.parser.close(code), opcode=0x8, encode=False) | module function_definition identifier parameters identifier default_parameter identifier none block return_statement call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier integer keyword_argument identifier false | Write a close ``frame`` with ``code``. |
def do_alarm_update(mc, args):
fields = {}
fields['alarm_id'] = args.id
if args.state.upper() not in state_types:
errmsg = ('Invalid state, not one of [' +
', '.join(state_types) + ']')
print(errmsg)
return
fields['state'] = args.state
fields['lifecycle_state'] = args.lifecycle_state
fields['link'] = args.link
try:
alarm = mc.alarms.update(**fields)
except (osc_exc.ClientException, k_exc.HttpError) as he:
raise osc_exc.CommandError('%s\n%s' % (he.message, he.details))
else:
print(jsonutils.dumps(alarm, indent=2)) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier if_statement comparison_operator call attribute attribute identifier identifier identifier argument_list identifier block expression_statement assignment identifier parenthesized_expression binary_operator binary_operator string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list identifier string string_start string_content string_end expression_statement call identifier argument_list identifier return_statement expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier try_statement block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list dictionary_splat identifier except_clause as_pattern tuple attribute identifier identifier attribute identifier identifier as_pattern_target identifier block raise_statement call attribute identifier identifier argument_list binary_operator string string_start string_content escape_sequence string_end tuple attribute identifier identifier attribute identifier identifier else_clause block expression_statement call identifier argument_list call attribute identifier identifier argument_list identifier keyword_argument identifier integer | Update the alarm state. |
def hide(cls):
cls.el.style.display = "none"
cls.overlay.hide()
cls.bind() | module function_definition identifier parameters identifier block expression_statement assignment attribute attribute attribute identifier identifier identifier identifier string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list | Hide the log interface. |
def kinks(path, tol=1e-8):
kink_list = []
for idx in range(len(path)):
if idx == 0 and not path.isclosed():
continue
try:
u = path[(idx - 1) % len(path)].unit_tangent(1)
v = path[idx].unit_tangent(0)
u_dot_v = u.real*v.real + u.imag*v.imag
flag = False
except ValueError:
flag = True
if flag or abs(u_dot_v - 1) > tol:
kink_list.append(idx)
return kink_list | module function_definition identifier parameters identifier default_parameter identifier float block expression_statement assignment identifier list for_statement identifier call identifier argument_list call identifier argument_list identifier block if_statement boolean_operator comparison_operator identifier integer not_operator call attribute identifier identifier argument_list block continue_statement try_statement block expression_statement assignment identifier call attribute subscript identifier binary_operator parenthesized_expression binary_operator identifier integer call identifier argument_list identifier identifier argument_list integer expression_statement assignment identifier call attribute subscript identifier identifier identifier argument_list integer expression_statement assignment identifier binary_operator binary_operator attribute identifier identifier attribute identifier identifier binary_operator attribute identifier identifier attribute identifier identifier expression_statement assignment identifier false except_clause identifier block expression_statement assignment identifier true if_statement boolean_operator identifier comparison_operator call identifier argument_list binary_operator identifier integer identifier block expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | returns indices of segments that start on a non-differentiable joint. |
def sort(self, *args, **kwargs):
self._list.sort(*args, **kwargs)
for index, value in enumerate(self._list):
self._dict[value] = index | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement call attribute attribute identifier identifier identifier argument_list list_splat identifier dictionary_splat identifier for_statement pattern_list identifier identifier call identifier argument_list attribute identifier identifier block expression_statement assignment subscript attribute identifier identifier identifier identifier | Sort this setlist in place. |
def xmlinfo(self, id):
self._update_index()
for package in self._index.findall('packages/package'):
if package.get('id') == id:
return package
for collection in self._index.findall('collections/collection'):
if collection.get('id') == id:
return collection
raise ValueError('Package %r not found in index' % id) | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list for_statement identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end block if_statement comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end identifier block return_statement identifier for_statement identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end block if_statement comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end identifier block return_statement identifier raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier | Return the XML info record for the given item |
def _check_values(in_values):
out_values = []
for value in in_values:
out_values.append(value)
return tuple(out_values) | module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list identifier return_statement call identifier argument_list identifier | Check if values need to be converted before they get mogrify'd |
def source(self, source):
if isinstance(source, list):
source = source[0] if len(source) > 0 else None
self._source = source | module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier conditional_expression subscript identifier integer comparison_operator call identifier argument_list identifier integer none expression_statement assignment attribute identifier identifier identifier | When the source gets updated, update the select widget |
def clean_bootstrap_builds(self, _args):
if exists(join(self.ctx.build_dir, 'bootstrap_builds')):
shutil.rmtree(join(self.ctx.build_dir, 'bootstrap_builds')) | module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list call identifier argument_list attribute attribute identifier identifier identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list call identifier argument_list attribute attribute identifier identifier identifier string string_start string_content string_end | Delete all the bootstrap builds. |
def derive_fernet_key(input_key):
hkdf = HKDF(
algorithm=hashes.SHA256(),
length=32,
salt=salt,
info=info,
backend=backend,
)
return base64.urlsafe_b64encode(hkdf.derive(force_bytes(input_key))) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list keyword_argument identifier call attribute identifier identifier argument_list keyword_argument identifier integer keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier return_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list call identifier argument_list identifier | Derive a 32-bit b64-encoded Fernet key from arbitrary input key. |
def algorithms(self):
if self._algorithms is None:
uri = "/loadbalancers/algorithms"
resp, body = self.method_get(uri)
self._algorithms = [alg["name"] for alg in body["algorithms"]]
return self._algorithms | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier list_comprehension subscript identifier string string_start string_content string_end for_in_clause identifier subscript identifier string string_start string_content string_end return_statement attribute identifier identifier | Returns a list of available load balancing algorithms. |
def as_length(self, value):
new_vec = self.copy()
new_vec.length = value
return new_vec | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier identifier return_statement identifier | Return a new vector scaled to given length |
def available_modes_with_ids(self):
if not self._available_mode_ids:
all_modes = FIXED_MODES.copy()
self._available_mode_ids = all_modes
modes = self.get_available_modes()
try:
if modes:
simple_modes = dict(
[(m.get("type", m.get("name")), m.get("id"))
for m in modes]
)
all_modes.update(simple_modes)
self._available_mode_ids = all_modes
except TypeError:
_LOGGER.debug("Did not receive a valid response. Passing..")
return self._available_mode_ids | module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list try_statement block if_statement identifier block expression_statement assignment identifier call identifier argument_list list_comprehension tuple call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end for_in_clause identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier identifier except_clause identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement attribute identifier identifier | Return list of objects containing available mode name and id. |
def load_dbf(self, shapefile_name):
dbf_ext = 'dbf'
try:
self.dbf = open("%s.%s" % (shapefile_name, dbf_ext), "rb")
except IOError:
try:
self.dbf = open("%s.%s" % (shapefile_name, dbf_ext.upper()), "rb")
except IOError:
pass | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier string string_start string_content string_end try_statement block expression_statement assignment attribute identifier identifier call identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier string string_start string_content string_end except_clause identifier block try_statement block expression_statement assignment attribute identifier identifier call identifier argument_list binary_operator string string_start string_content string_end tuple identifier call attribute identifier identifier argument_list string string_start string_content string_end except_clause identifier block pass_statement | Attempts to load file with .dbf extension as both lower and upper case |
def encode_params(params, **kwargs):
cleaned = clean_params(params, **kwargs)
return json.dumps(cleaned) | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list identifier dictionary_splat identifier return_statement call attribute identifier identifier argument_list identifier | Clean and JSON-encode a dict of parameters. |
def _enter_single_subdir(root_dir):
current_cwd = os.getcwd()
try:
dest_dir = root_dir
dir_list = os.listdir(root_dir)
if len(dir_list) == 1:
first = os.path.join(root_dir, dir_list[0])
if os.path.isdir(first):
dest_dir = first
else:
dest_dir = root_dir
os.chdir(dest_dir)
yield dest_dir
finally:
os.chdir(current_cwd) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list try_statement block expression_statement assignment identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator call identifier argument_list identifier integer block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier subscript identifier integer if_statement call attribute attribute identifier identifier identifier argument_list identifier block expression_statement assignment identifier identifier else_clause block expression_statement assignment identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement yield identifier finally_clause block expression_statement call attribute identifier identifier argument_list identifier | if the given directory has just a single subdir, enter that |
def content_bytes(self):
get_message = \
self._communication.needle_positions.get_line_configuration_message
return get_message(self._line_number) | module function_definition identifier parameters identifier block expression_statement assignment identifier line_continuation attribute attribute attribute identifier identifier identifier identifier return_statement call identifier argument_list attribute identifier identifier | Return the start and stop needle. |
def trigger(self, username, project, branch, **build_params):
method = 'POST'
url = ('/project/{username}/{project}/tree/{branch}?'
'circle-token={token}'.format(
username=username, project=project,
branch=branch, token=self.client.api_token))
if build_params is not None:
json_data = self.client.request(method, url,
build_parameters=build_params)
else:
json_data = self.client.request(method, url)
return json_data | module function_definition identifier parameters identifier identifier identifier identifier dictionary_splat_pattern identifier block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier parenthesized_expression call attribute concatenated_string string string_start string_content string_end string string_start string_content string_end identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier attribute attribute identifier identifier identifier if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier keyword_argument identifier identifier else_clause block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier return_statement identifier | Trigger new build and return a summary of the build. |
def _split_column_and_labels(self, column_or_label):
column = None if column_or_label is None else self._get_column(column_or_label)
labels = [label for i, label in enumerate(self.labels) if column_or_label not in (i, label)]
return column, labels | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier conditional_expression none comparison_operator identifier none call attribute identifier identifier argument_list identifier expression_statement assignment identifier list_comprehension identifier for_in_clause pattern_list identifier identifier call identifier argument_list attribute identifier identifier if_clause comparison_operator identifier tuple identifier identifier return_statement expression_list identifier identifier | Return the specified column and labels of other columns. |
def _check_intersection(self, other):
props = ["_callables_db", "_reverse_callables_db", "_modules_dict"]
for prop in props:
self_dict = getattr(self, prop)
other_dict = getattr(other, prop)
keys_self = set(self_dict.keys())
keys_other = set(other_dict.keys())
for key in keys_self & keys_other:
svalue = self_dict[key]
ovalue = other_dict[key]
same_type = type(svalue) == type(ovalue)
if same_type:
list_comp = isinstance(svalue, list) and any(
[item not in svalue for item in ovalue]
)
str_comp = isinstance(svalue, str) and svalue != ovalue
dict_comp = isinstance(svalue, dict) and svalue != ovalue
comp = any([list_comp, str_comp, dict_comp])
if (not same_type) or (same_type and comp):
emsg = "Conflicting information between objects"
raise RuntimeError(emsg) | 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 for_statement identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list for_statement identifier binary_operator identifier identifier block expression_statement assignment identifier subscript identifier identifier expression_statement assignment identifier subscript identifier identifier expression_statement assignment identifier comparison_operator call identifier argument_list identifier call identifier argument_list identifier if_statement identifier block expression_statement assignment identifier boolean_operator call identifier argument_list identifier identifier call identifier argument_list list_comprehension comparison_operator identifier identifier for_in_clause identifier identifier expression_statement assignment identifier boolean_operator call identifier argument_list identifier identifier comparison_operator identifier identifier expression_statement assignment identifier boolean_operator call identifier argument_list identifier identifier comparison_operator identifier identifier expression_statement assignment identifier call identifier argument_list list identifier identifier identifier if_statement boolean_operator parenthesized_expression not_operator identifier parenthesized_expression boolean_operator identifier identifier block expression_statement assignment identifier string string_start string_content string_end raise_statement call identifier argument_list identifier | Check that intersection of two objects has the same information. |
def bind_download_buttons(cls):
def on_click(ev):
button_el = ev.target
form_el = button_el.parent.parent.parent
content = form_el.get(selector="textarea")[0].text
suffix = form_el.name
download_path = "as_file/%s.%s" % (cls.filename, suffix)
form_el.action = join(settings.API_PATH, download_path)
input_el = form_el.get(selector="input")[0]
input_el.value = content
for el in document.get(selector="button.output_download_button"):
el.bind("click", on_click) | module function_definition identifier parameters identifier block function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier attribute attribute attribute identifier identifier identifier identifier expression_statement assignment identifier attribute subscript call attribute identifier identifier argument_list keyword_argument identifier string string_start string_content string_end integer identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier binary_operator string string_start string_content string_end tuple attribute identifier identifier identifier expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier identifier expression_statement assignment identifier subscript call attribute identifier identifier argument_list keyword_argument identifier string string_start string_content string_end integer expression_statement assignment attribute identifier identifier identifier for_statement identifier call attribute identifier identifier argument_list keyword_argument identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier | Bind buttons to callbacks. |
def layer_mapproxy(request, catalog_slug, layer_uuid, path_info):
layer = get_object_or_404(Layer,
uuid=layer_uuid,
catalog__slug=catalog_slug)
if layer.service.type == 'Hypermap:WorldMap':
layer.service.url = layer.url
mp, yaml_config = get_mapproxy(layer)
query = request.META['QUERY_STRING']
if len(query) > 0:
path_info = path_info + '?' + query
params = {}
headers = {
'X-Script-Name': '/registry/{0}/layer/{1}/map/'.format(catalog_slug, layer.id),
'X-Forwarded-Host': request.META['HTTP_HOST'],
'HTTP_HOST': request.META['HTTP_HOST'],
'SERVER_NAME': request.META['SERVER_NAME'],
}
if path_info == '/config':
response = HttpResponse(yaml_config, content_type='text/plain')
return response
mp_response = mp.get(path_info, params, headers)
response = HttpResponse(mp_response.body, status=mp_response.status_int)
for header, value in mp_response.headers.iteritems():
response[header] = value
return response | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier if_statement comparison_operator attribute attribute identifier identifier identifier string string_start string_content string_end block expression_statement assignment attribute attribute identifier identifier identifier attribute identifier identifier expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end if_statement comparison_operator call identifier argument_list identifier integer block expression_statement assignment identifier binary_operator binary_operator identifier string string_start string_content string_end identifier expression_statement assignment identifier dictionary 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 attribute identifier identifier pair string string_start string_content string_end subscript attribute identifier identifier string string_start string_content string_end pair string string_start string_content string_end subscript attribute identifier identifier string string_start string_content string_end pair string string_start string_content string_end subscript attribute identifier identifier string string_start string_content string_end if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier string string_start string_content string_end return_statement identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier keyword_argument identifier attribute identifier identifier for_statement pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list block expression_statement assignment subscript identifier identifier identifier return_statement identifier | Get Layer with matching catalog and uuid |
def processData(self, times, response, test_num, trace_num, rep_num):
response = response * self._polarity
if rep_num == 0:
self.spike_counts = []
self.spike_latencies = []
self.spike_rates = []
fs = 1./(times[1] - times[0])
spike_times = spikestats.spike_times(response, self._threshold, fs)
self.spike_counts.append(len(spike_times))
if len(spike_times) > 0:
self.spike_latencies.append(spike_times[0])
else:
self.spike_latencies.append(np.nan)
self.spike_rates.append(spikestats.firing_rate(spike_times, times))
binsz = self._bins[1] - self._bins[0]
response_bins = spikestats.bin_spikes(spike_times, binsz)
self.appendData(response_bins, rep_num) | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier block expression_statement assignment identifier binary_operator identifier attribute identifier identifier if_statement comparison_operator identifier integer block expression_statement assignment attribute identifier identifier list expression_statement assignment attribute identifier identifier list expression_statement assignment attribute identifier identifier list expression_statement assignment identifier binary_operator float parenthesized_expression binary_operator subscript identifier integer subscript identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier attribute identifier identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list call identifier argument_list identifier if_statement comparison_operator call identifier argument_list identifier integer block expression_statement call attribute attribute identifier identifier identifier argument_list subscript identifier integer else_clause block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier binary_operator subscript attribute identifier identifier integer subscript attribute identifier identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list identifier identifier | Calulate spike times from raw response data |
def little_endian(self):
if not self._ptr:
raise BfdException("BFD not initialized")
return _bfd.get_bfd_attribute(self._ptr, BfdAttributes.IS_LITTLE_ENDIAN) | module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end return_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier | Return the little_endian attribute of the BFD file being processed. |
def delete_rows_csr(mat, indices):
if not isinstance(mat, scipy.sparse.csr_matrix):
raise ValueError("works only for CSR format -- use .tocsr() first")
indices = list(indices)
mask = np.ones(mat.shape[0], dtype=bool)
mask[indices] = False
return mat[mask] | module function_definition identifier parameters identifier identifier block if_statement not_operator call identifier argument_list identifier attribute attribute identifier identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list subscript attribute identifier identifier integer keyword_argument identifier identifier expression_statement assignment subscript identifier identifier false return_statement subscript identifier identifier | Remove the rows denoted by ``indices`` form the CSR sparse matrix ``mat``. |
def merge_with_default_options(self, config_opts):
return dict(list(self.defaults.items()) + list(config_opts.items())) | module function_definition identifier parameters identifier identifier block return_statement call identifier argument_list binary_operator call identifier argument_list call attribute attribute identifier identifier identifier argument_list call identifier argument_list call attribute identifier identifier argument_list | merge options from configuration file with the default options |
def _extract_methods(self):
service = self._service
all_urls = set()
urls_with_options = set()
if not service.http:
return
for rule in service.http.rules:
http_method, url = _detect_pattern_option(rule)
if not url or not http_method or not rule.selector:
_logger.error(u'invalid HTTP binding encountered')
continue
method_info = self._get_or_create_method_info(rule.selector)
if rule.body:
method_info.body_field_path = rule.body
if not self._register(http_method, url, method_info):
continue
all_urls.add(url)
if http_method == self._OPTIONS:
urls_with_options.add(url)
self._add_cors_options_selectors(all_urls - urls_with_options)
self._update_usage()
self._update_system_parameters() | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call identifier argument_list if_statement not_operator attribute identifier identifier block return_statement for_statement identifier attribute attribute identifier identifier identifier block expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier if_statement boolean_operator boolean_operator not_operator identifier not_operator identifier not_operator attribute identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end continue_statement expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier if_statement attribute identifier identifier block expression_statement assignment attribute identifier identifier attribute identifier identifier if_statement not_operator call attribute identifier identifier argument_list identifier identifier identifier block continue_statement expression_statement call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list binary_operator identifier identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list | Obtains the methods used in the service. |
def listen_for_updates(self):
self.toredis.subscribe(self.group_pubsub, callback=self.callback) | module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier keyword_argument identifier attribute identifier identifier | Attach a callback on the group pubsub |
def send_message(message, pipe='public'):
if pipe not in ['public', 'private']:
raise ValueError('pipe argument can be only "public" or "private"')
else:
pipe = pipe.upper()
pipe_path = PUBLIC_PIPE if pipe == 'PUBLIC' else PRIVATE_PIPE
pipeout = open(pipe_path, 'a')
pipeout.write('%s\n' % message)
pipeout.close() | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end block if_statement comparison_operator identifier list string string_start string_content string_end string string_start string_content string_end block raise_statement call identifier argument_list string string_start string_content string_end else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier conditional_expression identifier comparison_operator identifier string string_start string_content string_end identifier expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content escape_sequence string_end identifier expression_statement call attribute identifier identifier argument_list | writes message to pipe |
def dumps(obj, **kwargs):
t = type(obj)
if obj is True:
return u'true'
elif obj is False:
return u'false'
elif obj == None:
return u'null'
elif t == type('') or t == type(u''):
single = "'" in obj
double = '"' in obj
if single and double:
return json.dumps(obj)
elif single:
return '"' + obj + '"'
else:
return "'" + obj + "'"
elif t is float or t is int:
return str(obj)
elif t is dict:
return u'{' + u','.join([
_dumpkey(k) + u':' + dumps(v) for k, v in obj.items()
]) + '}'
elif t is list:
return u'[' + ','.join([dumps(el) for el in obj]) + u']'
else:
return u'' | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator identifier true block return_statement string string_start string_content string_end elif_clause comparison_operator identifier false block return_statement string string_start string_content string_end elif_clause comparison_operator identifier none block return_statement string string_start string_content string_end elif_clause boolean_operator comparison_operator identifier call identifier argument_list string string_start string_end comparison_operator identifier call identifier argument_list string string_start string_end block expression_statement assignment identifier comparison_operator string string_start string_content string_end identifier expression_statement assignment identifier comparison_operator string string_start string_content string_end identifier if_statement boolean_operator identifier identifier block return_statement call attribute identifier identifier argument_list identifier elif_clause identifier block return_statement binary_operator binary_operator string string_start string_content string_end identifier string string_start string_content string_end else_clause block return_statement binary_operator binary_operator string string_start string_content string_end identifier string string_start string_content string_end elif_clause boolean_operator comparison_operator identifier identifier comparison_operator identifier identifier block return_statement call identifier argument_list identifier elif_clause comparison_operator identifier identifier block return_statement binary_operator binary_operator string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list list_comprehension binary_operator binary_operator call identifier argument_list identifier string string_start string_content string_end call identifier argument_list identifier for_in_clause pattern_list identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end elif_clause comparison_operator identifier identifier block return_statement binary_operator binary_operator string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list list_comprehension call identifier argument_list identifier for_in_clause identifier identifier string string_start string_content string_end else_clause block return_statement string string_start string_end | Serialize ``obj`` to a JSON5-formatted ``str``. |
def output(self, data, context):
if self.transform:
if hasattr(self.transform, 'context'):
self.transform.context = context
data = self.transform(data)
if hasattr(data, 'read'):
data = data.read().decode('utf8')
if data is not None:
data = self.outputs(data)
if data:
sys.stdout.buffer.write(data)
if not data.endswith(b'\n'):
sys.stdout.buffer.write(b'\n')
return data | module function_definition identifier parameters identifier identifier identifier block if_statement attribute identifier identifier block if_statement call identifier argument_list attribute identifier identifier string string_start string_content string_end block expression_statement assignment attribute attribute identifier identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement call identifier argument_list identifier string string_start string_content string_end block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement identifier block expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list identifier if_statement not_operator call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end block expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content escape_sequence string_end return_statement identifier | Outputs the provided data using the transformations and output format specified for this CLI endpoint |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.