code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def log_if(level, msg, condition, *args):
if condition:
log(level, msg, *args) | module function_definition identifier parameters identifier identifier identifier list_splat_pattern identifier block if_statement identifier block expression_statement call identifier argument_list identifier identifier list_splat identifier | Logs 'msg % args' at level 'level' only if condition is fulfilled. |
def fixtags(self, text):
text = _guillemetLeftPat.sub(ur'\1 \2', text)
text = _guillemetRightPat.sub(ur'\1 ', text)
return text | 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 identifier expression_statement assignment identifier call attribute identifier identifier argument_lis... | Clean up special characters, only run once, next-to-last before doBlockLevels |
def render_thread(self):
obs = True
while obs:
obs = self._obs_queue.get()
if obs:
for alert in obs.observation.alerts:
self._alerts[sc_pb.Alert.Name(alert)] = time.time()
for err in obs.action_errors:
if err.result != sc_err.Success:
self._alerts[sc_e... | module function_definition identifier parameters identifier block expression_statement assignment identifier true while_statement identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list if_statement identifier block for_statement identifier att... | A render loop that pulls observations off the queue to render. |
def inh(table):
t = []
for i in table:
t.append(np.ndarray.tolist(np.arcsinh(i)))
return t | module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list call attribute ident... | inverse hyperbolic sine transformation |
def parse_datetime(s: str) -> datetime.date:
for fmt in (CREATION_DATE_FMT, PUBLISHED_DATE_FMT, PUBLISHED_DATE_FMT_2):
try:
dt = datetime.strptime(s, fmt)
except ValueError:
pass
else:
return dt
raise ValueError('Incorrect datetime format for {}'.forma... | module function_definition identifier parameters typed_parameter identifier type identifier type attribute identifier identifier block for_statement identifier tuple identifier identifier identifier block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list i... | Try to parse a datetime object from a standard datetime format or date format. |
def _hash(number, alphabet):
hashed = ''
len_alphabet = len(alphabet)
while True:
hashed = alphabet[number % len_alphabet] + hashed
number //= len_alphabet
if not number:
return hashed | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier string string_start string_end expression_statement assignment identifier call identifier argument_list identifier while_statement true block expression_statement assignment identifier binary_operator... | Hashes `number` using the given `alphabet` sequence. |
def kube_cronjob_next_schedule_time(self, metric, scraper_config):
check_basename = scraper_config['namespace'] + '.cronjob.on_schedule_check'
curr_time = int(time.time())
for sample in metric.samples:
on_schedule = int(sample[self.SAMPLE_VALUE]) - curr_time
tags = [
... | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier binary_operator subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call identifier a... | Time until the next schedule |
def create_postgresql_pypostgresql(username, password, host, port, database, **kwargs):
return create_engine(
_create_postgresql_pypostgresql(
username, password, host, port, database),
**kwargs
) | module function_definition identifier parameters identifier identifier identifier identifier identifier dictionary_splat_pattern identifier block return_statement call identifier argument_list call identifier argument_list identifier identifier identifier identifier identifier dictionary_splat identifier | create an engine connected to a postgresql database using pypostgresql. |
def _load_manifest_from_url(manifest, url, verify_certificate=True, username=None, password=None):
try:
if username and password:
manifest_file_handler = StringIO(lib.authenticated_get(username, password, url,
verify=verify_certi... | module function_definition identifier parameters identifier identifier default_parameter identifier true default_parameter identifier none default_parameter identifier none block try_statement block if_statement boolean_operator identifier identifier block expression_statement assignment identifier call identifier argu... | load a url body into a manifest |
def object_ns(self):
return Namespace(
subject=self.object_,
object_=None,
prefix=self.prefix,
qualifier=self.qualifier,
version=self.version,
) | module function_definition identifier parameters identifier block return_statement call identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier none keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier ident... | Create a new namespace for the current namespace's object value. |
def use_comparative_asseessment_part_item_view(self):
self._object_views['asseessment_part_item'] = COMPARATIVE
for session in self._get_provider_sessions():
try:
session.use_comparative_asseessment_part_item_view()
except AttributeError:
pass | module function_definition identifier parameters identifier block expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end identifier for_statement identifier call attribute identifier identifier argument_list block try_statement block expression_statement ... | Pass through to provider AssessmentPartItemSession.use_comparative_asseessment_part_item_view |
def _all_dims(x, default_dims=None):
if x.get_shape().ndims is not None:
return list(xrange(x.get_shape().ndims))
else:
return default_dims | module function_definition identifier parameters identifier default_parameter identifier none block if_statement comparison_operator attribute call attribute identifier identifier argument_list identifier none block return_statement call identifier argument_list call identifier argument_list attribute call attribute id... | Returns a list of dims in x or default_dims if the rank is unknown. |
def slicesum(self, start, stop=None, axis=0):
return self.slice(start, stop, axis).sum(axis) | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier integer block return_statement call attribute call attribute identifier identifier argument_list identifier identifier identifier identifier argument_list identifier | Slices the histogram along axis, then sums over that slice, returning a d-1 dimensional histogram |
def entropy(self, base = 2):
entropy = 0
if not base and self.base: base = self.base
for type in self._dist:
if not base:
entropy += self._dist[type] * -math.log(self._dist[type])
else:
entropy += self._dist[type] * -math.log(self._dist[typ... | module function_definition identifier parameters identifier default_parameter identifier integer block expression_statement assignment identifier integer if_statement boolean_operator not_operator identifier attribute identifier identifier block expression_statement assignment identifier attribute identifier identifier... | Compute the entropy of the distribution |
def _class_tags(cls):
class_tags = set()
for base in cls.mro()[1:]:
class_tags.update(getattr(base, '_class_tags', set()))
return class_tags | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list for_statement identifier subscript call attribute identifier identifier argument_list slice integer block expression_statement call attribute identifier identifier argument_list cal... | Collect the tags from all base classes. |
def _calc_mask(self):
mask = []
for row in self._constraints:
mask.append(tuple(x is None for x in row))
return tuple(mask) | module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list call identifier generator_expression comparison_operator identifier non... | Computes a boolean mask from the user defined constraints. |
def _selectTree( self ):
self.uiGanttTREE.blockSignals(True)
self.uiGanttTREE.clearSelection()
for item in self.uiGanttVIEW.scene().selectedItems():
item.treeItem().setSelected(True)
self.uiGanttTREE.blockSignals(False) | module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list true expression_statement call attribute attribute identifier identifier identifier argument_list for_statement identifier call attribute call attribute attribut... | Matches the tree selection to the views selection. |
def open_json(file_name):
with open(file_name, "r") as json_data:
data = json.load(json_data)
return data | module function_definition identifier parameters identifier block 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 argu... | returns json contents as string |
def abbreviate(labels, rfill=' '):
max_len = max(len(l) for l in labels)
for i in range(1, max_len):
abbrev = [l[:i].ljust(i, rfill) for l in labels]
if len(abbrev) == len(set(abbrev)):
break
return abbrev | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier call identifier generator_expression call identifier argument_list identifier for_in_clause identifier identifier for_statement identifi... | Abbreviate labels without introducing ambiguities. |
def find_source_lines(self):
strs = trace.find_strings(self.filename)
lines = trace.find_lines_from_code(self.fn.__code__, strs)
self.firstcodelineno = sys.maxint
for lineno in lines:
self.firstcodelineno = min(self.firstcodelineno, lineno)
self.sourcelines.setdef... | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute attribute identifier ide... | Mark all executable source lines in fn as executed 0 times. |
def dataset(self):
data = tablib.Dataset()
if len(list(self)) == 0:
return data
first = self[0]
data.headers = first.keys()
for row in self.all():
row = _reduce_datetimes(row.values())
data.append(row)
return data | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator call identifier argument_list call identifier argument_list identifier integer block return_statement identifier expression_sta... | A Tablib Dataset representation of the RecordCollection. |
def twirl_url(self):
return construct_api_url(self.input, 'twirl', self.resolvers, False, self.get3d, False, **self.kwargs) | module function_definition identifier parameters identifier block return_statement call identifier argument_list attribute identifier identifier string string_start string_content string_end attribute identifier identifier false attribute identifier identifier false dictionary_splat attribute identifier identifier | Url of a TwirlyMol 3D viewer. |
def prettylist(list_):
if not list_:
return ''
values = set()
uniqueList = []
for entry in list_:
if not entry in values:
values.add(entry)
uniqueList.append(entry)
return uniqueList[0] if len(uniqueList) == 1 \
else '[' + '; '.join(uniqueList) + ']' | module function_definition identifier parameters identifier block if_statement not_operator identifier block return_statement string string_start string_end expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier list for_statement identifier identifier block ... | Filter out duplicate values while keeping order. |
def omit(self):
self._omit = self.lib.iperf_get_test_omit(self._test)
return self._omit | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier return_statement attribute identifier identifier | The test startup duration to omit in seconds. |
def stringify(data):
if isinstance(data, dict):
for key, value in data.items():
data[key] = stringify(value)
elif isinstance(data, list):
return [stringify(item) for item in data]
else:
return smart_text(data)
return data | module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier identifier block for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block expression_statement assignment subscript identifier identifier call identifi... | Turns all dictionary values into strings |
def inject_into_urllib3():
util.ssl_.SSLContext = SecureTransportContext
util.HAS_SNI = HAS_SNI
util.ssl_.HAS_SNI = HAS_SNI
util.IS_SECURETRANSPORT = True
util.ssl_.IS_SECURETRANSPORT = True | module function_definition identifier parameters block expression_statement assignment attribute attribute identifier identifier identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute attribute identifier identifier identifier identifie... | Monkey-patch urllib3 with SecureTransport-backed SSL-support. |
def run(addr, *commands, **kwargs):
results = []
handler = VarnishHandler(addr, **kwargs)
for cmd in commands:
if isinstance(cmd, tuple) and len(cmd)>1:
results.extend([getattr(handler, c[0].replace('.','_'))(*c[1:]) for c in cmd])
else:
results.append(getattr(handler... | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier list expression_statement assignment identifier call identifier argument_list identifier dictionary_splat identifier for_statement identifier ide... | Non-threaded batch command runner returning output results |
def _makepass(password, hasher='sha256'):
if hasher == 'sha256':
h = hashlib.sha256(password)
elif hasher == 'md5':
h = hashlib.md5(password)
else:
return NotImplemented
c = "abcdefghijklmnopqrstuvwxyz" \
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" \
"0123456789!?.,:;/*-+_()"
... | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end block if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier arg... | Create a znc compatible hashed password |
def apply_trans_rot(ampal, translation, angle, axis, point, radians=False):
if not numpy.isclose(angle, 0.0):
ampal.rotate(angle=angle, axis=axis, point=point, radians=radians)
ampal.translate(vector=translation)
return | module function_definition identifier parameters identifier identifier identifier identifier identifier default_parameter identifier false block if_statement not_operator call attribute identifier identifier argument_list identifier float block expression_statement call attribute identifier identifier argument_list key... | Applies a translation and rotation to an AMPAL object. |
def add_resources_to_registry():
from deform.widget import default_resource_registry
default_resource_registry.set_js_resources("jqueryui", None, None)
default_resource_registry.set_js_resources("datetimepicker", None, None)
default_resource_registry.set_js_resources("custom_dates", None, None)
defa... | module function_definition identifier parameters block import_from_statement dotted_name identifier identifier dotted_name identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end none none expression_statement call attribute identifier identifier ... | Add resources to the deform registry |
def register(name=''):
"For backwards compatibility, we support @register(name) syntax."
def reg(widget):
w = widget.class_traits()
Widget.widget_types.register(w['_model_module'].default_value,
w['_model_module_version'].default_value,
... | module function_definition identifier parameters default_parameter identifier string string_start string_end block expression_statement string string_start string_content string_end function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier... | For backwards compatibility, we support @register(name) syntax. |
def log_vacation_days():
days_off = get_days_off(rc.read())
pretty_days = map(lambda day: day.strftime('%a %b %d %Y'), days_off)
for day in pretty_days:
print(day) | module function_definition identifier parameters block expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list lambda lambda_parameters identifier call attribute identifier identi... | Sum and report taken days off. |
def global_custom_theme(request):
today = datetime.datetime.now().date()
theme = {}
if today.month == 3 and (14 <= today.day <= 16):
theme = {"css": "themes/piday/piday.css"}
return {"theme": theme} | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute call attribute attribute identifier identifier identifier argument_list identifier argument_list expression_statement assignment identifier dictionary if_statement boolean_operator comparison_oper... | Add custom theme javascript and css. |
def update_visited(self):
assert isinstance(self.player.cshape.center, eu.Vector2)
pos = self.player.cshape.center
def set_visited(layer, cell):
if cell and not cell.properties.get('visited') and cell.tile and cell.tile.id > 0:
cell.properties['visited'] = True
... | module function_definition identifier parameters identifier block assert_statement call identifier argument_list attribute attribute attribute identifier identifier identifier identifier attribute identifier identifier expression_statement assignment identifier attribute attribute attribute identifier identifier identi... | Updates exploration map visited status |
def _get_atomsection(mol2_lst):
started = False
for idx, s in enumerate(mol2_lst):
if s.startswith('@<TRIPOS>ATOM'):
first_idx = idx + 1
started = True
elif started and s.startswith('@<TRIPOS>'):
last_idx_plus1 = idx
... | module function_definition identifier parameters identifier block expression_statement assignment identifier false for_statement pattern_list identifier identifier call identifier argument_list identifier block if_statement call attribute identifier identifier argument_list string string_start string_content string_end... | Returns atom section from mol2 provided as list of strings |
def _raiseValidationException(standardExcMsg, customExcMsg=None):
if customExcMsg is None:
raise ValidationException(str(standardExcMsg))
else:
raise ValidationException(str(customExcMsg)) | module function_definition identifier parameters identifier default_parameter identifier none block if_statement comparison_operator identifier none block raise_statement call identifier argument_list call identifier argument_list identifier else_clause block raise_statement call identifier argument_list call identifie... | Raise ValidationException with standardExcMsg, unless customExcMsg is specified. |
def undo_action_name(self):
if self._open:
return self._open[-1].name
elif self._undo:
return self._undo[-1].name
return "" | module function_definition identifier parameters identifier block if_statement attribute identifier identifier block return_statement attribute subscript attribute identifier identifier unary_operator integer identifier elif_clause attribute identifier identifier block return_statement attribute subscript attribute ide... | The name of the top group on the undo stack, or an empty string. |
def find_by_name(self, item_name, items_list, name_list=None):
if not name_list:
names = [item.name for item in items_list if item]
else:
names = name_list
if item_name in names:
ind = names.index(item_name)
return items_list[ind]
return Fa... | module function_definition identifier parameters identifier identifier identifier default_parameter identifier none block if_statement not_operator identifier block expression_statement assignment identifier list_comprehension attribute identifier identifier for_in_clause identifier identifier if_clause identifier else... | Return item from items_list with name item_name. |
def PrintStorageInformation(self):
storage_reader = storage_factory.StorageFactory.CreateStorageReaderForFile(
self._storage_file_path)
if not storage_reader:
logger.error(
'Format of storage file: {0:s} not supported'.format(
self._storage_file_path))
return
try:... | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier if_statement not_operator identifier block expression_statement call attribute identifier identifier argume... | Prints the storage information. |
def _project_on_ellipsoid(c, r, locations):
p0 = locations - c
l2 = 1 / np.sum(p0**2 / r**2, axis=1, keepdims=True)
p = p0 * np.sqrt(l2)
fun = lambda x: np.sum((x.reshape(p0.shape) - p0)**2)
con = lambda x: np.sum(x.reshape(p0.shape)**2 / r**2, axis=1) - 1
res = sp.optimize.minimize(fun, p, cons... | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier binary_operator identifier identifier expression_statement assignment identifier binary_operator integer call attribute identifier identifier argument_list binary_operator binary_operator i... | displace locations to the nearest point on ellipsoid surface |
def drawHUD(self):
self.win.move(self.height - 2, self.x_pad)
self.win.clrtoeol()
self.win.box()
self.addstr(2, self.x_pad + 1, "Population: %i" % len(self.grid))
self.addstr(3, self.x_pad + 1, "Generation: %s" % self.current_gen)
self.addstr(3, self.x_grid - 21, "s: star... | module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator attribute identifier identifier integer attribute identifier identifier expression_statement call attribute attribute identifier identifier ident... | Draw information on population size and current generation |
def enumerate(context, data):
items = ensure_list(context.params.get('items'))
for item in items:
data['item'] = item
context.emit(data=data) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end for_statement identifier identifier block expression... | Iterate through a set of items and emit each one of them. |
def make_header(self, locale, catalog):
return {
"po-revision-date": self.get_catalogue_header_value(catalog, 'PO-Revision-Date'),
"mime-version": self.get_catalogue_header_value(catalog, 'MIME-Version'),
"last-translator": 'Automatic <hi@thorgate.eu>',
"x-generat... | module function_definition identifier parameters identifier identifier identifier block return_statement dictionary pair string string_start string_content string_end call attribute identifier identifier argument_list identifier string string_start string_content string_end pair string string_start string_content strin... | Populate header with correct data from top-most locale file. |
def register_hid_device(screen_width, screen_height,
absolute=False, integrated_display=False):
message = create(protobuf.REGISTER_HID_DEVICE_MESSAGE)
descriptor = message.inner().deviceDescriptor
descriptor.absolute = 1 if absolute else 0
descriptor.integratedDisplay = 1 if inte... | module function_definition identifier parameters identifier identifier default_parameter identifier false default_parameter identifier false block expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement assignment identifier attribute call attribute ... | Create a new REGISTER_HID_DEVICE_MESSAGE. |
def Docker():
docker_info = {'server': {}, 'env': '', 'type': '', 'os': ''}
try:
d_client = docker.from_env()
docker_info['server'] = d_client.version()
except Exception as e:
logger.error("Can't get docker info " + str(e))
system = System()
docker_info['os'] = system
if ... | module function_definition identifier parameters block expression_statement assignment identifier dictionary pair string string_start string_content string_end dictionary pair string string_start string_content string_end string string_start string_end pair string string_start string_content string_end string string_st... | Get Docker setup information |
def serialized(self, prepend_date=True):
name = self.serialized_name()
datetime = self.serialized_time(prepend_date)
return "%s %s" % (datetime, name) | module function_definition identifier parameters identifier default_parameter identifier true block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement bina... | Return a string fully representing the fact. |
def time(ctx, hours, minutes, seconds):
return _time(conversions.to_integer(hours, ctx), conversions.to_integer(minutes, ctx), conversions.to_integer(seconds, ctx)) | module function_definition identifier parameters identifier identifier identifier identifier block return_statement call identifier argument_list call attribute identifier identifier argument_list identifier identifier call attribute identifier identifier argument_list identifier identifier call attribute identifier id... | Defines a time value |
def add_host(self, name: str, **kwargs) -> None:
host = {
name: deserializer.inventory.InventoryElement.deserialize_host(
name=name, defaults=self.defaults, **kwargs
)
}
self.hosts.update(host) | module function_definition identifier parameters identifier typed_parameter identifier type identifier dictionary_splat_pattern identifier type none block expression_statement assignment identifier dictionary pair identifier call attribute attribute attribute identifier identifier identifier identifier argument_list ke... | Add a host to the inventory after initialization |
def _raise_error_from_response(data):
meta = data.get('meta')
if meta:
if meta.get('code') in (200, 409): return data
exc = error_types.get(meta.get('errorType'))
if exc:
raise exc(meta.get('errorDetail'))
else:
_log_and_raise_exception('Unknown error. met... | 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 identifier block if_statement comparison_operator call attribute identifier identifier argument_list ... | Processes the response data |
def AddAccuracy(model, softmax, label):
accuracy = brew.accuracy(model, [softmax, label], "accuracy")
return accuracy | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier list identifier identifier string string_start string_content string_end return_statement identifier | Adds an accuracy op to the model |
def _update_visible_blocks(self, *args):
self._visible_blocks[:] = []
block = self.firstVisibleBlock()
block_nbr = block.blockNumber()
top = int(self.blockBoundingGeometry(block).translated(
self.contentOffset()).top())
bottom = top + int(self.blockBoundingRect(block)... | module function_definition identifier parameters identifier list_splat_pattern identifier block expression_statement assignment subscript attribute identifier identifier slice list expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier ca... | Updates the list of visible blocks |
def launch_ipython(argv=None):
from .linux import launch_ipython as _launch_ipython_linux
os.environ = {str(k): str(v) for k,v in os.environ.items()}
try:
from qtconsole.qtconsoleapp import JupyterQtConsoleApp
except ImportError:
sys.exit("ERROR: IPython QtConsole not installed in this e... | module function_definition identifier parameters default_parameter identifier none block import_from_statement relative_import import_prefix dotted_name identifier aliased_import dotted_name identifier identifier expression_statement assignment attribute identifier identifier dictionary_comprehension pair call identifi... | Force usage of QtConsole under Windows |
def at_match(self, match, predicate=None, index=None):
return self.at_span(match.span, predicate, index) | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier none block return_statement call attribute identifier identifier argument_list attribute identifier identifier identifier identifier | Retrieves a list of matches from given match. |
def best_parent( self, node, tree_type=None ):
parents = self.parents(node)
selected_parent = None
if node['type'] == 'type':
module = ".".join( node['name'].split( '.' )[:-1] )
if module:
for mod in parents:
if mod['type'] == 'module' ... | module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier none if_statement comparison_operator subscript identifier st... | Choose the best parent for a given node |
def grid_2d_8graph(self, m, n):
me = nx.Graph()
node = me.node
add_node = me.add_node
add_edge = me.add_edge
for i in range(m):
for j in range(n):
add_node((i, j))
if i > 0:
add_edge((i, j), (i-1, j))
... | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier attribute identifier... | Make a 2d graph that's connected 8 ways, enabling diagonal movement |
def cancelThread(*threads, exception=EscapeException):
'Raise exception on another thread.'
for t in threads:
ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(t.ident), ctypes.py_object(exception)) | module function_definition identifier parameters list_splat_pattern identifier default_parameter identifier identifier block expression_statement string string_start string_content string_end for_statement identifier identifier block expression_statement call attribute attribute identifier identifier identifier argumen... | Raise exception on another thread. |
def result(self, res):
return self >> Parser(lambda _, index: Value.success(index, res)) | module function_definition identifier parameters identifier identifier block return_statement binary_operator identifier call identifier argument_list lambda lambda_parameters identifier identifier call attribute identifier identifier argument_list identifier identifier | Return a value according to the parameter `res` when parse successfully. |
def capture_dash_in_url_name(self, node):
for keyword in node.keywords:
if keyword.arg == 'name' and '-' in keyword.value.s:
return DJ04(
lineno=node.lineno,
col=node.col_offset,
) | module function_definition identifier parameters identifier identifier block for_statement identifier attribute identifier identifier block if_statement boolean_operator comparison_operator attribute identifier identifier string string_start string_content string_end comparison_operator string string_start string_conte... | Capture dash in URL name |
def _run_collect_allelic_counts(pos_file, pos_name, work_dir, data):
out_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), "structural", "counts"))
out_file = os.path.join(out_dir, "%s-%s-counts.tsv" % (dd.get_sample_name(data), pos_name))
if not utils.file_exists(out_file):
with file_tra... | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list iden... | Counts by alleles for a specific sample and set of positions. |
def unique(series: pd.Series) -> pd.Series:
return ~series.duplicated(keep=False) | module function_definition identifier parameters typed_parameter identifier type attribute identifier identifier type attribute identifier identifier block return_statement unary_operator call attribute identifier identifier argument_list keyword_argument identifier false | Test that the data items do not repeat. |
def unicode_name(self, name, in_group=False):
value = ord(_unicodedata.lookup(name))
if (self.is_bytes and value > 0xFF):
value = ""
if not in_group and value == "":
return '[^%s]' % ('\x00-\xff' if self.is_bytes else _uniprops.UNICODE_RANGE)
elif value == "":
... | module function_definition identifier parameters identifier identifier default_parameter identifier false block expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list identifier if_statement parenthesized_expression boolean_operator attribute identifi... | Insert Unicode value by its name. |
def begin_commit():
session_token = request.headers['session_token']
repository = request.headers['repository']
current_user = have_authenticated_user(request.environ['REMOTE_ADDR'], repository, session_token)
if current_user is False: return fail(user_auth_fail_msg)
repository_path = config['rep... | module function_definition identifier parameters block expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end exp... | Allow a client to begin a commit and acquire the write lock |
def _find_controller(self, *args):
for name in args:
obj = self._lookup_child(name)
if obj and iscontroller(obj):
return obj
return None | module function_definition identifier parameters identifier list_splat_pattern identifier block for_statement identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement boolean_operator identifier call identifier argument_list identi... | Returns the appropriate controller for routing a custom action. |
def read(fname):
path = os.path.join(SCRIPTDIR, fname)
if PY3:
f = open(path, 'r', encoding='utf8')
else:
f = open(path, 'r')
content = f.read()
f.close()
return content | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier if_statement identifier block expression_statement assignment identifier call identifier argument_list identifier str... | Return content of specified file |
def addPrefs(self, prefs=[]):
if len(prefs) == len(self.preferences) == 0:
logger.debug("no preferences")
return None
self.preferences.extend(prefs)
self.css1(path['search-btn']).click()
count = 0
for pref in self.preferences:
self.css1(path['s... | module function_definition identifier parameters identifier default_parameter identifier list block if_statement comparison_operator call identifier argument_list identifier call identifier argument_list attribute identifier identifier integer block expression_statement call attribute identifier identifier argument_lis... | add preference in self.preferences |
def move_position(self, dx, dy, speed=None):
if speed:
self._intf.write('MoveChuckPosition %1.1f %1.1f R Y %d' % (dx, dy, speed))
else:
self._intf.write('MoveChuckPosition %1.1f %1.1f R Y' % (dx, dy)) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier none block if_statement identifier block expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content string_end tuple identif... | Move chuck relative to actual position in um |
def reset_password(app, appbuilder, username, password):
_appbuilder = import_application(app, appbuilder)
user = _appbuilder.sm.find_user(username=username)
if not user:
click.echo("User {0} not found.".format(username))
else:
_appbuilder.sm.reset_password(user.id, password)
cli... | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_arg... | Resets a user's password |
def default_hass_config_dir():
data_dir = os.getenv("APPDATA") if os.name == "nt" else os.path.expanduser("~")
return os.path.join(data_dir, ".homeassistant") | module function_definition identifier parameters block expression_statement assignment identifier conditional_expression call attribute identifier identifier argument_list string string_start string_content string_end comparison_operator attribute identifier identifier string string_start string_content string_end call... | Put together the default configuration directory based on the OS. |
def add_fortran_to_env(env):
try:
FortranSuffixes = env['FORTRANFILESUFFIXES']
except KeyError:
FortranSuffixes = ['.f', '.for', '.ftn']
try:
FortranPPSuffixes = env['FORTRANPPFILESUFFIXES']
except KeyError:
FortranPPSuffixes = ['.fpp', '.FPP']
DialectAddToEnv(env, "F... | module function_definition identifier parameters identifier block try_statement block expression_statement assignment identifier subscript identifier string string_start string_content string_end except_clause identifier block expression_statement assignment identifier list string string_start string_content string_end... | Add Builders and construction variables for Fortran to an Environment. |
def signature(self):
iexec, execmod = self.context.parser.tree_find(self.context.el_name,
self.context.module, "executables")
if iexec is None:
iexec, execmod = self.context.parser.tree_find(self.context.el_name, self.context.module,
... | module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier call attribute attribute attribute identifier identifier identifier identifier argument_list attribute attribute identifier identifier identifier attribute attribute identifier identifier... | Gets completion or call signature information for the current cursor. |
def spew_length(self, length):
pos = self.pos
if not pos or length > pos:
return None
row = self.row
for char in reversed(self.string[pos - length:pos]):
pos -= 1
if char == '\n':
row -= 1
self.pos = pos
self.col = self.... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute identifier identifier if_statement boolean_operator not_operator identifier comparison_operator identifier identifier block return_statement none expression_statement assignment identifier a... | Move current position backwards by length. |
def add_atmost(self, lits, k, no_return=True):
if self.minicard:
res = pysolvers.minicard_add_am(self.minicard, lits, k)
if res == False:
self.status = False
if not no_return:
return res | module function_definition identifier parameters identifier identifier identifier default_parameter identifier true block if_statement attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier identifier identifier... | Add a new atmost constraint to solver's internal formula. |
def git_lines(*args, git=maybeloggit, **kwargs):
'Generator of stdout lines from given git command'
err = io.StringIO()
try:
for line in git('--no-pager', _err=err, *args, _decode_errors='replace', _iter=True, _bg_exc=False, **kwargs):
yield line[:-1]
except sh.ErrorReturnCode as e:
... | module function_definition identifier parameters list_splat_pattern identifier default_parameter identifier identifier dictionary_splat_pattern identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_lis... | Generator of stdout lines from given git command |
def make_automaton(self):
queue = deque()
for i in range(256):
c = chr(i)
if c in self.root.children:
node = self.root.children[c]
node.fail = self.root
queue.append(node)
else:
self.root.children[c] = self.root
while queue:
r = queue.popleft()
for node in r.children.values():
q... | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list for_statement identifier call identifier argument_list integer block expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_oper... | Converts trie to Aho-Corasick automaton. |
def error_string(mqtt_errno):
if mqtt_errno == MQTT_ERR_SUCCESS:
return "No error."
elif mqtt_errno == MQTT_ERR_NOMEM:
return "Out of memory."
elif mqtt_errno == MQTT_ERR_PROTOCOL:
return "A network protocol error occurred when communicating with the broker."
elif mqtt_errno == M... | module function_definition identifier parameters identifier block if_statement comparison_operator identifier identifier block return_statement string string_start string_content string_end elif_clause comparison_operator identifier identifier block return_statement string string_start string_content string_end elif_cl... | Return the error string associated with an mqtt error number. |
def _determine_current_dimension_size(self, dim_name, max_size):
if self.dimensions[dim_name] is not None:
return max_size
def _find_dim(h5group, dim):
if dim not in h5group:
return _find_dim(h5group.parent, dim)
return h5group[dim]
dim_variabl... | module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator subscript attribute identifier identifier identifier none block return_statement identifier function_definition identifier parameters identifier identifier block if_statement comparison_operator iden... | Helper method to determine the current size of a dimension. |
def update_pointed(self):
if not self.pointed_at_expired:
try:
conf_string, stat2 = self.zoo_client.get(self.point_path,
watch=self.watch_pointed)
except ZookeeperError:
self.old_data = ''
... | module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block try_statement block expression_statement assignment pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier... | Grabs the latest file contents based on the pointer uri |
def create_connection_model(service):
services = service._services
bases = (BaseModel,)
attributes = {model_service_name(service): fields.CharField() for service in services}
return type(BaseModel)(connection_service_name(service), bases, attributes) | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier tuple identifier expression_statement assignment identifier dictionary_comprehension pair call identifier argument_list identifier call ... | Create an SQL Alchemy table that connects the provides services |
def _await_socket(self, timeout):
with safe_open(self._ng_stdout, 'r') as ng_stdout:
start_time = time.time()
accumulated_stdout = ''
while 1:
remaining_time = time.time() - (start_time + timeout)
if remaining_time > 0:
stderr = read_file(self._ng_stderr, binary_mode=True... | module function_definition identifier parameters identifier identifier block with_statement with_clause with_item as_pattern call identifier argument_list attribute identifier identifier string string_start string_content string_end as_pattern_target identifier block expression_statement assignment identifier call attr... | Blocks for the nailgun subprocess to bind and emit a listening port in the nailgun stdout. |
def refresh_toc(self, refresh_done_callback, toc_cache):
self._useV2 = self.cf.platform.get_protocol_version() >= 4
self._toc_cache = toc_cache
self._refresh_callback = refresh_done_callback
self.toc = None
pk = CRTPPacket()
pk.set_header(CRTPPort.LOGGING, CHAN_SETTINGS)
... | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment attribute identifier identifier comparison_operator call attribute attribute attribute identifier identifier identifier identifier argument_list integer expression_statement assignment attribute ident... | Start refreshing the table of loggale variables |
def update():
repo_directory = get_config()['repo_directory']
os.chdir(repo_directory)
click.echo("Check for updates...")
local = subprocess.check_output('git rev-parse master'.split()).strip()
remote = subprocess.check_output(
'git ls-remote https://github.com/tldr-pages/tldr/ HEAD'.split()... | module function_definition identifier parameters block expression_statement assignment identifier subscript call identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identi... | Update to the latest pages. |
def apply(self, coordinates):
transform = self.get_transformation(coordinates)
result = MolecularDistortion(self.affected_atoms, transform)
result.apply(coordinates)
return result | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier identifier expression_statement c... | Generate, apply and return a random manipulation |
def copy(self):
ms = MouseState()
ms.left_pressed = self.left_pressed
ms.middle_pressed = self.middle_pressed
ms.right_pressed = self.right_pressed
ms.mouse_pos = self.mouse_pos
return ms | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier attribute identifier ... | Create a copy of this MouseState and return it. |
def ics2task():
from argparse import ArgumentParser, FileType
from sys import stdin
parser = ArgumentParser(description='Converter from iCalendar to Taskwarrior syntax.')
parser.add_argument('infile', nargs='?', type=FileType('r'), default=stdin,
help='Input iCalendar file (defau... | module function_definition identifier parameters block import_from_statement dotted_name identifier dotted_name identifier dotted_name identifier import_from_statement dotted_name identifier dotted_name identifier expression_statement assignment identifier call identifier argument_list keyword_argument identifier strin... | Command line tool to convert from iCalendar to Taskwarrior |
def _notify_remove(self, slice_):
change = RemoveChange(self, slice_)
self.notify_observers(change) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list identifier | Notify about a RemoveChange. |
def to_fp32(learn:Learner):
"Put `learn` back to FP32 precision mode."
learn.data.remove_tfm(batch_to_half)
for cb in learn.callbacks:
if isinstance(cb, MixedPrecision): learn.callbacks.remove(cb)
learn.model = learn.model.float()
return learn | module function_definition identifier parameters typed_parameter identifier type identifier block expression_statement string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list identifier for_statement identifier attribute identifier ident... | Put `learn` back to FP32 precision mode. |
def init(config_file):
schema = generate_schema_file(open(config_file, 'r').read())
sys.stdout.write(schema) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list call attribute call identifier argument_list identifier string string_start string_content string_end identifier argument_list expression_statement call attribute attribute identifi... | Initialize a confirm schema from an existing configuration file. |
def partial_row_coordinates(self, X):
utils.validation.check_is_fitted(self, 's_')
if self.check_input:
utils.check_array(X, dtype=[str, np.number])
X = self._prepare_input(X)
P = len(X) ** 0.5 * self.U_ / self.s_
coords = {}
for name, cols in sorted(self.grou... | module function_definition identifier parameters identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end if_statement attribute identifier identifier block expression_statement call attribute identi... | Returns the row coordinates for each group. |
def can_delete_post(self, post, user):
checker = self._get_checker(user)
is_author = self._is_post_author(post, user)
can_delete = (
user.is_superuser or
(is_author and checker.has_perm('can_delete_own_posts', post.topic.forum)) or
checker.has_perm('can_delete... | 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 identifier expression_... | Given a forum post, checks whether the user can delete the latter. |
def link_label(link):
if hasattr(link, 'label'):
label = link.label
else:
label = str(link.linknum+1)
return label | module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier string string_start string_content string_end block expression_statement assignment identifier attribute identifier identifier else_clause block expression_statement assignment identifier call identif... | return a link label as a string |
def level(self, lvl=None):
if not lvl:
return self._lvl
self._lvl = self._parse_level(lvl)
self.stream.setLevel(self._lvl)
logging.root.setLevel(self._lvl) | module function_definition identifier parameters identifier default_parameter identifier none block if_statement not_operator identifier block return_statement attribute identifier identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier ex... | Get or set the logging level. |
def copy_list(src_list, dst_list, lbl='Copying',
ioerr_ok=False, sherro_ok=False, oserror_ok=False):
task_iter = zip(src_list, dst_list)
def docopy(src, dst):
try:
shutil.copy2(src, dst)
except OSError:
if ioerr_ok:
return False
r... | module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_content string_end default_parameter identifier false default_parameter identifier false default_parameter identifier false block expression_statement assignment identifier call identifier argu... | Copies all data and stat info |
def find_function(self, name):
deffunction = lib.EnvFindDeffunction(self._env, name.encode())
if deffunction == ffi.NULL:
raise LookupError("Function '%s' not found" % name)
return Function(self._env, deffunction) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier call attribute identifier identifier argument_list if_statement comparison_operator identifier attribute identifier i... | Find the Function by its name. |
def coerce(value):
if isinstance(value, ListCell):
return value
elif isinstance(value, (list)):
return ListCell(value)
else:
return ListCell([value]) | module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier identifier block return_statement identifier elif_clause call identifier argument_list identifier parenthesized_expression identifier block return_statement call identifier argument_list identifier el... | Turns a value into a list |
def sysidpath(ignore_options=False):
failover = Path('/tmp/machine-id')
if not ignore_options:
options = (
Path('/etc/machine-id'),
failover,
)
for option in options:
if (option.exists() and
os.access(option, os.R_OK) and
... | module function_definition identifier parameters default_parameter identifier false block expression_statement assignment identifier call identifier argument_list string string_start string_content string_end if_statement not_operator identifier block expression_statement assignment identifier tuple call identifier arg... | get a unique identifier for the machine running this function |
def load(self,dset):
self.dset_filename = dset
self.dset = nib.load(dset)
self.data = self.dset.get_data()
self.header = self.dset.get_header() | module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier expression_statement assignment attribute ... | load a dataset from given filename into the object |
def _check_emotion_set_is_supported(self):
supported_emotion_subsets = [
set(['anger', 'fear', 'surprise', 'calm']),
set(['happiness', 'disgust', 'surprise']),
set(['anger', 'fear', 'surprise']),
set(['anger', 'fear', 'calm']),
set(['anger', 'happiness... | module function_definition identifier parameters identifier block expression_statement assignment identifier list call identifier argument_list 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_conten... | Validates set of user-supplied target emotions. |
def show_order(self, order_id):
request = self._get('transactions/orders/' + str(order_id))
return self.responder(request) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator string string_start string_content string_end call identifier argument_list identifier return_statement call attribute identifier ide... | Shows an existing order transaction. |
def accuracy_thresh(y_pred:Tensor, y_true:Tensor, thresh:float=0.5, sigmoid:bool=True)->Rank0Tensor:
"Compute accuracy when `y_pred` and `y_true` are the same size."
if sigmoid: y_pred = y_pred.sigmoid()
return ((y_pred>thresh)==y_true.byte()).float().mean() | module function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type identifier typed_default_parameter identifier type identifier float typed_default_parameter identifier type identifier true type identifier block expression_statement string string_start string_co... | Compute accuracy when `y_pred` and `y_true` are the same size. |
def _decodeTimestamp(byteIter):
dateStr = decodeSemiOctets(byteIter, 7)
timeZoneStr = dateStr[-2:]
return datetime.strptime(dateStr[:-2], '%y%m%d%H%M%S').replace(tzinfo=SmsPduTzInfo(timeZoneStr)) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier integer expression_statement assignment identifier subscript identifier slice unary_operator integer return_statement call attribute call attribute identifier identifier ... | Decodes a 7-octet timestamp |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.