code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def by_own_time_per_call(stat):
return (-stat.own_time_per_call if stat.own_hits else -stat.own_time,
by_deep_time_per_call(stat)) | module function_definition identifier parameters identifier block return_statement tuple conditional_expression unary_operator attribute identifier identifier attribute identifier identifier unary_operator attribute identifier identifier call identifier argument_list identifier | Sorting by exclusive elapsed time per call in descending order. |
def rigid_linear_interpolate_by_datetime(datetime_axis, y_axis, datetime_new_axis):
numeric_datetime_axis = [
totimestamp(a_datetime) for a_datetime in datetime_axis
]
numeric_datetime_new_axis = [
totimestamp(a_datetime) for a_datetime in datetime_new_axis
]
return rigid_linear_interpolate(
numeric_datetime_axis, y_axis, numeric_datetime_new_axis) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier list_comprehension call identifier argument_list identifier for_in_clause identifier identifier expression_statement assignment identifier list_comprehension call identifier argument_list identifier for_in_clause identifier identifier return_statement call identifier argument_list identifier identifier identifier | A datetime-version that takes datetime object list as x_axis. |
def refine (self, requirements):
assert isinstance(requirements, PropertySet)
if requirements not in self.refined_:
r = property.refine(self.all_, requirements.all_)
self.refined_[requirements] = create(r)
return self.refined_[requirements] | module function_definition identifier parameters identifier identifier block assert_statement call identifier argument_list identifier identifier if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement assignment subscript attribute identifier identifier identifier call identifier argument_list identifier return_statement subscript attribute identifier identifier identifier | Refines this set's properties using the requirements passed as an argument. |
def ipynb_to_rst(directory, filename):
print(filename)
os.chdir(directory)
subprocess.Popen(["ipython", "nbconvert", "--to", "rst",
filename],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=directory) | module function_definition identifier parameters identifier identifier block expression_statement call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier 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_content string_end identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier | Converts a given file in a directory to an rst in the same directory. |
def _repr_html_(self):
out="<table class='taqltable'>\n"
if not(self.name()[:4]=="Col_"):
out+="<tr>"
out+="<th><b>"+self.name()+"</b></th>"
out+="</tr>"
cropped=False
rowcount=0
colkeywords=self.getkeywords()
for row in self:
out +="\n<tr>"
out += "<td>" + _format_cell(row, colkeywords) + "</td>\n"
out += "</tr>\n"
rowcount+=1
out+="\n"
if rowcount>=20:
cropped=True
break
if out[-2:]=="\n\n":
out=out[:-1]
out+="</table>"
if cropped:
out+="<p style='text-align:center'>("+str(self.nrows()-20)+" more rows)</p>\n"
return out | module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_content escape_sequence string_end if_statement not_operator parenthesized_expression comparison_operator subscript call attribute identifier identifier argument_list slice integer string string_start string_content string_end block expression_statement augmented_assignment identifier string string_start string_content string_end expression_statement augmented_assignment identifier binary_operator binary_operator string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end expression_statement augmented_assignment identifier string string_start string_content string_end expression_statement assignment identifier false expression_statement assignment identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list for_statement identifier identifier block expression_statement augmented_assignment identifier string string_start string_content escape_sequence string_end expression_statement augmented_assignment identifier binary_operator binary_operator string string_start string_content string_end call identifier argument_list identifier identifier string string_start string_content escape_sequence string_end expression_statement augmented_assignment identifier string string_start string_content escape_sequence string_end expression_statement augmented_assignment identifier integer expression_statement augmented_assignment identifier string string_start string_content escape_sequence string_end if_statement comparison_operator identifier integer block expression_statement assignment identifier true break_statement if_statement comparison_operator subscript identifier slice unary_operator integer string string_start string_content escape_sequence escape_sequence string_end block expression_statement assignment identifier subscript identifier slice unary_operator integer expression_statement augmented_assignment identifier string string_start string_content string_end if_statement identifier block expression_statement augmented_assignment identifier binary_operator binary_operator string string_start string_content string_end call identifier argument_list binary_operator call attribute identifier identifier argument_list integer string string_start string_content escape_sequence string_end return_statement identifier | Give a nice representation of columns in notebooks. |
def copy(self, **kwargs):
msg = Message(self.encode(), self.gateway)
for key, val in kwargs.items():
setattr(msg, key, val)
return msg | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block expression_statement call identifier argument_list identifier identifier identifier return_statement identifier | Copy a message, optionally replace attributes with kwargs. |
def _convert_labeled_point_to_libsvm(p):
from pyspark.mllib.regression import LabeledPoint
assert isinstance(p, LabeledPoint)
items = [str(p.label)]
v = _convert_to_vector(p.features)
if isinstance(v, SparseVector):
nnz = len(v.indices)
for i in xrange(nnz):
items.append(str(v.indices[i] + 1) + ":" + str(v.values[i]))
else:
for i in xrange(len(v)):
items.append(str(i + 1) + ":" + str(v[i]))
return " ".join(items) | module function_definition identifier parameters identifier block import_from_statement dotted_name identifier identifier identifier dotted_name identifier assert_statement call identifier argument_list identifier identifier expression_statement assignment identifier list call identifier argument_list attribute identifier identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier for_statement identifier call identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list binary_operator binary_operator call identifier argument_list binary_operator subscript attribute identifier identifier identifier integer string string_start string_content string_end call identifier argument_list subscript attribute identifier identifier identifier else_clause block for_statement identifier call identifier argument_list call identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list binary_operator binary_operator call identifier argument_list binary_operator identifier integer string string_start string_content string_end call identifier argument_list subscript identifier identifier return_statement call attribute string string_start string_content string_end identifier argument_list identifier | Converts a LabeledPoint to a string in LIBSVM format. |
def to_dict(self):
return {
"state_size": self.state_size,
"chain": self.chain.to_json(),
"parsed_sentences": self.parsed_sentences if self.retain_original else None
} | module function_definition identifier parameters identifier block return_statement dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list pair string string_start string_content string_end conditional_expression attribute identifier identifier attribute identifier identifier none | Returns the underlying data as a Python dict. |
def flush(self, multithread=True, **kwargs):
if self._write_buf.tell() > 0:
data = self._write_buf.getvalue()
self._write_buf = BytesIO()
if multithread:
self._async_upload_part_request(data, index=self._cur_part, **kwargs)
else:
self.upload_part(data, self._cur_part, **kwargs)
self._cur_part += 1
if len(self._http_threadpool_futures) > 0:
dxpy.utils.wait_for_all_futures(self._http_threadpool_futures)
try:
for future in self._http_threadpool_futures:
if future.exception() != None:
raise future.exception()
finally:
self._http_threadpool_futures = set() | module function_definition identifier parameters identifier default_parameter identifier true dictionary_splat_pattern identifier block if_statement comparison_operator call attribute attribute identifier identifier identifier argument_list integer block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier call identifier argument_list if_statement identifier block expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier attribute identifier identifier dictionary_splat identifier else_clause block expression_statement call attribute identifier identifier argument_list identifier attribute identifier identifier dictionary_splat identifier expression_statement augmented_assignment attribute identifier identifier integer if_statement comparison_operator call identifier argument_list attribute identifier identifier integer block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier try_statement block for_statement identifier attribute identifier identifier block if_statement comparison_operator call attribute identifier identifier argument_list none block raise_statement call attribute identifier identifier argument_list finally_clause block expression_statement assignment attribute identifier identifier call identifier argument_list | Flushes the internal write buffer. |
def add_upsert(self, value, criteria):
value = value.strip()
v = value.lower()
self.lower_val_to_val[v] = value
criteria_array = self.upserts.get(v)
if criteria_array is None:
criteria_array = []
self.upserts_size[v] = 31 + len(value)
criteria_array.append(criteria.to_dict())
self.upserts[v] = criteria_array
self.upserts_size[v] += criteria.json_size() | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment subscript attribute identifier identifier identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier if_statement comparison_operator identifier none block expression_statement assignment identifier list expression_statement assignment subscript attribute identifier identifier identifier binary_operator integer call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list expression_statement assignment subscript attribute identifier identifier identifier identifier expression_statement augmented_assignment subscript attribute identifier identifier identifier call attribute identifier identifier argument_list | Add a tag or populator to the batch by value and criteria |
def unquote(text):
while '%' in text:
newtext = url_unquote(text)
if newtext == text:
break
text = newtext
return text | module function_definition identifier parameters identifier block while_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator identifier identifier block break_statement expression_statement assignment identifier identifier return_statement identifier | Replace all percent-encoded entities in text. |
def com_google_fonts_check_name_rfn(ttFont):
failed = False
for entry in ttFont["name"].names:
string = entry.toUnicode()
if "reserved font name" in string.lower():
yield WARN, ("Name table entry (\"{}\")"
" contains \"Reserved Font Name\"."
" This is an error except in a few specific"
" rare cases.").format(string)
failed = True
if not failed:
yield PASS, ("None of the name table strings"
" contain \"Reserved Font Name\".") | module function_definition identifier parameters identifier block expression_statement assignment identifier false for_statement identifier attribute subscript identifier string string_start string_content string_end identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator string string_start string_content string_end call attribute identifier identifier argument_list block expression_statement yield expression_list identifier call attribute parenthesized_expression concatenated_string string string_start string_content escape_sequence escape_sequence string_end string string_start string_content escape_sequence escape_sequence string_end string string_start string_content string_end string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier true if_statement not_operator identifier block expression_statement yield expression_list identifier parenthesized_expression concatenated_string string string_start string_content string_end string string_start string_content escape_sequence escape_sequence string_end | Name table strings must not contain the string 'Reserved Font Name'. |
async def on_isupport_targmax(self, value):
if not value:
return
for entry in value.split(','):
command, limit = entry.split(':', 1)
if not limit:
continue
self._target_limits[command] = int(limit) | module function_definition identifier parameters identifier identifier block if_statement not_operator identifier block return_statement for_statement identifier call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end integer if_statement not_operator identifier block continue_statement expression_statement assignment subscript attribute identifier identifier identifier call identifier argument_list identifier | The maximum number of targets certain types of commands can affect. |
def _download_images(data, img_cols):
images = collections.defaultdict(list)
for d in data:
for img_col in img_cols:
if d.get(img_col, None):
if isinstance(d[img_col], Image.Image):
images[img_col].append(d[img_col])
else:
with file_io.FileIO(d[img_col], 'rb') as fi:
im = Image.open(fi)
images[img_col].append(im)
else:
images[img_col].append('')
return images | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier for_statement identifier identifier block for_statement identifier identifier block if_statement call attribute identifier identifier argument_list identifier none block if_statement call identifier argument_list subscript identifier identifier attribute identifier identifier block expression_statement call attribute subscript identifier identifier identifier argument_list subscript identifier identifier else_clause block with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list subscript identifier identifier string string_start string_content string_end as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute subscript identifier identifier identifier argument_list identifier else_clause block expression_statement call attribute subscript identifier identifier identifier argument_list string string_start string_end return_statement identifier | Download images given image columns. |
def closeEvent(self, event):
self.stop_process()
self.backend.stop()
try:
self.modes.remove('_LinkHighlighter')
except KeyError:
pass
super(OutputWindow, self).closeEvent(event) | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end except_clause identifier block pass_statement expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list identifier | Terminates the child process on close. |
def make_vol_opt(hostdir, contdir, options=None):
vol = '--volume={}:{}'.format(hostdir, contdir)
if options != None:
if isinstance(options, str):
options = (options,)
vol += ':' + ','.join(options)
return vol | module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier identifier if_statement comparison_operator identifier none block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier tuple identifier expression_statement augmented_assignment identifier binary_operator string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list identifier return_statement identifier | Generate a docker volume option |
def _load_market_scheme(self):
try:
self.scheme = yaml.load(open(self.scheme_path, 'r'))
except Exception, error:
raise LoadMarketSchemeFailed(reason=error) | module function_definition identifier parameters identifier block try_statement block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list call identifier argument_list attribute identifier identifier string string_start string_content string_end except_clause identifier identifier block raise_statement call identifier argument_list keyword_argument identifier identifier | Load market yaml description |
def add(self, *number):
return self._format_result(sum(
[int(n) for n in number])) | module function_definition identifier parameters identifier list_splat_pattern identifier block return_statement call attribute identifier identifier argument_list call identifier argument_list list_comprehension call identifier argument_list identifier for_in_clause identifier identifier | Adds all parameters interpreted as integers |
def CalcDayOfWeek(self):
year, month, day, day_of_week = self.value
day_of_week = 255
if year == 255:
pass
elif month in _special_mon_inv:
pass
elif day in _special_day_inv:
pass
else:
try:
today = time.mktime( (year + 1900, month, day, 0, 0, 0, 0, 0, -1) )
day_of_week = time.gmtime(today)[6] + 1
except OverflowError:
pass
self.value = (year, month, day, day_of_week) | module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier identifier identifier attribute identifier identifier expression_statement assignment identifier integer if_statement comparison_operator identifier integer block pass_statement elif_clause comparison_operator identifier identifier block pass_statement elif_clause comparison_operator identifier identifier block pass_statement else_clause block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list tuple binary_operator identifier integer identifier identifier integer integer integer integer integer unary_operator integer expression_statement assignment identifier binary_operator subscript call attribute identifier identifier argument_list identifier integer integer except_clause identifier block pass_statement expression_statement assignment attribute identifier identifier tuple identifier identifier identifier identifier | Calculate the correct day of the week. |
def find_java_home(cratedb_version: tuple) -> str:
if MIN_VERSION_FOR_JVM11 <= cratedb_version < (4, 0):
return os.environ.get('JAVA_HOME', '')
if cratedb_version < MIN_VERSION_FOR_JVM11:
return _find_matching_java_home(lambda ver: ver[0] == 8)
else:
return _find_matching_java_home(lambda ver: ver[0] >= 11) | module function_definition identifier parameters typed_parameter identifier type identifier type identifier block if_statement comparison_operator identifier identifier tuple integer integer block return_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_end if_statement comparison_operator identifier identifier block return_statement call identifier argument_list lambda lambda_parameters identifier comparison_operator subscript identifier integer integer else_clause block return_statement call identifier argument_list lambda lambda_parameters identifier comparison_operator subscript identifier integer integer | Return a path to a JAVA_HOME suites for the given CrateDB version |
def _get_ann(dbs, features):
value = ""
for db, feature in zip(dbs, features):
value += db + ":" + feature
return value | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier string string_start string_end for_statement pattern_list identifier identifier call identifier argument_list identifier identifier block expression_statement augmented_assignment identifier binary_operator binary_operator identifier string string_start string_content string_end identifier return_statement identifier | Gives format to annotation for html table output |
def normalize_time(timestamp):
offset = timestamp.utcoffset()
if offset is None:
return timestamp
return timestamp.replace(tzinfo=None) - offset | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator identifier none block return_statement identifier return_statement binary_operator call attribute identifier identifier argument_list keyword_argument identifier none identifier | Normalize time in arbitrary timezone to UTC naive object. |
def load_children(self, f):
while True:
line = self.readline(f)
if line[0] == '&':
if line[1:].startswith("END"):
check_name = line[4:].strip().upper()
if check_name != self.__name:
raise FileFormatError("CP2KSection end mismatch, pos=%s", f.tell())
break
else:
section = CP2KSection()
section.load(f, line)
self.append(section)
else:
keyword = CP2KKeyword()
keyword.load(line)
self.append(keyword) | module function_definition identifier parameters identifier identifier block while_statement true block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator subscript identifier integer string string_start string_content string_end block if_statement call attribute subscript identifier slice integer identifier argument_list string string_start string_content string_end block expression_statement assignment identifier call attribute call attribute subscript identifier slice integer identifier argument_list identifier argument_list if_statement comparison_operator identifier attribute identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list break_statement else_clause block expression_statement assignment identifier call identifier argument_list expression_statement call attribute identifier identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list identifier else_clause block expression_statement assignment identifier call identifier argument_list expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier | Load the children of this section from a file-like object |
def authenticate_credentials(self, request, access_token):
try:
token = oauth2_provider.oauth2.models.AccessToken.objects.select_related('user')
token = token.get(token=access_token, expires__gt=provider_now())
except oauth2_provider.oauth2.models.AccessToken.DoesNotExist:
raise exceptions.AuthenticationFailed('Invalid token')
user = token.user
if not user.is_active:
msg = 'User inactive or deleted: %s' % user.username
raise exceptions.AuthenticationFailed(msg)
return (user, token) | module function_definition identifier parameters identifier identifier identifier block try_statement block expression_statement assignment identifier call attribute attribute attribute attribute attribute identifier identifier identifier identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier call identifier argument_list except_clause attribute attribute attribute attribute identifier identifier identifier identifier identifier block raise_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier attribute identifier identifier if_statement not_operator attribute identifier identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end attribute identifier identifier raise_statement call attribute identifier identifier argument_list identifier return_statement tuple identifier identifier | Authenticate the request, given the access token. |
def select(self):
if sys.platform=='win32':
self.dc.SelectObject(self.bitmap)
self.IsSelected = True | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier true | Select the current bitmap into this wxDC instance |
def update_buildroot_koji(self, buildroot, output):
docker = output[1]['extra']['docker']
name = ''
for tag in docker['tags']:
for repo in docker['repositories']:
if tag in repo:
iname = ImageName.parse(repo)
name = iname.to_str(registry=False)
break
buildroot['extra']['osbs']['koji'] = {
'build_name': name,
'builder_image_id': docker.get('digests', {})
} | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier subscript subscript subscript identifier integer string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier string string_start string_end for_statement identifier subscript identifier string string_start string_content string_end block for_statement identifier subscript identifier string string_start string_content string_end block if_statement comparison_operator identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier false break_statement expression_statement assignment subscript subscript subscript identifier string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end dictionary | put the final koji information in the buildroot under extra.osbs |
def multidict(ordered_pairs):
d = defaultdict(list)
for k, v in ordered_pairs:
d[k].append(v)
dict_copy = deepcopy(d)
for k, v in iteritems(dict_copy):
if len(v) == 1:
d[k] = v[0]
return dict(d) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier for_statement pattern_list identifier identifier identifier block expression_statement call attribute subscript identifier identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier for_statement pattern_list identifier identifier call identifier argument_list identifier block if_statement comparison_operator call identifier argument_list identifier integer block expression_statement assignment subscript identifier identifier subscript identifier integer return_statement call identifier argument_list identifier | Convert duplicate keys values to lists. |
def tag_map(self):
tm = dd(list)
for tag in self.__tags:
tm[tag.tagtype].append(tag)
return tm | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier for_statement identifier attribute identifier identifier block expression_statement call attribute subscript identifier attribute identifier identifier identifier argument_list identifier return_statement identifier | Build a map from tagtype to list of tags |
async def _set_subscriptions(self, subscriptions):
url, params = self._get_subscriptions_endpoint()
data = {
'object': 'page',
'callback_url': self.webhook_url,
'fields': ', '.join(subscriptions),
'verify_token': self.verify_token,
}
headers = {
'Content-Type': 'application/json',
}
post = self.session.post(
url,
params=params,
data=ujson.dumps(data),
headers=headers,
)
async with post as r:
await self._handle_fb_response(r)
data = await r.json() | module function_definition identifier parameters identifier identifier block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list expression_statement assignment identifier dictionary pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list identifier pair string string_start string_content string_end attribute identifier identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier with_statement with_clause with_item as_pattern identifier as_pattern_target identifier block expression_statement await call attribute identifier identifier argument_list identifier expression_statement assignment identifier await call attribute identifier identifier argument_list | Set the subscriptions to a specific list of values |
def add_last_closed_file(self, fname):
if fname in self.last_closed_files:
self.last_closed_files.remove(fname)
self.last_closed_files.insert(0, fname)
if len(self.last_closed_files) > 10:
self.last_closed_files.pop(-1) | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list integer identifier if_statement comparison_operator call identifier argument_list attribute identifier identifier integer block expression_statement call attribute attribute identifier identifier identifier argument_list unary_operator integer | Add to last closed file list. |
def mapstr_to_list(mapstr):
maplist = []
with StringIO(mapstr) as infile:
for row in infile:
maplist.append(row.strip())
return maplist | module function_definition identifier parameters identifier block expression_statement assignment identifier list with_statement with_clause with_item as_pattern call identifier argument_list identifier as_pattern_target identifier block for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list return_statement identifier | Convert an ASCII map string with rows to a list of strings, 1 string per row. |
def clear(self):
self._imgobj = None
try:
self.canvas.delete_object_by_tag(self._canvas_img_tag)
self.redraw()
except KeyError:
pass | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier none try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list except_clause identifier block pass_statement | Clear the displayed image. |
def interfaces(self):
if not self._interfaces_cache:
response = yield from self.get("/network/interfaces")
self._interfaces_cache = response.json
return self._interfaces_cache | module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block expression_statement assignment identifier yield call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment attribute identifier identifier attribute identifier identifier return_statement attribute identifier identifier | Get the list of network on compute |
def __update_rating(uid, rating):
entry = TabPost.update(
rating=rating
).where(TabPost.uid == uid)
entry.execute() | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list keyword_argument identifier identifier identifier argument_list comparison_operator attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list | Update the rating for post. |
def unpy2exe(filename, python_version=None, output_dir=None):
if output_dir is None:
output_dir = '.'
elif not os.path.exists(output_dir):
os.makedirs(output_dir)
pe = pefile.PE(filename)
is_py2exe = check_py2exe_file(pe)
if not is_py2exe:
raise ValueError('Not a py2exe executable.')
code_objects = extract_code_objects(pe)
for co in code_objects:
dump_to_pyc(co, python_version, output_dir) | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier string string_start string_content string_end elif_clause not_operator call attribute attribute identifier identifier identifier argument_list identifier block expression_statement 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 identifier if_statement not_operator identifier block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier for_statement identifier identifier block expression_statement call identifier argument_list identifier identifier identifier | Process input params and produce output pyc files. |
def _django_to_es_field(self, field):
from django.db import models
prefix = ""
if field.startswith("-"):
prefix = "-"
field = field.lstrip("-")
if field in ["id", "pk"]:
return "_id", models.AutoField
try:
dj_field, _, _, _ = self.model._meta.get_field_by_name(field)
if isinstance(dj_field, models.ForeignKey):
return prefix + field + "_id", models.ForeignKey
else:
return prefix + field, dj_field
except models.FieldDoesNotExist:
pass
return prefix + field.replace(FIELD_SEPARATOR, "."), None | module function_definition identifier parameters identifier identifier block import_from_statement dotted_name identifier identifier dotted_name identifier expression_statement assignment identifier string string_start string_end if_statement call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier list string string_start string_content string_end string string_start string_content string_end block return_statement expression_list string string_start string_content string_end attribute identifier identifier try_statement block expression_statement assignment pattern_list identifier identifier identifier identifier call attribute attribute attribute identifier identifier identifier identifier argument_list identifier if_statement call identifier argument_list identifier attribute identifier identifier block return_statement expression_list binary_operator binary_operator identifier identifier string string_start string_content string_end attribute identifier identifier else_clause block return_statement expression_list binary_operator identifier identifier identifier except_clause attribute identifier identifier block pass_statement return_statement expression_list binary_operator identifier call attribute identifier identifier argument_list identifier string string_start string_content string_end none | We use this function in value_list and ordering to get the correct fields name |
def stderr_file(self):
stderr_file = None
if self.connection_file is not None:
stderr_file = self.kernel_id + '.stderr'
if self.stderr_dir is not None:
stderr_file = osp.join(self.stderr_dir, stderr_file)
else:
try:
stderr_file = osp.join(get_temp_dir(), stderr_file)
except (IOError, OSError):
stderr_file = None
return stderr_file | module function_definition identifier parameters identifier block expression_statement assignment identifier none if_statement comparison_operator attribute identifier identifier none block expression_statement assignment identifier binary_operator attribute identifier identifier string string_start string_content string_end if_statement comparison_operator attribute identifier identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier identifier else_clause block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list call identifier argument_list identifier except_clause tuple identifier identifier block expression_statement assignment identifier none return_statement identifier | Filename to save kernel stderr output. |
def create_configwidget(self, parent):
if self.CONFIGWIDGET_CLASS is not None:
configwidget = self.CONFIGWIDGET_CLASS(self, parent)
configwidget.initialize()
return configwidget | module function_definition identifier parameters identifier identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list return_statement identifier | Create configuration dialog box page widget |
def label_from_func(self, func:Callable, label_cls:Callable=None, **kwargs)->'LabelList':
"Apply `func` to every input to get its label."
return self._label_from_list([func(o) for o in self.items], label_cls=label_cls, **kwargs) | module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_default_parameter identifier type identifier none dictionary_splat_pattern identifier type string string_start string_content string_end block expression_statement string string_start string_content string_end return_statement call attribute identifier identifier argument_list list_comprehension call identifier argument_list identifier for_in_clause identifier attribute identifier identifier keyword_argument identifier identifier dictionary_splat identifier | Apply `func` to every input to get its label. |
def _hierarchy(self):
self.hierarchy = {}
for rank in self.taxonomy:
taxslice = self._slice(level=self.taxonomy.index(rank))
self.hierarchy[rank] = self._group(taxslice) | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier dictionary for_statement identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment subscript attribute identifier identifier identifier call attribute identifier identifier argument_list identifier | Generate dictionary of referenced idents grouped by shared rank |
def from_name(cls, name):
result = cls.list()
dc_names = {}
for dc in result:
dc_names[dc['name']] = dc['id']
return dc_names.get(name) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier dictionary for_statement identifier identifier block expression_statement assignment subscript identifier subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end return_statement call attribute identifier identifier argument_list identifier | Retrieve datacenter id associated to a name. |
def full_analysis(self, analysis_set, output_directory, verbose = True, compile_pdf = True, quick_plots = False):
if not os.path.isdir(output_directory):
os.makedirs(output_directory)
self.analysis_directory = output_directory
self.calculate_metrics(analysis_set = analysis_set, analysis_directory = output_directory, verbose = verbose)
self.write_dataframe_to_csv( os.path.join(output_directory, 'data.csv') )
return self.plot(analysis_set = analysis_set, analysis_directory = output_directory, matplotlib_plots = True, verbose = verbose, compile_pdf = compile_pdf, quick_plots = quick_plots) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier true default_parameter identifier true default_parameter identifier false block if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end return_statement call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier true keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier | Combines calculate_metrics, write_dataframe_to_csv, and plot |
def pull_repo(repo_name):
repo = ClonedRepo.objects.get(pk=repo_name)
repo.pull() | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list | Pull from origin for repo_name. |
def _get_websocket(self, reuse=True):
if self.ws and reuse:
if self.ws.connected:
return self.ws
logging.debug("Stale connection, reconnecting.")
self.ws = self._create_connection()
return self.ws | module function_definition identifier parameters identifier default_parameter identifier true block if_statement boolean_operator attribute identifier identifier identifier block if_statement attribute attribute identifier identifier identifier block return_statement attribute identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list return_statement attribute identifier identifier | Reuse existing connection or create a new connection. |
def vec_by_id(self, docid):
pos = self.id2pos[docid]
return self.qindex.vector_by_id(pos) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier identifier return_statement call attribute attribute identifier identifier identifier argument_list identifier | Return indexed vector corresponding to document `docid`. |
def drain_events(self, allowed_methods=None, timeout=None):
return self.wait_multi(self.channels.values(), timeout=timeout) | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none block return_statement call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier | Wait for an event on any channel. |
def fan_maxcfm(ddtt):
if str(ddtt.Maximum_Flow_Rate).lower() == 'autosize':
return 'autosize'
else:
m3s = float(ddtt.Maximum_Flow_Rate)
return m3s2cfm(m3s) | module function_definition identifier parameters identifier block if_statement comparison_operator call attribute call identifier argument_list attribute identifier identifier identifier argument_list string string_start string_content string_end block return_statement string string_start string_content string_end else_clause block expression_statement assignment identifier call identifier argument_list attribute identifier identifier return_statement call identifier argument_list identifier | return the fan max cfm |
def open_fileswitcher(self, symbol=False):
if self.fileswitcher is not None and \
self.fileswitcher.is_visible:
self.fileswitcher.hide()
self.fileswitcher.is_visible = False
return
if symbol:
self.fileswitcher.plugin = self.editor
self.fileswitcher.set_search_text('@')
else:
self.fileswitcher.set_search_text('')
self.fileswitcher.show()
self.fileswitcher.is_visible = True | module function_definition identifier parameters identifier default_parameter identifier false block if_statement boolean_operator comparison_operator attribute identifier identifier none line_continuation attribute attribute identifier identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement assignment attribute attribute identifier identifier identifier false return_statement if_statement identifier block expression_statement assignment attribute attribute identifier identifier identifier attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end else_clause block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_end expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement assignment attribute attribute identifier identifier identifier true | Open file list management dialog box. |
def sodium_memcmp(inp1, inp2):
ensure(isinstance(inp1, bytes),
raising=exc.TypeError)
ensure(isinstance(inp2, bytes),
raising=exc.TypeError)
ln = max(len(inp1), len(inp2))
buf1 = ffi.new("char []", ln)
buf2 = ffi.new("char []", ln)
ffi.memmove(buf1, inp1, len(inp1))
ffi.memmove(buf2, inp2, len(inp2))
eqL = len(inp1) == len(inp2)
eqC = lib.sodium_memcmp(buf1, buf2, ln) == 0
return eqL and eqC | module function_definition identifier parameters identifier identifier block expression_statement call identifier argument_list call identifier argument_list identifier identifier keyword_argument identifier attribute identifier identifier expression_statement call identifier argument_list call identifier argument_list identifier identifier keyword_argument identifier attribute identifier identifier expression_statement assignment identifier call identifier argument_list call identifier argument_list identifier call identifier argument_list identifier 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_list string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list identifier identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier identifier call identifier argument_list identifier expression_statement assignment identifier comparison_operator call identifier argument_list identifier call identifier argument_list identifier expression_statement assignment identifier comparison_operator call attribute identifier identifier argument_list identifier identifier identifier integer return_statement boolean_operator identifier identifier | Compare contents of two memory regions in constant time |
def load_template_source(template_name, template_dirs=None):
template_zipfiles = getattr(settings, "TEMPLATE_ZIP_FILES", [])
for fname in template_zipfiles:
try:
z = zipfile.ZipFile(fname)
source = z.read(template_name)
except (IOError, KeyError):
continue
z.close()
template_path = "%s:%s" % (fname, template_name)
return (source, template_path)
raise TemplateDoesNotExist(template_name) | module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end list for_statement identifier identifier block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier except_clause tuple identifier identifier block continue_statement expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier binary_operator string string_start string_content string_end tuple identifier identifier return_statement tuple identifier identifier raise_statement call identifier argument_list identifier | Template loader that loads templates from a ZIP file. |
def start(self):
self._events_to_write = []
self._new_contracts_to_write = []
@events.on(SmartContractEvent.CONTRACT_CREATED)
@events.on(SmartContractEvent.CONTRACT_MIGRATED)
def call_on_success_event(sc_event: SmartContractEvent):
self.on_smart_contract_created(sc_event)
@events.on(SmartContractEvent.RUNTIME_NOTIFY)
def call_on_event(sc_event: NotifyEvent):
self.on_smart_contract_event(sc_event)
Blockchain.Default().PersistCompleted.on_change += self.on_persist_completed | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier list expression_statement assignment attribute identifier identifier list decorated_definition decorator call attribute identifier identifier argument_list attribute identifier identifier decorator call attribute identifier identifier argument_list attribute identifier identifier function_definition identifier parameters typed_parameter identifier type identifier block expression_statement call attribute identifier identifier argument_list identifier decorated_definition decorator call attribute identifier identifier argument_list attribute identifier identifier function_definition identifier parameters typed_parameter identifier type identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement augmented_assignment attribute attribute call attribute identifier identifier argument_list identifier identifier attribute identifier identifier | Handle EventHub events for SmartContract decorators |
def create_from_eflux(cls, params, emin, emax, eflux, scale=1.0):
params = params.copy()
params[0] = 1.0
params[0] = eflux / cls.eval_eflux(emin, emax, params, scale=scale)
return cls(params, scale) | module function_definition identifier parameters identifier identifier identifier identifier identifier default_parameter identifier float block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment subscript identifier integer float expression_statement assignment subscript identifier integer binary_operator identifier call attribute identifier identifier argument_list identifier identifier identifier keyword_argument identifier identifier return_statement call identifier argument_list identifier identifier | Create a spectral function instance given its energy flux. |
def load(self):
try:
self._read()
self._parse()
except Exception as exc:
self.failed = True
params = {'path': self._path, 'exception': exc}
if self.fail_silently:
LOG.warning("Error processing message json file '%(path)s': "
"%(exception)s", params)
else:
raise exceptions.MessageFailure(
_("Error processing message json file '%(path)s': "
"%(exception)s") % params) | module function_definition identifier parameters identifier block try_statement block expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list except_clause as_pattern identifier as_pattern_target identifier block expression_statement assignment attribute identifier identifier true expression_statement assignment identifier dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end identifier if_statement attribute identifier 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 identifier else_clause block raise_statement call attribute identifier identifier argument_list binary_operator call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end identifier | Read and parse the message file. |
def rgb2short(r, g, b):
r, g, b = [len(tuple(s for s in snaps if s < x)) for x in (r, g, b)]
return (r * 36) + (g * 6) + b + 16 | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment pattern_list identifier identifier identifier list_comprehension call identifier argument_list call identifier generator_expression identifier for_in_clause identifier identifier if_clause comparison_operator identifier identifier for_in_clause identifier tuple identifier identifier identifier return_statement binary_operator binary_operator binary_operator parenthesized_expression binary_operator identifier integer parenthesized_expression binary_operator identifier integer identifier integer | Converts RGB values to the nearest equivalent xterm-256 color. |
def can_user_approve_this_page(self, user):
self.ensure_one()
if not self.is_approval_required:
return True
if user.has_group('document_page.group_document_manager'):
return True
if not user.has_group(
'document_page_approval.group_document_approver_user'):
return False
if not self.approver_group_ids:
return True
return len(user.groups_id & self.approver_group_ids) > 0 | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list if_statement not_operator attribute identifier identifier block return_statement true if_statement call attribute identifier identifier argument_list string string_start string_content string_end block return_statement true if_statement not_operator call attribute identifier identifier argument_list string string_start string_content string_end block return_statement false if_statement not_operator attribute identifier identifier block return_statement true return_statement comparison_operator call identifier argument_list binary_operator attribute identifier identifier attribute identifier identifier integer | Check if a user can approve this page. |
def _styleof(expr, styles):
style = dict()
for expr_filter, sty in styles:
if expr_filter(expr):
style.update(sty)
return style | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list for_statement pattern_list identifier identifier identifier block if_statement call identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Merge style dictionaries in order |
def connection_made(self, transport):
self.logger.info('Connection made at object %s', id(self))
self.transport = transport
self.keepalive = True
if self._timeout:
self.logger.debug('Registering timeout event')
self._timout_handle = self._loop.call_later(
self._timeout, self._handle_timeout) | module function_definition identifier parameters identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end call identifier argument_list identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier true if_statement attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier attribute identifier identifier | Called when the connection is made |
def _get_vswitch_for_physical_network(self, phys_network_name):
for pattern in self._physical_network_mappings:
if phys_network_name is None:
phys_network_name = ''
if re.match(pattern, phys_network_name):
return self._physical_network_mappings[pattern] | module function_definition identifier parameters identifier identifier block for_statement identifier attribute identifier identifier block if_statement comparison_operator identifier none block expression_statement assignment identifier string string_start string_end if_statement call attribute identifier identifier argument_list identifier identifier block return_statement subscript attribute identifier identifier identifier | Get the vswitch name for the received network name. |
def _md5(path, blocksize=2 ** 20):
m = hashlib.md5()
with open(path, 'rb') as f:
while True:
buf = f.read(blocksize)
if not buf:
break
m.update(buf)
return m.hexdigest() | module function_definition identifier parameters identifier default_parameter identifier binary_operator integer integer block expression_statement assignment identifier call attribute identifier identifier argument_list 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 while_statement true block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement not_operator identifier block break_statement expression_statement call attribute identifier identifier argument_list identifier return_statement call attribute identifier identifier argument_list | Compute the checksum of a file. |
def doc_browse(self, args, range=None):
self.log.debug('browse: in')
self.call_options[self.call_id] = {"browse": True}
self.send_at_position("DocUri", False, "point") | module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment subscript attribute identifier identifier attribute identifier identifier dictionary pair string string_start string_content string_end true expression_statement call attribute identifier identifier argument_list string string_start string_content string_end false string string_start string_content string_end | Browse doc of whatever at cursor. |
def _pulse_enable(self):
GPIO.output(self.pins.e, 0)
c.usleep(1)
GPIO.output(self.pins.e, 1)
c.usleep(1)
GPIO.output(self.pins.e, 0)
c.usleep(100) | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list attribute attribute identifier identifier identifier integer expression_statement call attribute identifier identifier argument_list integer expression_statement call attribute identifier identifier argument_list attribute attribute identifier identifier identifier integer expression_statement call attribute identifier identifier argument_list integer expression_statement call attribute identifier identifier argument_list attribute attribute identifier identifier identifier integer expression_statement call attribute identifier identifier argument_list integer | Pulse the `enable` flag to process data. |
def _add_spanning_relation(self, source, target):
self.add_edge(source, target, layers={self.ns, self.ns+':unit'},
edge_type=EdgeTypes.spanning_relation) | module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list identifier identifier keyword_argument identifier set attribute identifier identifier binary_operator attribute identifier identifier string string_start string_content string_end keyword_argument identifier attribute identifier identifier | add a spanning relation to this docgraph |
def add(self, queue_name, transactional=False):
task = self.to_task()
task.add(queue_name, transactional) | module function_definition identifier parameters identifier identifier default_parameter identifier false block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier identifier | Add task to the queue. |
def _make_index(df, cols=META_IDX):
return pd.MultiIndex.from_tuples(
pd.unique(list(zip(*[df[col] for col in cols]))), names=tuple(cols)) | module function_definition identifier parameters identifier default_parameter identifier identifier block return_statement call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list call identifier argument_list call identifier argument_list list_splat list_comprehension subscript identifier identifier for_in_clause identifier identifier keyword_argument identifier call identifier argument_list identifier | Create an index from the columns of a dataframe |
def _call(self, x, out=None):
if out is None:
out = self.range.element()
with writable_array(out) as out_arr:
finite_diff(x.asarray(), axis=self.axis, dx=self.dx,
method=self.method, pad_mode=self.pad_mode,
pad_const=self.pad_const, out=out_arr)
return out | module function_definition identifier parameters identifier identifier default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list with_statement with_clause with_item as_pattern call identifier argument_list identifier as_pattern_target identifier block expression_statement call identifier argument_list call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier return_statement identifier | Calculate partial derivative of ``x``. |
def homer_stats_table_interChr(self):
headers = OrderedDict()
headers['InterChr'] = {
'title': 'InterChr',
'description': 'Fraction of Reads forming inter chromosomal interactions',
'format': '{:,.4f}'
}
self.general_stats_addcols(self.tagdir_data['FreqDistribution'], headers, 'Homer-InterChr') | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment subscript identifier string string_start string_content string_end dictionary pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end expression_statement call attribute identifier identifier argument_list subscript attribute identifier identifier string string_start string_content string_end identifier string string_start string_content string_end | Add core HOMER stats to the general stats table from FrequencyDistribution file |
def del_actor(self, actor):
if _debug: TCPClientDirector._debug("del_actor %r", actor)
del self.clients[actor.peer]
if self.serviceElement:
self.sap_request(del_actor=actor)
if actor.peer in self.reconnect:
connect_task = FunctionTask(self.connect, actor.peer)
connect_task.install_task(_time() + self.reconnect[actor.peer]) | module function_definition identifier parameters identifier identifier block if_statement identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier delete_statement subscript attribute identifier identifier attribute identifier identifier if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier if_statement comparison_operator attribute identifier identifier attribute identifier identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list binary_operator call identifier argument_list subscript attribute identifier identifier attribute identifier identifier | Remove an actor when the socket is closed. |
def matches_truth(call_alleles, truth_alleles, data):
if not truth_alleles:
return ""
else:
def _remove_p(x):
return x[:-1] if x.endswith("P") else x
t_cmp = set([_remove_p(hla_groups.hla_protein(x, data)) for x in truth_alleles])
c_cmp = set([_remove_p(hla_groups.hla_protein(x, data)) for x in call_alleles])
return "yes" if len(t_cmp.intersection(c_cmp)) == len(t_cmp) else "no" | module function_definition identifier parameters identifier identifier identifier block if_statement not_operator identifier block return_statement string string_start string_end else_clause block function_definition identifier parameters identifier block return_statement conditional_expression subscript identifier slice unary_operator integer call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement assignment identifier call identifier argument_list list_comprehension call identifier argument_list call attribute identifier identifier argument_list identifier identifier for_in_clause identifier identifier expression_statement assignment identifier call identifier argument_list list_comprehension call identifier argument_list call attribute identifier identifier argument_list identifier identifier for_in_clause identifier identifier return_statement conditional_expression string string_start string_content string_end comparison_operator call identifier argument_list call attribute identifier identifier argument_list identifier call identifier argument_list identifier string string_start string_content string_end | Flexibly check if truth and call alleles match, using p-groups. |
def fetch(elastic, backend, limit=None, search_after_value=None, scroll=True):
logging.debug("Creating a elastic items generator.")
elastic_scroll_id = None
search_after = search_after_value
while True:
if scroll:
rjson = get_elastic_items(elastic, elastic_scroll_id, limit)
else:
rjson = get_elastic_items_search(elastic, search_after, limit)
if rjson and "_scroll_id" in rjson:
elastic_scroll_id = rjson["_scroll_id"]
if rjson and "hits" in rjson:
if not rjson["hits"]["hits"]:
break
for hit in rjson["hits"]["hits"]:
item = hit['_source']
if 'sort' in hit:
search_after = hit['sort']
try:
backend._fix_item(item)
except Exception:
pass
yield item
else:
logging.error("No results found from %s", elastic.index_url)
break
return | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier none default_parameter identifier true block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier none expression_statement assignment identifier identifier while_statement true block if_statement identifier block expression_statement assignment identifier call identifier argument_list identifier identifier identifier else_clause block expression_statement assignment identifier call identifier argument_list identifier identifier identifier if_statement boolean_operator identifier comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier subscript identifier string string_start string_content string_end if_statement boolean_operator identifier comparison_operator string string_start string_content string_end identifier block if_statement not_operator subscript subscript identifier string string_start string_content string_end string string_start string_content string_end block break_statement for_statement identifier subscript subscript identifier string string_start string_content string_end string string_start string_content string_end block expression_statement assignment identifier subscript identifier string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier subscript identifier string string_start string_content string_end try_statement block expression_statement call attribute identifier identifier argument_list identifier except_clause identifier block pass_statement expression_statement yield identifier else_clause block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier break_statement return_statement | Fetch the items from raw or enriched index |
def _update_const_classes():
klasses = (bool, int, float, complex, str, bytes)
for kls in klasses:
CONST_CLS[kls] = Const | module function_definition identifier parameters block expression_statement assignment identifier tuple identifier identifier identifier identifier identifier identifier for_statement identifier identifier block expression_statement assignment subscript identifier identifier identifier | update constant classes, so the keys of CONST_CLS can be reused |
def _relative_uris(self, uri_list):
return [u for u in (self._relative(uri) for uri in uri_list) if u] | module function_definition identifier parameters identifier identifier block return_statement list_comprehension identifier for_in_clause identifier generator_expression call attribute identifier identifier argument_list identifier for_in_clause identifier identifier if_clause identifier | if uris in list are relative, re-relate them to our basedir |
def setup_custom_logger(name):
global loggers
if loggers.get(name):
return loggers.get(name)
formatter = logging.Formatter(
fmt='%(levelname)s: %(message)s'
)
handler = TqdmLoggingHandler()
handler.setFormatter(formatter)
if system() not in ['Windows', 'cli']:
logging.addLevelName(logging.ERROR, "\033[1;31m%s\033[1;0m" % logging.getLevelName(logging.ERROR))
logging.addLevelName(logging.WARNING, "\033[1;33m%s\033[1;0m" % logging.getLevelName(logging.WARNING))
logging.addLevelName(logging.INFO, "\033[1;34m%s\033[1;0m" % logging.getLevelName(logging.INFO))
logging.addLevelName(logging.DEBUG, "\033[1;35m%s\033[1;0m" % logging.getLevelName(logging.DEBUG))
logger = logging.getLogger(name)
logger.setLevel(logging.WARNING)
if logger.handlers:
logger.handlers = []
logger.addHandler(handler)
loggers.update(dict(name=logger))
return logger | module function_definition identifier parameters identifier block global_statement identifier if_statement call attribute identifier identifier argument_list identifier block return_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list expression_statement call attribute identifier identifier argument_list identifier if_statement comparison_operator call identifier argument_list list string string_start string_content string_end string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list attribute identifier identifier binary_operator string string_start string_content escape_sequence escape_sequence string_end call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier binary_operator string string_start string_content escape_sequence escape_sequence string_end call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier binary_operator string string_start string_content escape_sequence escape_sequence string_end call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier binary_operator string string_start string_content escape_sequence escape_sequence string_end call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier if_statement attribute identifier identifier block expression_statement assignment attribute identifier identifier list expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list call identifier argument_list keyword_argument identifier identifier return_statement identifier | Create a logger with a certain name and level |
def notify_exception(self, exception, run_done_callbacks=True):
logger.error("%s : %s" % (exception.__class__.__name__, str(exception)))
self._exception = exception
if self.is_running(True):
for _cnt in range(0, 5):
if not self._cancel():
time.sleep(1)
else:
break
self.notify_done(error=True, run_done_callbacks=run_done_callbacks) | module function_definition identifier parameters identifier identifier default_parameter identifier true block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple attribute attribute identifier identifier identifier call identifier argument_list identifier expression_statement assignment attribute identifier identifier identifier if_statement call attribute identifier identifier argument_list true block for_statement identifier call identifier argument_list integer integer block if_statement not_operator call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list integer else_clause block break_statement expression_statement call attribute identifier identifier argument_list keyword_argument identifier true keyword_argument identifier identifier | set the exception message, stop transfer if running and set the done event |
def update_params(self, params):
if not params.get('BINARY', True):
raise Warning('To increase performance please use ElastiCache'
' in binary mode')
else:
params['BINARY'] = True
if 'OPTIONS' not in params:
params['OPTIONS'] = {
'tcp_nodelay': True,
'ketama': True
} | module function_definition identifier parameters identifier identifier block if_statement not_operator call attribute identifier identifier argument_list string string_start string_content string_end true block raise_statement call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end else_clause block expression_statement assignment subscript identifier string string_start string_content string_end true if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end dictionary pair string string_start string_content string_end true pair string string_start string_content string_end true | update connection params to maximize performance |
def run(self):
self._clearQuantities()
self._clearPrices()
self._clipPrices()
self._logClearances()
return self.offers, self.bids | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list return_statement expression_list attribute identifier identifier attribute identifier identifier | Clears a set of bids and offers. |
def parse_negation_operation(operation: str) -> Tuple[bool, str]:
_operation = operation.strip()
if not _operation:
raise QueryParserException('Operation is not valid: {}'.format(operation))
negation = False
if _operation[0] == '~':
negation = True
_operation = _operation[1:]
return negation, _operation.strip() | module function_definition identifier parameters typed_parameter identifier type identifier type generic_type identifier type_parameter type identifier type identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement not_operator identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier false if_statement comparison_operator subscript identifier integer string string_start string_content string_end block expression_statement assignment identifier true expression_statement assignment identifier subscript identifier slice integer return_statement expression_list identifier call attribute identifier identifier argument_list | Parse the negation modifier in an operation. |
def _basis_polynomial_factory(cls, kind):
valid_kind = cls._validate(kind)
basis_polynomial = getattr(np.polynomial, valid_kind)
return basis_polynomial | 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 return_statement identifier | Return a polynomial given some coefficients. |
def validate_file_permissions(config):
files = config.get('files', {})
for file_name, options in files.items():
for key in options.keys():
if key not in ["owner", "group", "mode"]:
raise RuntimeError(
"Invalid ownership configuration: {}".format(key))
mode = options.get('mode', config.get('permissions', '600'))
optional = options.get('optional', config.get('optional', 'False'))
if '*' in file_name:
for file in glob.glob(file_name):
if file not in files.keys():
if os.path.isfile(file):
_validate_file_mode(mode, file, optional)
else:
if os.path.isfile(file_name):
_validate_file_mode(mode, file_name, optional) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end dictionary for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block for_statement identifier call attribute identifier identifier argument_list block if_statement comparison_operator identifier list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier call 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 string string_start string_content string_end expression_statement assignment identifier 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 string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end identifier block for_statement identifier call attribute identifier identifier argument_list identifier block if_statement comparison_operator identifier call attribute identifier identifier argument_list block if_statement call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call identifier argument_list identifier identifier identifier else_clause block if_statement call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call identifier argument_list identifier identifier identifier | Verify that permissions on configuration files are secure enough. |
def _set_duty(self, motor_duty_file, duty, friction_offset,
voltage_comp):
duty_int = int(round(duty*voltage_comp))
if duty_int > 0:
duty_int = min(100, duty_int + friction_offset)
elif duty_int < 0:
duty_int = max(-100, duty_int - friction_offset)
self._fast_write(motor_duty_file, duty_int) | module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment identifier call identifier argument_list call identifier argument_list binary_operator identifier identifier if_statement comparison_operator identifier integer block expression_statement assignment identifier call identifier argument_list integer binary_operator identifier identifier elif_clause comparison_operator identifier integer block expression_statement assignment identifier call identifier argument_list unary_operator integer binary_operator identifier identifier expression_statement call attribute identifier identifier argument_list identifier identifier | Function to set the duty cycle of the motors. |
def imagenet_clamp_batch(batch, low, high):
F.clip(batch[:,0,:,:],low-123.680, high-123.680)
F.clip(batch[:,1,:,:],low-116.779, high-116.779)
F.clip(batch[:,2,:,:],low-103.939, high-103.939) | module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list subscript identifier slice integer slice slice binary_operator identifier float binary_operator identifier float expression_statement call attribute identifier identifier argument_list subscript identifier slice integer slice slice binary_operator identifier float binary_operator identifier float expression_statement call attribute identifier identifier argument_list subscript identifier slice integer slice slice binary_operator identifier float binary_operator identifier float | Not necessary in practice |
def to_csv(self, fileobj=sys.stdout):
openclose = is_string(fileobj)
if openclose:
fileobj = open(fileobj, "w")
for idx, section in enumerate(self.sections):
fileobj.write(section.to_csvline(with_header=(idx == 0)))
fileobj.flush()
if openclose:
fileobj.close() | module function_definition identifier parameters identifier default_parameter identifier attribute identifier identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement identifier block expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end for_statement pattern_list identifier identifier call identifier argument_list attribute identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list keyword_argument identifier parenthesized_expression comparison_operator identifier integer expression_statement call attribute identifier identifier argument_list if_statement identifier block expression_statement call attribute identifier identifier argument_list | Write data on file fileobj using CSV format. |
def GetConfigPolicy(self, request, context):
try:
policy = self.plugin.get_config_policy()
return policy._pb
except Exception as err:
msg = "message: {}\n\nstack trace: {}".format(
err.message, traceback.format_exc())
return GetConfigPolicyReply(error=msg) | module function_definition identifier parameters identifier identifier identifier block try_statement block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list return_statement attribute identifier identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement assignment identifier call attribute string string_start string_content escape_sequence escape_sequence string_end identifier argument_list attribute identifier identifier call attribute identifier identifier argument_list return_statement call identifier argument_list keyword_argument identifier identifier | Dispatches the request to the plugins get_config_policy method |
def preproc_directive(self) -> bool:
self._stream.save_context()
if self.read_until("\n", '\\'):
return self._stream.validate_context()
return self._stream.restore_context() | module function_definition identifier parameters identifier type identifier block expression_statement call attribute attribute identifier identifier identifier argument_list if_statement call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end string string_start string_content escape_sequence string_end block return_statement call attribute attribute identifier identifier identifier argument_list return_statement call attribute attribute identifier identifier identifier argument_list | Consume a preproc directive. |
def map(self, width, height):
template = ti.load(os.path.join(script_dir, 'assets', 'template.tmx'))['map0']
template.set_view(0, 0, width*template.tw, height*template.th)
border_x = template.cells[width]
for y in xrange(0,height+1):
border_x[y].tile = template.cells[0][0].tile
for x in xrange(0,width):
template.cells[x][height].tile = template.cells[0][0].tile
self.recursive_division(template.cells, 3, width, height, 0, 0)
return template | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier subscript call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end expression_statement call attribute identifier identifier argument_list integer integer binary_operator identifier attribute identifier identifier binary_operator identifier attribute identifier identifier expression_statement assignment identifier subscript attribute identifier identifier identifier for_statement identifier call identifier argument_list integer binary_operator identifier integer block expression_statement assignment attribute subscript identifier identifier identifier attribute subscript subscript attribute identifier identifier integer integer identifier for_statement identifier call identifier argument_list integer identifier block expression_statement assignment attribute subscript subscript attribute identifier identifier identifier identifier identifier attribute subscript subscript attribute identifier identifier integer integer identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier integer identifier identifier integer integer return_statement identifier | Creates and returns a new randomly generated map |
def dateadd(value: fields.DateTime(),
addend: fields.Int(validate=Range(min=1)),
unit: fields.Str(validate=OneOf(['minutes', 'days']))='days'):
value = value or dt.datetime.utcnow()
if unit == 'minutes':
delta = dt.timedelta(minutes=addend)
else:
delta = dt.timedelta(days=addend)
result = value + delta
return {'result': result} | module function_definition identifier parameters typed_parameter identifier type call attribute identifier identifier argument_list typed_parameter identifier type call attribute identifier identifier argument_list keyword_argument identifier call identifier argument_list keyword_argument identifier integer typed_default_parameter identifier type call attribute identifier identifier argument_list keyword_argument identifier 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 block expression_statement assignment identifier boolean_operator identifier call attribute attribute identifier identifier identifier argument_list if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier expression_statement assignment identifier binary_operator identifier identifier return_statement dictionary pair string string_start string_content string_end identifier | Add a value to a date. |
def _update_or_init_po_files(target, source, env):
import SCons.Action
from SCons.Tool.GettextCommon import _init_po_files
for tgt in target:
if tgt.rexists():
action = SCons.Action.Action('$MSGMERGECOM', '$MSGMERGECOMSTR')
else:
action = _init_po_files
status = action([tgt], source, env)
if status : return status
return 0 | module function_definition identifier parameters identifier identifier identifier block import_statement dotted_name identifier identifier import_from_statement dotted_name identifier identifier identifier dotted_name identifier for_statement identifier identifier block if_statement call attribute identifier identifier argument_list block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end else_clause block expression_statement assignment identifier identifier expression_statement assignment identifier call identifier argument_list list identifier identifier identifier if_statement identifier block return_statement identifier return_statement integer | Action function for `POUpdate` builder |
def folderitems(self):
items = super(AnalysisRequestAnalysesView, self).folderitems()
self.categories.sort()
return items | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute call identifier argument_list identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list return_statement identifier | XXX refactor if possible to non-classic mode |
def assemble_english():
if request.method == 'OPTIONS':
return {}
response = request.body.read().decode('utf-8')
body = json.loads(response)
stmts_json = body.get('statements')
stmts = stmts_from_json(stmts_json)
sentences = {}
for st in stmts:
enga = EnglishAssembler()
enga.add_statements([st])
model_str = enga.make_model()
sentences[st.uuid] = model_str
res = {'sentences': sentences}
return res | module function_definition identifier parameters block if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block return_statement dictionary expression_statement assignment identifier call attribute call attribute attribute identifier identifier identifier argument_list 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 call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier dictionary for_statement identifier identifier block expression_statement assignment identifier call identifier argument_list expression_statement call attribute identifier identifier argument_list list identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment subscript identifier attribute identifier identifier identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier return_statement identifier | Assemble each statement into |
def visit_Variable(self, node):
var_name = node.identifier.name
var_symbol = self.table[var_name]
if var_symbol is None:
raise SementicError(f"Variable `{var_name}` is not declared.") | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier subscript attribute identifier identifier identifier if_statement comparison_operator identifier none block raise_statement call identifier argument_list string string_start string_content interpolation identifier string_content string_end | Visitor for `Variable` AST node. |
async def _set_whitelist(self):
page = self.settings()
if 'whitelist' in page:
await self._send_to_messenger_profile(page, {
'whitelisted_domains': page['whitelist'],
})
logger.info('Whitelisted %s for page %s',
page['whitelist'],
page['page_id']) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator string string_start string_content string_end identifier block expression_statement await call attribute identifier identifier argument_list identifier dictionary pair string string_start string_content string_end subscript identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end | Whitelist domains for the messenger extensions |
def submit_tag_batch(self, batch):
url = '%s/api/v5/batch/tags' % self.base_url
self._submit_batch(url, batch) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier identifier | Submit a tag batch |
def _elements(cls):
if not cls.__is_selector():
raise Exception("Invalid selector[%s]." %cls.__control["by"])
driver = Web.driver
try:
elements = WebDriverWait(driver, cls.__control["timeout"]).until(lambda driver: getattr(driver,"find_elements")(cls.__control["by"], cls.__control["value"]))
except:
raise Exception("Timeout at %d seconds.Element(%s) not found." %(cls.__control["timeout"],cls.__control["by"]))
return elements | module function_definition identifier parameters identifier block if_statement not_operator call attribute identifier identifier argument_list block raise_statement call identifier argument_list binary_operator string string_start string_content string_end subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier attribute identifier identifier try_statement block expression_statement assignment identifier call attribute call identifier argument_list identifier subscript attribute identifier identifier string string_start string_content string_end identifier argument_list lambda lambda_parameters identifier call call identifier argument_list identifier string string_start string_content string_end argument_list subscript attribute identifier identifier string string_start string_content string_end subscript attribute identifier identifier string string_start string_content string_end except_clause block raise_statement call identifier argument_list binary_operator string string_start string_content string_end tuple subscript attribute identifier identifier string string_start string_content string_end subscript attribute identifier identifier string string_start string_content string_end return_statement identifier | find the elements with controls |
def _roots_to_targets(self, build_graph, target_roots):
with self._run_tracker.new_workunit(name='parse', labels=[WorkUnitLabel.SETUP]):
return [
build_graph.get_target(address)
for address
in build_graph.inject_roots_closure(target_roots, self._fail_fast)
] | module function_definition identifier parameters identifier identifier identifier block with_statement with_clause with_item call attribute attribute identifier identifier identifier argument_list keyword_argument identifier string string_start string_content string_end keyword_argument identifier list attribute identifier identifier block return_statement list_comprehension call attribute identifier identifier argument_list identifier for_in_clause identifier call attribute identifier identifier argument_list identifier attribute identifier identifier | Populate the BuildGraph and target list from a set of input TargetRoots. |
def create_parameterized_CAG(input, output, filename="CAG_with_indicators_and_values.pdf"):
with open(input, "rb") as f:
G = pickle.load(f)
G.parameterize(year=2017, month=4)
G.get_timeseries_values_for_indicators()
with open(output, "wb") as f:
pickle.dump(G, f) | module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_content string_end 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 argument_list identifier expression_statement call attribute identifier identifier argument_list keyword_argument identifier integer keyword_argument identifier integer expression_statement call attribute identifier identifier argument_list with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier identifier | Create a CAG with mapped and parameterized indicators |
def class_name_for_annotation_type(annotation_type, ns=None):
assert isinstance(annotation_type, AnnotationType)
name = fmt_class(annotation_type.name)
if ns:
return prefix_with_ns_if_necessary(name, annotation_type.namespace, ns)
return name | module function_definition identifier parameters identifier default_parameter identifier none block assert_statement call identifier argument_list identifier identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier if_statement identifier block return_statement call identifier argument_list identifier attribute identifier identifier identifier return_statement identifier | Same as class_name_for_data_type, but works with annotation types. |
def delete_video(video_id, cascade=False, delete_shares=False,
_connection=None):
c = _connection
if not c:
c = connection.APIConnection()
c.post('delete_video', video_id=video_id, cascade=cascade,
delete_shares=delete_shares) | module function_definition identifier parameters identifier default_parameter identifier false default_parameter identifier false default_parameter identifier none block expression_statement assignment identifier identifier if_statement not_operator identifier block 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 keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier | Delete the video represented by the ``video_id`` parameter. |
def add_parameters(parser):
group = parser.add_argument_group('Evaluation arguments')
group.add_argument('--eval-batch-size', type=int, default=1024)
group.add_argument(
'--similarity-datasets', type=str,
default=nlp.data.word_embedding_evaluation.word_similarity_datasets,
nargs='*',
help='Word similarity datasets to use for intrinsic evaluation.')
group.add_argument(
'--similarity-functions', type=str,
default=nlp.embedding.evaluation.list_evaluation_functions(
'similarity'), nargs='+',
help='Word similarity functions to use for intrinsic evaluation.')
group.add_argument(
'--analogy-datasets', type=str, default=['GoogleAnalogyTestSet'],
nargs='*',
help='Word similarity datasets to use for intrinsic evaluation.')
group.add_argument(
'--analogy-functions', type=str,
default=nlp.embedding.evaluation.list_evaluation_functions('analogy'),
nargs='+',
help='Word analogy functions to use for intrinsic evaluation. ')
group.add_argument(
'--analogy-dont-exclude-question-words', action='store_true',
help=('Exclude input words from valid output analogies.'
'The performance of word embeddings on the analogy task '
'is around 0% accuracy if input words are not excluded.')) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier integer expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier attribute attribute attribute identifier identifier identifier identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier list string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier parenthesized_expression concatenated_string string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end | Add evaluation specific parameters to parser. |
def _get_taxon(taxon):
if not taxon:
return None
sep = taxon.find(':')
taxid = taxon[sep + 1:]
assert taxid.isdigit(), "UNEXPECTED TAXON({T})".format(T=taxid)
return int(taxid) | module function_definition identifier parameters identifier block if_statement not_operator identifier block return_statement none expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier subscript identifier slice binary_operator identifier integer assert_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier identifier return_statement call identifier argument_list identifier | Return Interacting taxon ID | optional | 0 or 1 | gaf column 13. |
def parse_sig(sig):
label, sig = sig
assert label == b'sig-val'
algo_name = sig[0]
parser = {b'rsa': _parse_rsa_sig,
b'ecdsa': _parse_ecdsa_sig,
b'eddsa': _parse_eddsa_sig,
b'dsa': _parse_dsa_sig}[algo_name]
return parser(args=sig[1:]) | module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier identifier assert_statement comparison_operator identifier string string_start string_content string_end expression_statement assignment identifier subscript identifier integer expression_statement assignment identifier subscript dictionary 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 identifier pair string string_start string_content string_end identifier identifier return_statement call identifier argument_list keyword_argument identifier subscript identifier slice integer | Parse signature integer values from s-expr. |
def stashed(func):
@functools.wraps(func)
def _wrapper(*args, **kwargs):
if CTX.stash and not CTX.repo.stashed:
CTX.repo.stash(func.__name__)
try:
func(*args, **kwargs)
finally:
CTX.repo.unstash()
else:
func(*args, **kwargs)
return _wrapper | module function_definition identifier parameters identifier block decorated_definition decorator call attribute identifier identifier argument_list identifier function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block if_statement boolean_operator attribute identifier identifier not_operator attribute attribute identifier identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier try_statement block expression_statement call identifier argument_list list_splat identifier dictionary_splat identifier finally_clause block expression_statement call attribute attribute identifier identifier identifier argument_list else_clause block expression_statement call identifier argument_list list_splat identifier dictionary_splat identifier return_statement identifier | Simple decorator to stash changed files between a destructive repo operation |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.