code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def format_docstring(elt, arg_comments:dict={}, alt_doc_string:str='', ignore_warn:bool=False)->str:
"Merge and format the docstring definition with `arg_comments` and `alt_doc_string`."
parsed = ""
doc = parse_docstring(inspect.getdoc(elt))
description = alt_doc_string or f"{doc['short_description']} {doc['long_description']}"
if description: parsed += f'\n\n{link_docstring(inspect.getmodule(elt), description)}'
resolved_comments = {**doc.get('comments', {}), **arg_comments}
args = inspect.getfullargspec(elt).args if not is_enum(elt.__class__) else elt.__members__.keys()
if resolved_comments: parsed += '\n'
for a in resolved_comments:
parsed += f'\n- *{a}*: {resolved_comments[a]}'
if a not in args and not ignore_warn: warn(f'Doc arg mismatch: {a}')
return_comment = arg_comments.get('return') or doc.get('return')
if return_comment: parsed += f'\n\n*return*: {return_comment}'
return parsed | module function_definition identifier parameters identifier typed_default_parameter identifier type identifier dictionary typed_default_parameter identifier type identifier string string_start string_end typed_default_parameter identifier type identifier false type identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier string string_start string_end expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list identifier expression_statement assignment identifier boolean_operator identifier string string_start interpolation subscript identifier string string_start string_content string_end string_content interpolation subscript identifier string string_start string_content string_end string_end if_statement identifier block expression_statement augmented_assignment identifier string string_start string_content escape_sequence escape_sequence interpolation call identifier argument_list call attribute identifier identifier argument_list identifier identifier string_end expression_statement assignment identifier dictionary dictionary_splat call attribute identifier identifier argument_list string string_start string_content string_end dictionary dictionary_splat identifier expression_statement assignment identifier conditional_expression attribute call attribute identifier identifier argument_list identifier identifier not_operator call identifier argument_list attribute identifier identifier call attribute attribute identifier identifier identifier argument_list if_statement identifier block expression_statement augmented_assignment identifier string string_start string_content escape_sequence string_end for_statement identifier identifier block expression_statement augmented_assignment identifier string string_start string_content escape_sequence interpolation identifier string_content interpolation subscript identifier identifier string_end if_statement boolean_operator comparison_operator identifier identifier not_operator identifier block expression_statement call identifier argument_list string string_start string_content interpolation identifier string_end expression_statement assignment identifier boolean_operator 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 if_statement identifier block expression_statement augmented_assignment identifier string string_start string_content escape_sequence escape_sequence interpolation identifier string_end return_statement identifier | Merge and format the docstring definition with `arg_comments` and `alt_doc_string`. |
def _image_loop(self):
if self.progress_bar and 'tqdm' in self.progress_bar.lower():
return tqdm(self.imgs, desc='Saving PNGs as flat PDFs', total=len(self.imgs), unit='PDFs')
else:
return self.imgs | module function_definition identifier parameters identifier block if_statement boolean_operator attribute identifier identifier comparison_operator string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list block return_statement call identifier argument_list attribute identifier identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier call identifier argument_list attribute identifier identifier keyword_argument identifier string string_start string_content string_end else_clause block return_statement attribute identifier identifier | Retrieve an iterable of images either with, or without a progress bar. |
def remaining_bytes(self, meta=True):
pos, self._pos = self._pos, len(self.buffer)
return self.buffer[pos:] | module function_definition identifier parameters identifier default_parameter identifier true block expression_statement assignment pattern_list identifier attribute identifier identifier expression_list attribute identifier identifier call identifier argument_list attribute identifier identifier return_statement subscript attribute identifier identifier slice identifier | Returns the remaining, unread bytes from the buffer. |
def authenticate(self, request, **kwargs):
self.request = request
if not self.request:
return None
state = self.request.GET.get('state')
code = self.request.GET.get('code')
nonce = kwargs.pop('nonce', None)
if not code or not state:
return None
reverse_url = self.get_settings('OIDC_AUTHENTICATION_CALLBACK_URL',
'oidc_authentication_callback')
token_payload = {
'client_id': self.OIDC_RP_CLIENT_ID,
'client_secret': self.OIDC_RP_CLIENT_SECRET,
'grant_type': 'authorization_code',
'code': code,
'redirect_uri': absolutify(
self.request,
reverse(reverse_url)
),
}
token_info = self.get_token(token_payload)
id_token = token_info.get('id_token')
access_token = token_info.get('access_token')
payload = self.verify_token(id_token, nonce=nonce)
if payload:
self.store_tokens(access_token, id_token)
try:
return self.get_or_create_user(access_token, id_token, payload)
except SuspiciousOperation as exc:
LOGGER.warning('failed to get or create user: %s', exc)
return None
return None | module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block expression_statement assignment attribute identifier identifier identifier if_statement not_operator attribute identifier identifier block return_statement none expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end none if_statement boolean_operator not_operator identifier not_operator identifier block return_statement none 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 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 string string_start string_content string_end pair string string_start string_content string_end identifier pair string string_start string_content string_end call identifier argument_list attribute identifier identifier call identifier argument_list identifier 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 expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier if_statement identifier block expression_statement call attribute identifier identifier argument_list identifier identifier try_statement block return_statement call attribute identifier identifier argument_list identifier identifier identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier return_statement none return_statement none | Authenticates a user based on the OIDC code flow. |
def _get_shells():
start = time.time()
if 'sh.last_shells' in __context__:
if start - __context__['sh.last_shells'] > 5:
__context__['sh.last_shells'] = start
else:
__context__['sh.shells'] = __salt__['cmd.shells']()
else:
__context__['sh.last_shells'] = start
__context__['sh.shells'] = __salt__['cmd.shells']()
return __context__['sh.shells'] | module function_definition identifier parameters block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator string string_start string_content string_end identifier block if_statement comparison_operator binary_operator identifier subscript identifier string string_start string_content string_end integer block expression_statement assignment subscript identifier string string_start string_content string_end identifier else_clause block expression_statement assignment subscript identifier string string_start string_content string_end call subscript identifier string string_start string_content string_end argument_list else_clause block 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 call subscript identifier string string_start string_content string_end argument_list return_statement subscript identifier string string_start string_content string_end | Return the valid shells on this system |
def _checksum(self):
for line in [self._line1, self._line2]:
check = 0
for char in line[:-1]:
if char.isdigit():
check += int(char)
if char == "-":
check += 1
if (check % 10) != int(line[-1]):
raise ChecksumError(self._platform + " " + line) | module function_definition identifier parameters identifier block for_statement identifier list attribute identifier identifier attribute identifier identifier block expression_statement assignment identifier integer for_statement identifier subscript identifier slice unary_operator integer block if_statement call attribute identifier identifier argument_list block expression_statement augmented_assignment identifier call identifier argument_list identifier if_statement comparison_operator identifier string string_start string_content string_end block expression_statement augmented_assignment identifier integer if_statement comparison_operator parenthesized_expression binary_operator identifier integer call identifier argument_list subscript identifier unary_operator integer block raise_statement call identifier argument_list binary_operator binary_operator attribute identifier identifier string string_start string_content string_end identifier | Performs the checksum for the current TLE. |
def _forward_mode(self, *args):
X: np.ndarray
dX: np.ndarray
X, dX = self._parse_dicts(*args)
if X is not None:
val = X
else:
val = self.X
if dX is not None:
diff = dX
else:
diff = np.ones_like(val)
return (val, diff) | module function_definition identifier parameters identifier list_splat_pattern identifier block expression_statement assignment identifier type attribute identifier identifier expression_statement assignment identifier type attribute identifier identifier expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list list_splat identifier if_statement comparison_operator identifier none block expression_statement assignment identifier identifier else_clause block expression_statement assignment identifier attribute identifier identifier 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 identifier return_statement tuple identifier identifier | Forward mode differentiation for variables |
def from_apps(cls, apps):
"Takes in an Apps and returns a VersionedProjectState matching it"
app_models = {}
for model in apps.get_models(include_swapped=True):
model_state = VersionedModelState.from_model(model)
app_models[(model_state.app_label, model_state.name.lower())] = model_state
return cls(app_models) | module function_definition identifier parameters identifier identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier dictionary for_statement identifier call attribute identifier identifier argument_list keyword_argument identifier true block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment subscript identifier tuple attribute identifier identifier call attribute attribute identifier identifier identifier argument_list identifier return_statement call identifier argument_list identifier | Takes in an Apps and returns a VersionedProjectState matching it |
def backend_add(cls, name, backend):
oper = cls.call(
'hosting.rproxy.server.create', cls.usable_id(name), backend)
cls.echo('Adding backend %s:%s into webaccelerator' %
(backend['ip'], backend['port']))
cls.display_progress(oper)
cls.echo('Backend added')
return oper | 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 call attribute identifier identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement identifier | Add a backend into a webaccelerator |
def clear(self):
value = self._sum / tf.cast(self._count, self._dtype)
with tf.control_dependencies([value]):
reset_value = self._sum.assign(tf.zeros_like(self._sum))
reset_count = self._count.assign(0)
with tf.control_dependencies([reset_value, reset_count]):
return tf.identity(value) | module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier with_statement with_clause with_item call attribute identifier identifier argument_list list identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list integer with_statement with_clause with_item call attribute identifier identifier argument_list list identifier identifier block return_statement call attribute identifier identifier argument_list identifier | Return the mean estimate and reset the streaming statistics. |
def _load_lines(self, filename, line_generator, suite, rules):
line_counter = 0
for line in line_generator:
line_counter += 1
if line.category in self.ignored_lines:
continue
if line.category == "test":
suite.addTest(Adapter(filename, line))
rules.saw_test()
elif line.category == "plan":
if line.skip:
rules.handle_skipping_plan(line)
return suite
rules.saw_plan(line, line_counter)
elif line.category == "bail":
rules.handle_bail(line)
return suite
elif line.category == "version":
rules.saw_version_at(line_counter)
rules.check(line_counter)
return suite | module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment identifier integer for_statement identifier identifier block expression_statement augmented_assignment identifier integer if_statement comparison_operator attribute identifier identifier attribute identifier identifier block continue_statement if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list elif_clause comparison_operator attribute identifier identifier string string_start string_content string_end block if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier return_statement identifier expression_statement call attribute identifier identifier argument_list identifier identifier elif_clause comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list identifier return_statement identifier elif_clause comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Load a suite with lines produced by the line generator. |
def unpack(data):
size, position = decoder._DecodeVarint(data, 0)
envelope = wire.Envelope()
envelope.ParseFromString(data[position:position+size])
return envelope | module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list subscript identifier slice identifier binary_operator identifier identifier return_statement identifier | unpack from delimited data |
def getDefaultTMParams(self, inputSize, numInputBits):
sampleSize = int(1.5 * numInputBits)
if numInputBits == 20:
activationThreshold = 18
minThreshold = 18
elif numInputBits == 10:
activationThreshold = 8
minThreshold = 8
else:
activationThreshold = int(numInputBits * .6)
minThreshold = activationThreshold
return {
"columnCount": inputSize,
"cellsPerColumn": 16,
"learn": True,
"learnOnOneCell": False,
"initialPermanence": 0.41,
"connectedPermanence": 0.6,
"permanenceIncrement": 0.1,
"permanenceDecrement": 0.03,
"minThreshold": minThreshold,
"basalPredictedSegmentDecrement": 0.003,
"apicalPredictedSegmentDecrement": 0.0,
"reducedBasalThreshold": int(activationThreshold*0.6),
"activationThreshold": activationThreshold,
"sampleSize": sampleSize,
"implementation": "ApicalTiebreak",
"seed": self.seed
} | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list binary_operator float identifier if_statement comparison_operator identifier integer block expression_statement assignment identifier integer expression_statement assignment identifier integer elif_clause comparison_operator identifier integer block expression_statement assignment identifier integer expression_statement assignment identifier integer else_clause block expression_statement assignment identifier call identifier argument_list binary_operator identifier float expression_statement assignment identifier identifier return_statement dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end integer pair string string_start string_content string_end true pair string string_start string_content string_end false pair string string_start string_content string_end float pair string string_start string_content string_end float pair string string_start string_content string_end float pair string string_start string_content string_end float pair string string_start string_content string_end identifier pair string string_start string_content string_end float pair string string_start string_content string_end float pair string string_start string_content string_end call identifier argument_list binary_operator identifier float pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end attribute identifier identifier | Returns a good default set of parameters to use in the TM region. |
def _create_rubber_bands_action(self):
icon = resources_path('img', 'icons', 'toggle-rubber-bands.svg')
self.action_toggle_rubberbands = QAction(
QIcon(icon),
self.tr('Toggle Scenario Outlines'), self.iface.mainWindow())
message = self.tr('Toggle rubber bands showing scenario extents.')
self.action_toggle_rubberbands.setStatusTip(message)
self.action_toggle_rubberbands.setWhatsThis(message)
self.action_toggle_rubberbands.setCheckable(True)
flag = setting('showRubberBands', False, expected_type=bool)
self.action_toggle_rubberbands.setChecked(flag)
self.action_toggle_rubberbands.triggered.connect(
self.dock_widget.toggle_rubber_bands)
self.add_action(self.action_toggle_rubberbands) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end expression_statement assignment attribute identifier identifier call identifier argument_list call identifier argument_list identifier call attribute identifier identifier argument_list string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list true expression_statement assignment identifier call identifier argument_list string string_start string_content string_end false keyword_argument identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list attribute attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier | Create action for toggling rubber bands. |
def shapeExprFor(self, id_: Union[ShExJ.shapeExprLabel, START]) -> Optional[ShExJ.shapeExpr]:
rval = self.schema.start if id_ is START else self.schema_id_map.get(str(id_))
return rval | module function_definition identifier parameters identifier typed_parameter identifier type generic_type identifier type_parameter type attribute identifier identifier type identifier type generic_type identifier type_parameter type attribute identifier identifier block expression_statement assignment identifier conditional_expression attribute attribute identifier identifier identifier comparison_operator identifier identifier call attribute attribute identifier identifier identifier argument_list call identifier argument_list identifier return_statement identifier | Return the shape expression that corresponds to id |
def maybe_resume_consumer(self):
if self._consumer is None or not self._consumer.is_paused:
return
if self.load < self.flow_control.resume_threshold:
self._consumer.resume()
else:
_LOGGER.debug("Did not resume, current load is %s", self.load) | module function_definition identifier parameters identifier block if_statement boolean_operator comparison_operator attribute identifier identifier none not_operator attribute attribute identifier identifier identifier block return_statement if_statement comparison_operator attribute identifier identifier attribute attribute identifier identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list else_clause block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier | Check the current load and resume the consumer if needed. |
def _fromdata(self, code, dtype, count, value, name=None):
self.code = int(code)
self.name = name if name else str(code)
self.dtype = TIFF_DATA_TYPES[dtype]
self.count = int(count)
self.value = value | module function_definition identifier parameters identifier identifier identifier identifier identifier default_parameter identifier none block expression_statement assignment attribute identifier identifier call identifier argument_list identifier expression_statement assignment attribute identifier identifier conditional_expression identifier identifier call identifier argument_list identifier expression_statement assignment attribute identifier identifier subscript identifier identifier expression_statement assignment attribute identifier identifier call identifier argument_list identifier expression_statement assignment attribute identifier identifier identifier | Initialize instance from arguments. |
def _read_message(self):
size = int(self.buf.read_line().decode("utf-8"))
return self.buf.read(size).decode("utf-8") | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list call attribute call attribute attribute identifier identifier identifier argument_list identifier argument_list string string_start string_content string_end return_statement call attribute call attribute attribute identifier identifier identifier argument_list identifier identifier argument_list string string_start string_content string_end | Reads a single size-annotated message from the server |
def _chunk_filter(self, extensions):
if isinstance(extensions, six.string_types):
extensions = extensions.split()
def _filter(chunk):
name = chunk['name']
if extensions is not None:
if not any(name.endswith(e) for e in extensions):
return False
for pattern in self.state.ignore_re:
if pattern.match(name):
return False
for pattern in self.state.ignore:
if fnmatch.fnmatchcase(name, pattern):
return False
return True
return _filter | module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list function_definition identifier parameters identifier block expression_statement assignment identifier subscript identifier string string_start string_content string_end if_statement comparison_operator identifier none block if_statement not_operator call identifier generator_expression call attribute identifier identifier argument_list identifier for_in_clause identifier identifier block return_statement false for_statement identifier attribute attribute identifier identifier identifier block if_statement call attribute identifier identifier argument_list identifier block return_statement false for_statement identifier attribute attribute identifier identifier identifier block if_statement call attribute identifier identifier argument_list identifier identifier block return_statement false return_statement true return_statement identifier | Create a filter from the extensions and ignore files |
def getextensibleindex(bunchdt, data, commdct, key, objname):
theobject = getobject(bunchdt, key, objname)
if theobject == None:
return None
theidd = iddofobject(data, commdct, key)
extensible_i = [
i for i in range(len(theidd)) if 'begin-extensible' in theidd[i]]
try:
extensible_i = extensible_i[0]
except IndexError:
return theobject | module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier identifier if_statement comparison_operator identifier none block return_statement none expression_statement assignment identifier call identifier argument_list identifier identifier identifier expression_statement assignment identifier list_comprehension identifier for_in_clause identifier call identifier argument_list call identifier argument_list identifier if_clause comparison_operator string string_start string_content string_end subscript identifier identifier try_statement block expression_statement assignment identifier subscript identifier integer except_clause identifier block return_statement identifier | get the index of the first extensible item |
def multi_session(self):
_val = 0
if "multi_session" in self._dict:
_val = self._dict["multi_session"]
if str(_val).lower() == 'all':
_val = -1
return int(_val) | module function_definition identifier parameters identifier block expression_statement assignment identifier integer if_statement comparison_operator string string_start string_content string_end attribute identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end if_statement comparison_operator call attribute call identifier argument_list identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier unary_operator integer return_statement call identifier argument_list identifier | convert the multi_session param a number |
def random_draft(card_class: CardClass, exclude=[]):
from . import cards
from .deck import Deck
deck = []
collection = []
for card in cards.db.keys():
if card in exclude:
continue
cls = cards.db[card]
if not cls.collectible:
continue
if cls.type == CardType.HERO:
continue
if cls.card_class and cls.card_class not in [card_class, CardClass.NEUTRAL]:
continue
collection.append(cls)
while len(deck) < Deck.MAX_CARDS:
card = random.choice(collection)
if deck.count(card.id) < card.max_count_in_deck:
deck.append(card.id)
return deck | module function_definition identifier parameters typed_parameter identifier type identifier default_parameter identifier list block import_from_statement relative_import import_prefix dotted_name identifier import_from_statement relative_import import_prefix dotted_name identifier dotted_name identifier expression_statement assignment identifier list expression_statement assignment identifier list for_statement identifier call attribute attribute identifier identifier identifier argument_list block if_statement comparison_operator identifier identifier block continue_statement expression_statement assignment identifier subscript attribute identifier identifier identifier if_statement not_operator attribute identifier identifier block continue_statement if_statement comparison_operator attribute identifier identifier attribute identifier identifier block continue_statement if_statement boolean_operator attribute identifier identifier comparison_operator attribute identifier identifier list identifier attribute identifier identifier block continue_statement expression_statement call attribute identifier identifier argument_list identifier while_statement comparison_operator call identifier argument_list identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier return_statement identifier | Return a deck of 30 random cards for the \a card_class |
def peak_interval(data, alpha=_alpha, npoints=_npoints):
peak = kde_peak(data,npoints)
x = np.sort(data.flat); n = len(x)
window = int(np.rint((1.0-alpha)*n))
starts = x[:n-window]; ends = x[window:]
widths = ends - starts
select = (peak >= starts) & (peak <= ends)
widths = widths[select]
if len(widths) == 0:
raise ValueError('Too few elements for interval calculation')
min_idx = np.argmin(widths)
lo = x[min_idx]
hi = x[min_idx+window]
return interval(peak,lo,hi) | module function_definition identifier parameters identifier default_parameter identifier identifier default_parameter identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list binary_operator parenthesized_expression binary_operator float identifier identifier expression_statement assignment identifier subscript identifier slice binary_operator identifier identifier expression_statement assignment identifier subscript identifier slice identifier expression_statement assignment identifier binary_operator identifier identifier expression_statement assignment identifier binary_operator parenthesized_expression comparison_operator identifier identifier parenthesized_expression comparison_operator identifier identifier expression_statement assignment identifier subscript identifier identifier if_statement comparison_operator call identifier argument_list identifier integer block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier subscript identifier identifier expression_statement assignment identifier subscript identifier binary_operator identifier identifier return_statement call identifier argument_list identifier identifier identifier | Identify interval using Gaussian kernel density estimator. |
def _normalize(image):
offset = tf.constant(MEAN_RGB, shape=[1, 1, 3])
image -= offset
scale = tf.constant(STDDEV_RGB, shape=[1, 1, 3])
image /= scale
return image | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier list integer integer integer expression_statement augmented_assignment identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier list integer integer integer expression_statement augmented_assignment identifier identifier return_statement identifier | Normalize the image to zero mean and unit variance. |
def remove_stale_sockets(self):
if self.opts.max_idle_time_seconds is not None:
with self.lock:
while (self.sockets and
self.sockets[-1].idle_time_seconds() > self.opts.max_idle_time_seconds):
sock_info = self.sockets.pop()
sock_info.close()
while True:
with self.lock:
if (len(self.sockets) + self.active_sockets >=
self.opts.min_pool_size):
break
if not self._socket_semaphore.acquire(False):
break
try:
sock_info = self.connect()
with self.lock:
self.sockets.appendleft(sock_info)
finally:
self._socket_semaphore.release() | module function_definition identifier parameters identifier block if_statement comparison_operator attribute attribute identifier identifier identifier none block with_statement with_clause with_item attribute identifier identifier block while_statement parenthesized_expression boolean_operator attribute identifier identifier comparison_operator call attribute subscript attribute identifier identifier unary_operator integer identifier argument_list attribute attribute identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list while_statement true block with_statement with_clause with_item attribute identifier identifier block if_statement parenthesized_expression comparison_operator binary_operator call identifier argument_list attribute identifier identifier attribute identifier identifier attribute attribute identifier identifier identifier block break_statement if_statement not_operator call attribute attribute identifier identifier identifier argument_list false block break_statement try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list with_statement with_clause with_item attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier finally_clause block expression_statement call attribute attribute identifier identifier identifier argument_list | Removes stale sockets then adds new ones if pool is too small. |
def dynamic_import(import_string):
lastdot = import_string.rfind('.')
if lastdot == -1:
return __import__(import_string, {}, {}, [])
module_name, attr = import_string[:lastdot], import_string[lastdot + 1:]
parent_module = __import__(module_name, {}, {}, [attr])
return getattr(parent_module, attr) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier unary_operator integer block return_statement call identifier argument_list identifier dictionary dictionary list expression_statement assignment pattern_list identifier identifier expression_list subscript identifier slice identifier subscript identifier slice binary_operator identifier integer expression_statement assignment identifier call identifier argument_list identifier dictionary dictionary list identifier return_statement call identifier argument_list identifier identifier | Dynamically import a module or object. |
def file_envs(self, load=None):
if load is None:
load = {}
load.pop('cmd', None)
return self.envs(**load) | module function_definition identifier parameters identifier default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier dictionary expression_statement call attribute identifier identifier argument_list string string_start string_content string_end none return_statement call attribute identifier identifier argument_list dictionary_splat identifier | Return environments for all backends for requests from fileclient |
def dump(self):
for modpath in sorted(self.map):
title = 'Imports in %s' % modpath
print('\n' + title + '\n' + '-'*len(title))
for name, value in sorted(self.map.get(modpath, {}).items()):
print(' %s -> %s' % (name, ', '.join(sorted(value)))) | module function_definition identifier parameters identifier block for_statement identifier call identifier argument_list attribute identifier identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end identifier expression_statement call identifier argument_list binary_operator binary_operator binary_operator string string_start string_content escape_sequence string_end identifier string string_start string_content escape_sequence string_end binary_operator string string_start string_content string_end call identifier argument_list identifier for_statement pattern_list identifier identifier call identifier argument_list call attribute call attribute attribute identifier identifier identifier argument_list identifier dictionary identifier argument_list block expression_statement call identifier argument_list binary_operator string string_start string_content string_end tuple identifier call attribute string string_start string_content string_end identifier argument_list call identifier argument_list identifier | Prints out the contents of the import map. |
def plot_prep_methods(df, prep, prepi, out_file_base, outtype, title=None,
size=None):
samples = df[(df["bamprep"] == prep)]["sample"].unique()
assert len(samples) >= 1, samples
out_file = "%s-%s.%s" % (out_file_base, samples[0], outtype)
df = df[df["category"].isin(cat_labels)]
_seaborn(df, prep, prepi, out_file, title, size)
return out_file | module function_definition identifier parameters identifier identifier identifier identifier identifier default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier call attribute subscript subscript identifier parenthesized_expression comparison_operator subscript identifier string string_start string_content string_end identifier string string_start string_content string_end identifier argument_list assert_statement comparison_operator call identifier argument_list identifier integer identifier expression_statement assignment identifier binary_operator string string_start string_content string_end tuple identifier subscript identifier integer identifier expression_statement assignment identifier subscript identifier call attribute subscript identifier string string_start string_content string_end identifier argument_list identifier expression_statement call identifier argument_list identifier identifier identifier identifier identifier identifier return_statement identifier | Plot comparison between BAM preparation methods. |
def roots(cls, degree, domain, kind):
basis_coefs = cls._basis_monomial_coefs(degree)
basis_poly = cls.functions_factory(basis_coefs, domain, kind)
return basis_poly.roots() | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier identifier return_statement call attribute identifier identifier argument_list | Return optimal collocation nodes for some orthogonal polynomial. |
def current_version():
import setuptools
version = [None]
def monkey_setup(**settings):
version[0] = settings['version']
old_setup = setuptools.setup
setuptools.setup = monkey_setup
import setup
reload(setup)
setuptools.setup = old_setup
return version[0] | module function_definition identifier parameters block import_statement dotted_name identifier expression_statement assignment identifier list none function_definition identifier parameters dictionary_splat_pattern identifier block expression_statement assignment subscript identifier integer subscript identifier string string_start string_content string_end expression_statement assignment identifier attribute identifier identifier expression_statement assignment attribute identifier identifier identifier import_statement dotted_name identifier expression_statement call identifier argument_list identifier expression_statement assignment attribute identifier identifier identifier return_statement subscript identifier integer | Get the current version number from setup.py |
def renew_session(self):
if ((not 'user_uid' in self.cookieInterface.cookies) or self.cookieInterface.cookies['user_uid']!=self.session_uid) and (not self.expired):
self.on_session_expired()
if self.expired:
self.session_uid = str(random.randint(1,999999999))
self.cookieInterface.set_cookie('user_uid', self.session_uid, str(self.session_timeout_seconds))
if self.timeout_timer:
self.timeout_timer.cancel()
self.timeout_timer = threading.Timer(self.session_timeout_seconds, self.on_session_expired)
self.expired = False
self.timeout_timer.start() | module function_definition identifier parameters identifier block if_statement boolean_operator parenthesized_expression boolean_operator parenthesized_expression not_operator comparison_operator string string_start string_content string_end attribute attribute identifier identifier identifier comparison_operator subscript attribute attribute identifier identifier identifier string string_start string_content string_end attribute identifier identifier parenthesized_expression not_operator attribute identifier identifier block expression_statement call attribute identifier identifier argument_list if_statement attribute identifier identifier block expression_statement assignment attribute identifier identifier call identifier argument_list call attribute identifier identifier argument_list integer integer expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end attribute identifier identifier call identifier argument_list attribute identifier identifier if_statement attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier false expression_statement call attribute attribute identifier identifier identifier argument_list | Have to be called on user actions to check and renew session |
def branchlist2branches(data, commdct, branchlist):
objkey = 'BranchList'.upper()
theobjects = data.dt[objkey]
fieldlists = []
objnames = [obj[1] for obj in theobjects]
for theobject in theobjects:
fieldlists.append(list(range(2, len(theobject))))
blists = extractfields(data, commdct, objkey, fieldlists)
thebranches = [branches for name, branches in zip(objnames, blists)
if name == branchlist]
return thebranches[0] | 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 expression_statement assignment identifier subscript attribute identifier identifier identifier expression_statement assignment identifier list expression_statement assignment identifier list_comprehension subscript identifier integer for_in_clause identifier identifier for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list call identifier argument_list integer call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier identifier identifier identifier expression_statement assignment identifier list_comprehension identifier for_in_clause pattern_list identifier identifier call identifier argument_list identifier identifier if_clause comparison_operator identifier identifier return_statement subscript identifier integer | get branches from the branchlist |
def image_undo():
if len(image_undo_list) <= 0:
print("no undos in memory")
return
[image, Z] = image_undo_list.pop(-1)
image.set_array(Z)
_pylab.draw() | module function_definition identifier parameters block if_statement comparison_operator call identifier argument_list identifier integer block expression_statement call identifier argument_list string string_start string_content string_end return_statement expression_statement assignment list_pattern identifier identifier call attribute identifier identifier argument_list unary_operator integer expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list | Undoes the last coarsen or smooth command. |
def _read_cache_from_file(self):
cache = {}
try:
with(open(self._cache_file_name, 'r')) as fp:
contents = fp.read()
cache = simplejson.loads(contents)
except (IOError, JSONDecodeError):
pass
return cache | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary try_statement block with_statement with_clause with_item as_pattern parenthesized_expression call identifier argument_list attribute identifier identifier string string_start string_content string_end as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier except_clause tuple identifier identifier block pass_statement return_statement identifier | Read the contents of the cache from a file on disk. |
def _setToDefaults(self):
try:
tmpObj = cfgpars.ConfigObjPars(self._taskParsObj.filename,
associatedPkg=\
self._taskParsObj.getAssocPkg(),
setAllToDefaults=self.taskName,
strict=False)
except Exception as ex:
msg = "Error Determining Defaults"
showerror(message=msg+'\n\n'+ex.message, title="Error Determining Defaults")
return
tmpObj.filename = self._taskParsObj.filename = ''
newParList = tmpObj.getParList()
try:
self.setAllEntriesFromParList(newParList)
self.checkAllTriggers('defaults')
self.updateTitle('')
self.showStatus("Loaded default "+self.taskName+" values via: "+ \
os.path.basename(tmpObj._original_configspec), keep=1)
except editpar.UnfoundParamError as pe:
showerror(message=str(pe), title="Error Setting to Default Values") | module function_definition identifier parameters identifier block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list attribute attribute identifier identifier identifier keyword_argument identifier line_continuation call attribute attribute identifier identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier false except_clause as_pattern identifier as_pattern_target identifier block expression_statement assignment identifier string string_start string_content string_end expression_statement call identifier argument_list keyword_argument identifier binary_operator binary_operator identifier string string_start string_content escape_sequence escape_sequence string_end attribute identifier identifier keyword_argument identifier string string_start string_content string_end return_statement expression_statement assignment attribute identifier identifier assignment attribute attribute identifier identifier identifier string string_start string_end expression_statement assignment identifier call attribute identifier identifier argument_list try_statement block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_end expression_statement call attribute identifier identifier argument_list binary_operator binary_operator binary_operator string string_start string_content string_end attribute identifier identifier string string_start string_content string_end line_continuation call attribute attribute identifier identifier identifier argument_list attribute identifier identifier keyword_argument identifier integer except_clause as_pattern attribute identifier identifier as_pattern_target identifier block expression_statement call identifier argument_list keyword_argument identifier call identifier argument_list identifier keyword_argument identifier string string_start string_content string_end | Load the default parameter settings into the GUI. |
def lookup(self, topic):
nsq.assert_valid_topic_name(topic)
return self._request('GET', '/lookup', fields={'topic': topic}) | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list identifier return_statement call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end keyword_argument identifier dictionary pair string string_start string_content string_end identifier | Returns producers for a topic. |
def _ExecuteTransaction(self, transaction):
def Action(connection):
connection.cursor.execute("START TRANSACTION")
for query in transaction:
connection.cursor.execute(query["query"], query["args"])
connection.cursor.execute("COMMIT")
return connection.cursor.fetchall()
return self._RetryWrapper(Action) | module function_definition identifier parameters identifier identifier block function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end for_statement identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end return_statement call attribute attribute identifier identifier identifier argument_list return_statement call attribute identifier identifier argument_list identifier | Get connection from pool and execute transaction. |
def linkorcopy(self, src, dst):
if os.path.isdir(dst):
log.warn('linkorcopy given a directory as destination. '
'Use caution.')
log.debug('src: %s dst: %s', src, dst)
elif os.path.exists(dst):
os.unlink(dst)
elif not os.path.exists(os.path.dirname(dst)):
os.makedirs(os.path.dirname(dst))
if self.linkfiles:
log.debug('Linking: %s -> %s', src, dst)
os.link(src, dst)
else:
log.debug('Copying: %s -> %s', src, dst)
shutil.copy2(src, dst) | module function_definition identifier parameters identifier identifier identifier block if_statement call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call attribute identifier 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 identifier elif_clause call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier elif_clause not_operator call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier expression_statement call attribute identifier identifier argument_list identifier identifier else_clause block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier expression_statement call attribute identifier identifier argument_list identifier identifier | hardlink src file to dst if possible, otherwise copy. |
def load(self, model):
self._dawg.load(find_data(model))
self._loaded_model = True | module function_definition identifier parameters identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list call identifier argument_list identifier expression_statement assignment attribute identifier identifier true | Load pickled DAWG from disk. |
def accel_toggle_transparency(self, *args):
self.transparency_toggled = not self.transparency_toggled
self.settings.styleBackground.triggerOnChangedValue(
self.settings.styleBackground, 'transparency'
)
return True | module function_definition identifier parameters identifier list_splat_pattern identifier block expression_statement assignment attribute identifier identifier not_operator attribute identifier identifier expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list attribute attribute identifier identifier identifier string string_start string_content string_end return_statement true | Callback to toggle transparency. |
def shutdown_connections(self):
if not self.is_shutting_down:
self.set_state(self.STATE_SHUTTING_DOWN)
for name in self.connections:
if self.connections[name].is_running:
self.connections[name].shutdown() | module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier for_statement identifier attribute identifier identifier block if_statement attribute subscript attribute identifier identifier identifier identifier block expression_statement call attribute subscript attribute identifier identifier identifier identifier argument_list | This method closes the connections to RabbitMQ. |
def create_command(
principal, permissions, endpoint_plus_path, notify_email, notify_message
):
if not principal:
raise click.UsageError("A security principal is required for this command")
endpoint_id, path = endpoint_plus_path
principal_type, principal_val = principal
client = get_client()
if principal_type == "identity":
principal_val = maybe_lookup_identity_id(principal_val)
if not principal_val:
raise click.UsageError(
"Identity does not exist. "
"Use --provision-identity to auto-provision an identity."
)
elif principal_type == "provision-identity":
principal_val = maybe_lookup_identity_id(principal_val, provision=True)
principal_type = "identity"
if not notify_email:
notify_message = None
rule_data = assemble_generic_doc(
"access",
permissions=permissions,
principal=principal_val,
principal_type=principal_type,
path=path,
notify_email=notify_email,
notify_message=notify_message,
)
res = client.add_endpoint_acl_rule(endpoint_id, rule_data)
formatted_print(
res,
text_format=FORMAT_TEXT_RECORD,
fields=[("Message", "message"), ("Rule ID", "access_id")],
) | module function_definition identifier parameters identifier identifier identifier identifier identifier block if_statement not_operator identifier block raise_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment pattern_list identifier identifier identifier expression_statement assignment pattern_list identifier identifier identifier expression_statement assignment identifier call identifier argument_list if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list identifier if_statement not_operator identifier block raise_statement call attribute identifier identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end elif_clause comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier true expression_statement assignment identifier string string_start string_content string_end if_statement not_operator identifier block expression_statement assignment identifier none expression_statement assignment identifier call identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement call identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier list tuple string string_start string_content string_end string string_start string_content string_end tuple string string_start string_content string_end string string_start string_content string_end | Executor for `globus endpoint permission create` |
def without_extra_phrases(self):
name = re.sub(r'\s*\([^)]*\)?\s*$', '', self.name)
name = re.sub(r'(?i)\s* formerly.*$', '', name)
name = re.sub(r'(?i)\s*and its affiliates$', '', name)
name = re.sub(r'\bet al\b', '', name)
if "-" in name:
hyphen_parts = name.rsplit("-", 1)
if len(hyphen_parts[1]) < len(hyphen_parts[0]) and re.search(r'(\w{4,}|\s+)$', hyphen_parts[0]) and not re.match(r'^([a-zA-Z]|[0-9]+)$', hyphen_parts[1]):
name = hyphen_parts[0].strip()
return name | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end identifier if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end integer if_statement boolean_operator boolean_operator comparison_operator call identifier argument_list subscript identifier integer call identifier argument_list subscript identifier integer call attribute identifier identifier argument_list string string_start string_content string_end subscript identifier integer not_operator call attribute identifier identifier argument_list string string_start string_content string_end subscript identifier integer block expression_statement assignment identifier call attribute subscript identifier integer identifier argument_list return_statement identifier | Removes parenthethical and dashed phrases |
def from_cli_multi_ifos(opt, length_dict, delta_f_dict,
low_frequency_cutoff_dict, ifos, strain_dict=None,
**kwargs):
psd = {}
for ifo in ifos:
if strain_dict is not None:
strain = strain_dict[ifo]
else:
strain = None
psd[ifo] = from_cli_single_ifo(opt, length_dict[ifo], delta_f_dict[ifo],
low_frequency_cutoff_dict[ifo], ifo,
strain=strain, **kwargs)
return psd | module function_definition identifier parameters identifier identifier identifier identifier identifier default_parameter identifier none dictionary_splat_pattern identifier block expression_statement assignment identifier dictionary for_statement identifier identifier block if_statement comparison_operator identifier none block expression_statement assignment identifier subscript identifier identifier else_clause block expression_statement assignment identifier none expression_statement assignment subscript identifier identifier call identifier argument_list identifier subscript identifier identifier subscript identifier identifier subscript identifier identifier identifier keyword_argument identifier identifier dictionary_splat identifier return_statement identifier | Get the PSD for all ifos when using the multi-detector CLI |
def trunc_str(s: str) -> str:
if len(s) > max_str_size:
i = max(0, (max_str_size - 3) // 2)
j = max(0, max_str_size - 3 - i)
s = s[:i] + "..." + s[-j:]
return s | module function_definition identifier parameters typed_parameter identifier type identifier type identifier block if_statement comparison_operator call identifier argument_list identifier identifier block expression_statement assignment identifier call identifier argument_list integer binary_operator parenthesized_expression binary_operator identifier integer integer expression_statement assignment identifier call identifier argument_list integer binary_operator binary_operator identifier integer identifier expression_statement assignment identifier binary_operator binary_operator subscript identifier slice identifier string string_start string_content string_end subscript identifier slice unary_operator identifier return_statement identifier | Truncate strings to maximum length. |
def register_plugin_dir(path):
import glob
for f in glob.glob(path + '/*.py'):
for k, v in load_plugins_from_module(f).items():
if k:
global_registry[k] = v | module function_definition identifier parameters identifier block import_statement dotted_name identifier for_statement identifier call attribute identifier identifier argument_list binary_operator identifier string string_start string_content string_end block for_statement pattern_list identifier identifier call attribute call identifier argument_list identifier identifier argument_list block if_statement identifier block expression_statement assignment subscript identifier identifier identifier | Find plugins in given directory |
def removeFileSafely(filename,clobber=True):
if filename is not None and filename.strip() != '':
if os.path.exists(filename) and clobber: os.remove(filename) | module function_definition identifier parameters identifier default_parameter identifier true block if_statement boolean_operator comparison_operator identifier none comparison_operator call attribute identifier identifier argument_list string string_start string_end block if_statement boolean_operator call attribute attribute identifier identifier identifier argument_list identifier identifier block expression_statement call attribute identifier identifier argument_list identifier | Delete the file specified, but only if it exists and clobber is True. |
def xor(a, b):
return bytearray(i ^ j for i, j in zip(a, b)) | module function_definition identifier parameters identifier identifier block return_statement call identifier generator_expression binary_operator identifier identifier for_in_clause pattern_list identifier identifier call identifier argument_list identifier identifier | Bitwise xor on equal length bytearrays. |
def command(state, args):
if len(args) > 1:
print(f'Usage: {args[0]}')
return
db = state.db
_refresh_incomplete_anime(db)
_fix_cached_completed(db) | module function_definition identifier parameters identifier identifier block if_statement comparison_operator call identifier argument_list identifier integer block expression_statement call identifier argument_list string string_start string_content interpolation subscript identifier integer string_end return_statement expression_statement assignment identifier attribute identifier identifier expression_statement call identifier argument_list identifier expression_statement call identifier argument_list identifier | Fix cache issues caused by schema pre-v4. |
def data_layout(self):
with ffi.OutputString(owned=False) as outmsg:
ffi.lib.LLVMPY_GetDataLayout(self, outmsg)
return str(outmsg) | module function_definition identifier parameters identifier block with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list keyword_argument identifier false as_pattern_target identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier return_statement call identifier argument_list identifier | This module's data layout specification, as a string. |
async def on_isupport_invex(self, value):
if not value:
value = INVITE_EXCEPT_MODE
self._channel_modes.add(value)
self._channel_modes_behaviour[rfc1459.protocol.BEHAVIOUR_LIST].add(value) | module function_definition identifier parameters identifier identifier block if_statement not_operator identifier block expression_statement assignment identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute subscript attribute identifier identifier attribute attribute identifier identifier identifier identifier argument_list identifier | Server allows invite exceptions. |
def put_coord_inside(lattice, cart_coordinate):
fc = lattice.get_fractional_coords(cart_coordinate)
return lattice.get_cartesian_coords([c - np.floor(c) for c in fc]) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement call attribute identifier identifier argument_list list_comprehension binary_operator identifier call attribute identifier identifier argument_list identifier for_in_clause identifier identifier | converts a cartesian coordinate such that it is inside the unit cell. |
def pattern_logic_srt():
if Config.options.pattern_files and Config.options.regex:
return prep_regex(prep_patterns(Config.options.pattern_files))
elif Config.options.pattern_files:
return prep_patterns(Config.options.pattern_files)
elif Config.options.regex:
return prep_regex(Config.REGEX)
else:
return Config.TERMS | module function_definition identifier parameters block if_statement boolean_operator attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier block return_statement call identifier argument_list call identifier argument_list attribute attribute identifier identifier identifier elif_clause attribute attribute identifier identifier identifier block return_statement call identifier argument_list attribute attribute identifier identifier identifier elif_clause attribute attribute identifier identifier identifier block return_statement call identifier argument_list attribute identifier identifier else_clause block return_statement attribute identifier identifier | Return patterns to be used for searching srt subtitles. |
def non_fluents(self) -> Dict[str, PVariable]:
return { str(pvar): pvar for pvar in self.pvariables if pvar.is_non_fluent() } | module function_definition identifier parameters identifier type generic_type identifier type_parameter type identifier type identifier block return_statement dictionary_comprehension pair call identifier argument_list identifier identifier for_in_clause identifier attribute identifier identifier if_clause call attribute identifier identifier argument_list | Returns non-fluent pvariables. |
def generate_filename(self, mark, **kwargs):
kwargs = kwargs.copy()
kwargs['opacity'] = int(kwargs['opacity'] * 100)
kwargs['st_mtime'] = kwargs['fstat'].st_mtime
kwargs['st_size'] = kwargs['fstat'].st_size
params = [
'%(original_basename)s',
'wm',
'w%(watermark)i',
'o%(opacity)i',
'gs%(greyscale)i',
'r%(rotation)i',
'fm%(st_mtime)i',
'fz%(st_size)i',
'p%(position)s',
]
scale = kwargs.get('scale', None)
if scale and scale != mark.size:
params.append('_s%i' % (float(kwargs['scale'][0]) / mark.size[0] * 100))
if kwargs.get('tile', None):
params.append('_tiled')
filename = '%s%s' % ('_'.join(params), kwargs['ext'])
return filename % kwargs | module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment subscript identifier string string_start string_content string_end call identifier argument_list binary_operator subscript identifier string string_start string_content string_end integer expression_statement assignment subscript identifier string string_start string_content string_end attribute 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 string string_start string_content string_end identifier expression_statement assignment identifier list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end none if_statement boolean_operator identifier comparison_operator identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end parenthesized_expression binary_operator binary_operator call identifier argument_list subscript subscript identifier string string_start string_content string_end integer subscript attribute identifier identifier integer integer if_statement call attribute identifier identifier argument_list string string_start string_content string_end none block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier binary_operator string string_start string_content string_end tuple call attribute string string_start string_content string_end identifier argument_list identifier subscript identifier string string_start string_content string_end return_statement binary_operator identifier identifier | Comes up with a good filename for the watermarked image |
def repeat(obj, times=None):
if times is None:
return AsyncIterWrapper(sync_itertools.repeat(obj))
return AsyncIterWrapper(sync_itertools.repeat(obj, times)) | module function_definition identifier parameters identifier default_parameter identifier none block if_statement comparison_operator identifier none block return_statement call identifier argument_list call attribute identifier identifier argument_list identifier return_statement call identifier argument_list call attribute identifier identifier argument_list identifier identifier | Make an iterator that returns object over and over again. |
def __pull_image_info(self, title, imageinfo, normalized):
for info in imageinfo:
info.update({'title': title})
_from = None
for norm in normalized:
if title == norm['to']:
_from = norm['from']
info['metadata'] = {}
extmetadata = info.get('extmetadata')
if extmetadata:
info['metadata'].update(extmetadata)
del info['extmetadata']
self.__insert_image_info(title, _from, info) | module function_definition identifier parameters identifier identifier identifier identifier block for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list dictionary pair string string_start string_content string_end identifier expression_statement assignment identifier none for_statement identifier identifier block if_statement comparison_operator identifier subscript identifier string string_start string_content string_end block expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment subscript identifier string string_start string_content string_end dictionary expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement identifier block expression_statement call attribute subscript identifier string string_start string_content string_end identifier argument_list identifier delete_statement subscript identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier identifier identifier | Pull image INFO from API response and insert |
def srandmember(self, key, count=None, *, encoding=_NOTSET):
args = [key]
count is not None and args.append(count)
return self.execute(b'SRANDMEMBER', *args, encoding=encoding) | module function_definition identifier parameters identifier identifier default_parameter identifier none keyword_separator default_parameter identifier identifier block expression_statement assignment identifier list identifier expression_statement boolean_operator comparison_operator identifier none call attribute identifier identifier argument_list identifier return_statement call attribute identifier identifier argument_list string string_start string_content string_end list_splat identifier keyword_argument identifier identifier | Get one or multiple random members from a set. |
def add(cls, name, value):
attr = cls(value)
attr._name = name
setattr(cls, name, attr) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment attribute identifier identifier identifier expression_statement call identifier argument_list identifier identifier identifier | Add a name-value pair to the enumeration. |
def raw(config):
client = Client()
client.prepare_connection()
audit_api = API(client)
print(audit_api.raw()) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list identifier expression_statement call identifier argument_list call attribute identifier identifier argument_list | Dump the contents of LDAP to console in raw format. |
def blockshapes(self):
if self._blockshapes is None:
if self._filename:
self._populate_from_rasterio_object(read_image=False)
else:
self._blockshapes = [(self.height, self.width) for z in range(self.num_bands)]
return self._blockshapes | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list keyword_argument identifier false else_clause block expression_statement assignment attribute identifier identifier list_comprehension tuple attribute identifier identifier attribute identifier identifier for_in_clause identifier call identifier argument_list attribute identifier identifier return_statement attribute identifier identifier | Raster all bands block shape. |
def relation_for_unit(unit=None, rid=None):
unit = unit or remote_unit()
relation = relation_get(unit=unit, rid=rid)
for key in relation:
if key.endswith('-list'):
relation[key] = relation[key].split()
relation['__unit__'] = unit
return relation | module function_definition identifier parameters default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier boolean_operator identifier call identifier argument_list expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier for_statement identifier identifier block if_statement call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment subscript identifier identifier call attribute subscript identifier identifier identifier argument_list expression_statement assignment subscript identifier string string_start string_content string_end identifier return_statement identifier | Get the json represenation of a unit's relation |
def copy_with_new_str(self, new_str):
old_atts = dict((att, value) for bfs in self.chunks
for (att, value) in bfs.atts.items())
return FmtStr(Chunk(new_str, old_atts)) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier generator_expression tuple identifier identifier for_in_clause identifier attribute identifier identifier for_in_clause tuple_pattern identifier identifier call attribute attribute identifier identifier identifier argument_list return_statement call identifier argument_list call identifier argument_list identifier identifier | Copies the current FmtStr's attributes while changing its string. |
def _get_build_env(env):
env_override = ''
if env is None:
return env_override
if not isinstance(env, dict):
raise SaltInvocationError(
'\'env\' must be a Python dictionary'
)
for key, value in env.items():
env_override += '{0}={1}\n'.format(key, value)
env_override += 'export {0}\n'.format(key)
return env_override | module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_end if_statement comparison_operator identifier none block return_statement identifier if_statement not_operator call identifier argument_list identifier identifier block raise_statement call identifier argument_list string string_start string_content escape_sequence escape_sequence string_end for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block expression_statement augmented_assignment identifier call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier identifier expression_statement augmented_assignment identifier call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier return_statement identifier | Get build environment overrides dictionary to use in build process |
def check_images(data):
if isinstance(data, ndarray):
data = fromarray(data)
if not isinstance(data, Images):
data = fromarray(asarray(data))
if len(data.shape) not in set([3, 4]):
raise Exception('Number of image dimensions %s must be 2 or 3' % (len(data.shape)))
return data | module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement not_operator call identifier argument_list identifier identifier block expression_statement assignment identifier call identifier argument_list call identifier argument_list identifier if_statement comparison_operator call identifier argument_list attribute identifier identifier call identifier argument_list list integer integer block raise_statement call identifier argument_list binary_operator string string_start string_content string_end parenthesized_expression call identifier argument_list attribute identifier identifier return_statement identifier | Check and reformat input images if needed |
def from_jd(jd):
d = jd - EPOCH
baktun = trunc(d / 144000)
d = (d % 144000)
katun = trunc(d / 7200)
d = (d % 7200)
tun = trunc(d / 360)
d = (d % 360)
uinal = trunc(d / 20)
kin = int((d % 20))
return (baktun, katun, tun, uinal, kin) | module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator identifier identifier expression_statement assignment identifier call identifier argument_list binary_operator identifier integer expression_statement assignment identifier parenthesized_expression binary_operator identifier integer expression_statement assignment identifier call identifier argument_list binary_operator identifier integer expression_statement assignment identifier parenthesized_expression binary_operator identifier integer expression_statement assignment identifier call identifier argument_list binary_operator identifier integer expression_statement assignment identifier parenthesized_expression binary_operator identifier integer expression_statement assignment identifier call identifier argument_list binary_operator identifier integer expression_statement assignment identifier call identifier argument_list parenthesized_expression binary_operator identifier integer return_statement tuple identifier identifier identifier identifier identifier | Calculate Mayan long count from Julian day |
def readinto(self, buf):
got = 0
vbuf = memoryview(buf)
while got < len(buf):
if self._cur_avail == 0:
if not self._open_next():
break
cnt = len(buf) - got
if cnt > self._cur_avail:
cnt = self._cur_avail
res = self._fd.readinto(vbuf[got : got + cnt])
if not res:
break
self._md_context.update(vbuf[got : got + res])
self._cur_avail -= res
self._remain -= res
got += res
return got | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier integer expression_statement assignment identifier call identifier argument_list identifier while_statement comparison_operator identifier call identifier argument_list identifier block if_statement comparison_operator attribute identifier identifier integer block if_statement not_operator call attribute identifier identifier argument_list block break_statement expression_statement assignment identifier binary_operator call identifier argument_list identifier identifier if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list subscript identifier slice identifier binary_operator identifier identifier if_statement not_operator identifier block break_statement expression_statement call attribute attribute identifier identifier identifier argument_list subscript identifier slice identifier binary_operator identifier identifier expression_statement augmented_assignment attribute identifier identifier identifier expression_statement augmented_assignment attribute identifier identifier identifier expression_statement augmented_assignment identifier identifier return_statement identifier | Zero-copy read directly into buffer. |
def PrintAllTables(self):
goodlogging.Log.Info("DB", "Database contents:\n")
for table in self._tableDict.keys():
self._PrintDatabaseTable(table) | module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_content escape_sequence string_end for_statement identifier call attribute attribute identifier identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list identifier | Prints contents of every table. |
def delete_role(self, name):
client = self._client('iam')
inline_policies = client.list_role_policies(
RoleName=name
)['PolicyNames']
for policy_name in inline_policies:
self.delete_role_policy(name, policy_name)
client.delete_role(RoleName=name) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier subscript call attribute identifier identifier argument_list keyword_argument identifier identifier string string_start string_content string_end for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier | Delete a role by first deleting all inline policies. |
def mail_admins(subject, message, fail_silently=False, connection=None,
html_message=None):
if not settings.ADMINS:
return
mail = EmailMultiAlternatives('%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject),
message, settings.SERVER_EMAIL, [a[1] for a in settings.ADMINS],
connection=connection)
if html_message:
mail.attach_alternative(html_message, 'text/html')
mail.send(fail_silently=fail_silently) | module function_definition identifier parameters identifier identifier default_parameter identifier false default_parameter identifier none default_parameter identifier none block if_statement not_operator attribute identifier identifier block return_statement expression_statement assignment identifier call identifier argument_list binary_operator string string_start string_content string_end tuple attribute identifier identifier identifier identifier attribute identifier identifier list_comprehension subscript identifier integer for_in_clause identifier attribute identifier identifier keyword_argument identifier identifier if_statement identifier block expression_statement call attribute identifier identifier argument_list identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier | Sends a message to the admins, as defined by the DBBACKUP_ADMINS setting. |
async def on_raw_375(self, message):
await self._registration_completed(message)
self.motd = message.params[1] + '\n' | module function_definition identifier parameters identifier identifier block expression_statement await call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier binary_operator subscript attribute identifier identifier integer string string_start string_content escape_sequence string_end | Start message of the day. |
def redirect_uris(self, value):
if isinstance(value, six.text_type):
value = value.split("\n")
value = [v.strip() for v in value]
for v in value:
validate_redirect_uri(v)
self._redirect_uris = "\n".join(value) or "" | module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end expression_statement assignment identifier list_comprehension call attribute identifier identifier argument_list for_in_clause identifier identifier for_statement identifier identifier block expression_statement call identifier argument_list identifier expression_statement assignment attribute identifier identifier boolean_operator call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier string string_start string_end | Validate and store redirect URIs for client. |
def runstring(self):
cfile = self.template % self.last
self.last += 1
return cfile | module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator attribute identifier identifier attribute identifier identifier expression_statement augmented_assignment attribute identifier identifier integer return_statement identifier | Return the run number and the file name. |
def ship_move(ship, x, y, speed):
click.echo('Moving ship %s to %s,%s with speed %s' % (ship, x, y, speed)) | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier identifier identifier | Moves SHIP to the new location X,Y. |
def GetDictToFormat(self):
d = {}
for k, v in self.__dict__.items():
d[k] = util.EncodeUnicode(v)
return d | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary for_statement pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list block expression_statement assignment subscript identifier identifier call attribute identifier identifier argument_list identifier return_statement identifier | Return a copy of self as a dict, suitable for passing to FormatProblem |
def id_to_did(did_id, method='op'):
if isinstance(did_id, bytes):
did_id = Web3.toHex(did_id)
if isinstance(did_id, str):
did_id = remove_0x_prefix(did_id)
else:
raise TypeError("did id must be a hex string or bytes")
if Web3.toBytes(hexstr=did_id) == b'':
did_id = '0'
return f'did:{method}:{did_id}' | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call identifier argument_list identifier else_clause block raise_statement call identifier argument_list string string_start string_content string_end if_statement comparison_operator call attribute identifier identifier argument_list keyword_argument identifier identifier string string_start string_end block expression_statement assignment identifier string string_start string_content string_end return_statement string string_start string_content interpolation identifier string_content interpolation identifier string_end | Return an Ocean DID from given a hex id. |
def _flush(self):
if not self.enabled:
return
try:
try:
self.lock.acquire()
self.flush()
except Exception:
self.log.error(traceback.format_exc())
finally:
if self.lock.locked():
self.lock.release() | module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block return_statement try_statement block try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list except_clause identifier block expression_statement call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list finally_clause block if_statement call attribute attribute identifier identifier identifier argument_list block expression_statement call attribute attribute identifier identifier identifier argument_list | Decorator for flushing handlers with an lock, catching exceptions |
def find_shape(self, canvas_x, canvas_y):
shape_x, shape_y, w = self.canvas_to_shapes_transform.dot([canvas_x,
canvas_y,
1])
if hasattr(self.space, 'point_query_first'):
shape = self.space.point_query_first((shape_x, shape_y))
else:
info = self.space.point_query_nearest((shape_x, shape_y), 0,
[pymunk.ShapeFilter
.ALL_CATEGORIES])
shape = info.shape if info else None
if shape:
return self.bodies[shape.body]
return None | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment pattern_list identifier identifier identifier call attribute attribute identifier identifier identifier argument_list list identifier identifier integer if_statement call identifier argument_list attribute identifier identifier string string_start string_content string_end block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list tuple identifier identifier else_clause block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list tuple identifier identifier integer list attribute attribute identifier identifier identifier expression_statement assignment identifier conditional_expression attribute identifier identifier identifier none if_statement identifier block return_statement subscript attribute identifier identifier attribute identifier identifier return_statement none | Look up shape based on canvas coordinates. |
def on_message(self, message_id_service, contact_id_service, content):
try:
live_chat = Chat.live.get(
Q(agent__id_service=contact_id_service) | Q(asker__id_service=contact_id_service))
except ObjectDoesNotExist:
self._new_chat_processing(message_id_service, contact_id_service, content)
else:
live_chat.handle_message(message_id_service, contact_id_service, content, self) | module function_definition identifier parameters identifier identifier identifier identifier block try_statement block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list binary_operator call identifier argument_list keyword_argument identifier identifier call identifier argument_list keyword_argument identifier identifier except_clause identifier block expression_statement call attribute identifier identifier argument_list identifier identifier identifier else_clause block expression_statement call attribute identifier identifier argument_list identifier identifier identifier identifier | To use as callback in message service backend |
def no_duplicates_sections2d(sections2d, prt=None):
no_dups = True
ctr = cx.Counter()
for _, hdrgos in sections2d:
for goid in hdrgos:
ctr[goid] += 1
for goid, cnt in ctr.most_common():
if cnt == 1:
break
no_dups = False
if prt is not None:
prt.write("**SECTIONS WARNING FOUND: {N:3} {GO}\n".format(N=cnt, GO=goid))
return no_dups | module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier true expression_statement assignment identifier call attribute identifier identifier argument_list for_statement pattern_list identifier identifier identifier block for_statement identifier identifier block expression_statement augmented_assignment subscript identifier identifier integer for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block if_statement comparison_operator identifier integer block break_statement expression_statement assignment identifier false if_statement comparison_operator identifier none block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content escape_sequence string_end identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier return_statement identifier | Check for duplicate header GO IDs in the 2-D sections variable. |
def profile_delete(self):
self.validate_profile_exists()
profile_data = self.profiles.get(self.args.profile_name)
fqfn = profile_data.get('fqfn')
with open(fqfn, 'r+') as fh:
data = json.load(fh)
for profile in data:
if profile.get('profile_name') == self.args.profile_name:
data.remove(profile)
fh.seek(0)
fh.write(json.dumps(data, indent=2, sort_keys=True))
fh.truncate()
if not data:
os.remove(fqfn) | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute attribute identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end 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 assignment identifier call attribute identifier identifier argument_list identifier for_statement identifier identifier block if_statement comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end attribute attribute identifier identifier identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list integer expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier keyword_argument identifier integer keyword_argument identifier true expression_statement call attribute identifier identifier argument_list if_statement not_operator identifier block expression_statement call attribute identifier identifier argument_list identifier | Delete an existing profile. |
def update_forum_redirects_counter(sender, forum, user, request, response, **kwargs):
if forum.is_link and forum.link_redirects:
forum.link_redirects_count = F('link_redirects_count') + 1
forum.save() | module function_definition identifier parameters identifier identifier identifier identifier identifier dictionary_splat_pattern identifier block if_statement boolean_operator attribute identifier identifier attribute identifier identifier block expression_statement assignment attribute identifier identifier binary_operator call identifier argument_list string string_start string_content string_end integer expression_statement call attribute identifier identifier argument_list | Handles the update of the link redirects counter associated with link forums. |
def change_view(self, request, object_id, **kwargs):
page = get_object_or_404(Page, pk=object_id)
content_model = page.get_content_model()
kwargs.setdefault("extra_context", {})
kwargs["extra_context"].update({
"hide_delete_link": not content_model.can_delete(request),
"hide_slug_field": content_model.overridden(),
})
return super(PageAdmin, self).change_view(request, object_id, **kwargs) | module function_definition identifier parameters identifier identifier identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list string string_start string_content string_end dictionary expression_statement call attribute subscript identifier string string_start string_content string_end identifier argument_list dictionary pair string string_start string_content string_end not_operator call attribute identifier identifier argument_list identifier pair string string_start string_content string_end call attribute identifier identifier argument_list return_statement call attribute call identifier argument_list identifier identifier identifier argument_list identifier identifier dictionary_splat identifier | Enforce custom permissions for the page instance. |
def show_rich_text(self, text, collapse=False, img_path=''):
self.switch_to_plugin()
self.switch_to_rich_text()
context = generate_context(collapse=collapse, img_path=img_path,
css_path=self.css_path)
self.render_sphinx_doc(text, context) | module function_definition identifier parameters identifier identifier default_parameter identifier false default_parameter identifier string string_start string_end block expression_statement call attribute identifier identifier argument_list expression_statement 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 attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier identifier | Show text in rich mode |
def binary_size(self):
return (
1 +
1 + len(self.name.encode('utf-8')) +
2 +
1 + len(self.desc.encode('utf-8')) +
sum(p.binary_size() for p in self.params.values())) | module function_definition identifier parameters identifier block return_statement parenthesized_expression binary_operator binary_operator binary_operator binary_operator binary_operator binary_operator integer integer call identifier argument_list call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end integer integer call identifier argument_list call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end call identifier generator_expression call attribute identifier identifier argument_list for_in_clause identifier call attribute attribute identifier identifier identifier argument_list | Return the number of bytes to store this group and its parameters. |
def log_pin_request(self):
if self.pin_logging and self.pin is not None:
_log(
"info", " * To enable the debugger you need to enter the security pin:"
)
_log("info", " * Debugger pin code: %s" % self.pin)
return Response("") | module function_definition identifier parameters identifier block if_statement boolean_operator attribute identifier identifier comparison_operator attribute identifier identifier none block expression_statement call identifier argument_list 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 binary_operator string string_start string_content string_end attribute identifier identifier return_statement call identifier argument_list string string_start string_end | Log the pin if needed. |
def to_native_units(self, motor):
assert abs(self.rotations_per_minute) <= motor.max_rpm,\
"invalid rotations-per-minute: {} max RPM is {}, {} was requested".format(
motor, motor.max_rpm, self.rotations_per_minute)
return self.rotations_per_minute/motor.max_rpm * motor.max_speed | module function_definition identifier parameters identifier identifier block assert_statement comparison_operator call identifier argument_list attribute identifier identifier attribute identifier identifier call attribute string string_start string_content string_end identifier argument_list identifier attribute identifier identifier attribute identifier identifier return_statement binary_operator binary_operator attribute identifier identifier attribute identifier identifier attribute identifier identifier | Return the native speed measurement required to achieve desired rotations-per-minute |
def check_dissociated(self, cutoff=1.2):
dissociated = False
if not len(self.B) > self.nslab + 1:
return dissociated
adsatoms = [atom for atom in self.B[self.nslab:]]
ads0, ads1 = set(atom.symbol for atom in adsatoms)
bond_dist = get_ads_dist(self.B, ads0, ads1)
Cradii = [cradii[atom.number]
for atom in [ase.Atom(ads0), ase.Atom(ads1)]]
bond_dist0 = sum(Cradii)
if bond_dist > cutoff * bond_dist0:
print('DISSOCIATED: {} Ang > 1.2 * {} Ang'
.format(bond_dist, bond_dist0))
dissociated = True
return dissociated | module function_definition identifier parameters identifier default_parameter identifier float block expression_statement assignment identifier false if_statement not_operator comparison_operator call identifier argument_list attribute identifier identifier binary_operator attribute identifier identifier integer block return_statement identifier expression_statement assignment identifier list_comprehension identifier for_in_clause identifier subscript attribute identifier identifier slice attribute identifier identifier expression_statement assignment pattern_list identifier identifier call identifier generator_expression attribute identifier identifier for_in_clause identifier identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier identifier identifier expression_statement assignment identifier list_comprehension subscript identifier attribute identifier identifier for_in_clause identifier list call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator identifier binary_operator identifier identifier block expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier identifier expression_statement assignment identifier true return_statement identifier | Check if adsorbate dissociates |
def _reduction_output_shape(x, output_shape, reduced_dim):
if output_shape is None:
if reduced_dim is None:
return Shape([])
else:
if reduced_dim not in x.shape.dims:
raise ValueError(
"reduced_dim=%s not in x.shape.dims=%s" % (reduced_dim, x.shape))
return x.shape - reduced_dim
if reduced_dim is not None:
if [reduced_dim] != [d for d in x.shape.dims if d not in output_shape.dims]:
raise ValueError(
"reduced_dim contradicts output_shape:"
"x=%s output_shape=%s reduced_dim=%s" %
(x, output_shape, reduced_dim))
return output_shape | module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator identifier none block if_statement comparison_operator identifier none block return_statement call identifier argument_list list else_clause block if_statement comparison_operator identifier attribute attribute identifier identifier identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end tuple identifier attribute identifier identifier return_statement binary_operator attribute identifier identifier identifier if_statement comparison_operator identifier none block if_statement comparison_operator list identifier list_comprehension identifier for_in_clause identifier attribute attribute identifier identifier identifier if_clause comparison_operator identifier attribute identifier identifier block raise_statement call identifier argument_list binary_operator concatenated_string string string_start string_content string_end string string_start string_content string_end tuple identifier identifier identifier return_statement identifier | Helper function to reduce_sum, etc. |
def will_tag(self):
wanttags = self.retrieve_config('Tag', 'no')
if wanttags == 'yes':
if aux.staggerexists:
willtag = True
else:
willtag = False
print(("You want me to tag {0}, but you have not installed "
"the Stagger module. I cannot honour your request.").
format(self.name), file=sys.stderr, flush=True)
else:
willtag = False
return willtag | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end if_statement comparison_operator identifier string string_start string_content string_end block if_statement attribute identifier identifier block expression_statement assignment identifier true else_clause block expression_statement assignment identifier false expression_statement call identifier argument_list call attribute parenthesized_expression concatenated_string string string_start string_content string_end string string_start string_content string_end identifier argument_list attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier true else_clause block expression_statement assignment identifier false return_statement identifier | Check whether the feed should be tagged |
def side_task(pipe, *side_jobs):
assert iterable(pipe), 'side_task needs the first argument to be iterable'
for sj in side_jobs:
assert callable(sj), 'all side_jobs need to be functions, not {}'.format(sj)
side_jobs = (lambda i:i ,) + side_jobs
for i in map(pipe, *side_jobs):
yield i[0] | module function_definition identifier parameters identifier list_splat_pattern identifier block assert_statement call identifier argument_list identifier string string_start string_content string_end for_statement identifier identifier block assert_statement call identifier argument_list identifier call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier binary_operator tuple lambda lambda_parameters identifier identifier identifier for_statement identifier call identifier argument_list identifier list_splat identifier block expression_statement yield subscript identifier integer | allows you to run a function in a pipeline without affecting the data |
def _calculate_session_expiry(self, request, user_info):
access_token_expiry_timestamp = self._get_access_token_expiry(request)
id_token_expiry_timestamp = self._get_id_token_expiry(user_info)
now_in_seconds = int(time.time())
earliest_expiration_timestamp = min(access_token_expiry_timestamp, id_token_expiry_timestamp)
seconds_until_expiry = earliest_expiration_timestamp - now_in_seconds
if seconds_until_expiry <= 0:
raise AuthError('Session expiry time has already passed!')
return seconds_until_expiry | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment identifier binary_operator identifier identifier if_statement comparison_operator identifier integer block raise_statement call identifier argument_list string string_start string_content string_end return_statement identifier | Returns the number of seconds after which the Django session should expire. |
def _extract_mask_distance(image, mask = slice(None), voxelspacing = None):
if isinstance(mask, slice):
mask = numpy.ones(image.shape, numpy.bool)
distance_map = distance_transform_edt(mask, sampling=voxelspacing)
return _extract_intensities(distance_map, mask) | module function_definition identifier parameters identifier default_parameter identifier call identifier argument_list none default_parameter identifier none block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier identifier return_statement call identifier argument_list identifier identifier | Internal, single-image version of `mask_distance`. |
def check_vip_ip(self, ip, environment_vip):
uri = 'api/ipv4/ip/%s/environment-vip/%s/' % (ip, environment_vip)
return super(ApiNetworkIPv4, self).get(uri) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end tuple identifier identifier return_statement call attribute call identifier argument_list identifier identifier identifier argument_list identifier | Check available ip in environment vip |
def refresh(self):
table = self.tableType()
if table:
table.markTableCacheExpired()
self.uiRecordTREE.searchRecords(self.uiSearchTXT.text()) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement identifier block expression_statement call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list | Commits changes stored in the interface to the database. |
def tags(self, extra_params=None):
return self.api._get_json(
Tag,
space=self,
rel_path=self._build_rel_path('tags'),
extra_params=extra_params,
) | module function_definition identifier parameters identifier default_parameter identifier none block return_statement call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier | All Tags in this Space |
def log_output(f):
@wraps(f)
def wrapper_fn(*args, **kwargs):
res = f(*args, **kwargs)
logging.debug("Logging result %s.", res)
return res
return wrapper_fn | module function_definition identifier parameters identifier block decorated_definition decorator call identifier argument_list identifier function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list list_splat identifier dictionary_splat identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier return_statement identifier return_statement identifier | Logs the output value. |
def _notify_single_item(self, item):
triggered_channels = set()
for key_set in self.watch_keys:
plucked = {
key_name: item[key_name]
for key_name in key_set if key_name in item
}
route_keys = expand_dict_as_keys(plucked)
for route in route_keys:
channels = self.get_route_items(route) or {}
LOG.debug('route table match: %s -> %s', route, channels)
if not channels:
LOG.debug(
'no subscribers for message.\nkey %s\nroutes: %s',
route,
self._routes
)
for channel in channels:
if channel in triggered_channels:
LOG.debug('skipping dispatch to %s', channel)
continue
LOG.debug('routing dispatch to %s: %s', channel, item)
try:
channel.notify(item) and triggered_channels.add(channel)
except Exception:
LOG.exception('Channel notification failed')
return triggered_channels | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list for_statement identifier attribute identifier identifier block expression_statement assignment identifier dictionary_comprehension pair identifier subscript identifier identifier for_in_clause identifier identifier if_clause comparison_operator identifier identifier expression_statement assignment identifier call identifier argument_list identifier for_statement identifier identifier block expression_statement assignment identifier boolean_operator call attribute identifier identifier argument_list identifier dictionary expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier if_statement not_operator identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content escape_sequence escape_sequence string_end identifier attribute identifier identifier for_statement identifier identifier block if_statement comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier continue_statement expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier try_statement block expression_statement boolean_operator call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list identifier except_clause identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement identifier | Route inbound items to individual channels |
def _handle_files(self, data):
initial = data.get("set", False)
files = data["files"]
for f in files:
try:
fobj = File(
self.room,
self.conn,
f[0],
f[1],
type=f[2],
size=f[3],
expire_time=int(f[4]) / 1000,
uploader=f[6].get("nick") or f[6].get("user"),
)
self.room.filedict = fobj.fid, fobj
if not initial:
self.conn.enqueue_data("file", fobj)
except Exception:
import pprint
LOGGER.exception("bad file")
pprint.pprint(f)
if initial:
self.conn.enqueue_data("initial_files", self.room.files) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end false expression_statement assignment identifier subscript identifier string string_start string_content string_end for_statement identifier identifier block try_statement block expression_statement assignment identifier call identifier argument_list attribute identifier identifier attribute identifier identifier subscript identifier integer subscript identifier integer keyword_argument identifier subscript identifier integer keyword_argument identifier subscript identifier integer keyword_argument identifier binary_operator call identifier argument_list subscript identifier integer integer keyword_argument identifier boolean_operator 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 expression_statement assignment attribute attribute identifier identifier identifier expression_list attribute identifier identifier identifier if_statement not_operator identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier except_clause identifier block import_statement dotted_name identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier if_statement identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end attribute attribute identifier identifier identifier | Handle new files being uploaded |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.