code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def _RemoveRegistryKeys(self, metadata_value_pairs):
filtered_pairs = []
for metadata, stat_entry in metadata_value_pairs:
if stat_entry.pathspec.pathtype != rdf_paths.PathSpec.PathType.REGISTRY:
filtered_pairs.append((metadata, stat_entry))
return filtered_pairs | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list for_statement pattern_list identifier identifier identifier block if_statement comparison_operator attribute attribute identifier identifier identifier attribute attribute attribute identifier identifier identifier identifier block expression_statement call attribute identifier identifier argument_list tuple identifier identifier return_statement identifier | Filter out registry keys to operate on files. |
def rgba(self, val):
rgba = _user_to_rgba(val, expand=False)
if self._rgba is None:
self._rgba = rgba
else:
self._rgba[:, :rgba.shape[1]] = rgba | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier false if_statement comparison_operator attribute identifier identifier none block expression_statement assignment attribute identifier identifier identifier else_clause block expression_statement assignment subscript attribute identifier identifier slice slice subscript attribute identifier identifier integer identifier | Set the color using an Nx4 array of RGBA floats |
def main(reactor):
control_ep = UNIXClientEndpoint(reactor, '/var/run/tor/control')
tor = yield txtorcon.connect(reactor, control_ep)
state = yield tor.create_state()
print("Closing all circuits:")
for circuit in list(state.circuits.values()):
path = '->'.join(map(lambda r: r.id_hex, circuit.path))
print("Circuit {} through {}".format(circuit.id, path))
for stream in circuit.streams:
print(" Stream {} to {}".format(stream.id, stream.target_host))
yield stream.close()
print(" closed")
yield circuit.close()
print("closed")
yield tor.quit() | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end expression_statement assignment identifier yield call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier yield call attribute identifier identifier argument_list expression_statement call identifier argument_list string string_start string_content string_end for_statement identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list call identifier argument_list lambda lambda_parameters identifier attribute identifier identifier attribute identifier identifier expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier identifier for_statement identifier attribute identifier identifier block expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement yield call attribute identifier identifier argument_list expression_statement call identifier argument_list string string_start string_content string_end expression_statement yield call attribute identifier identifier argument_list expression_statement call identifier argument_list string string_start string_content string_end expression_statement yield call attribute identifier identifier argument_list | Close all open streams and circuits in the Tor we connect to |
def new_expiry(days=DEFAULT_PASTE_LIFETIME_DAYS):
now = delorean.Delorean()
return now + datetime.timedelta(days=days) | module function_definition identifier parameters default_parameter identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list return_statement binary_operator identifier call attribute identifier identifier argument_list keyword_argument identifier identifier | Return an expiration `days` in the future |
def path_list(self, sep=os.pathsep):
from pathlib import Path
return [ Path(pathstr) for pathstr in self.split(sep) ] | module function_definition identifier parameters identifier default_parameter identifier attribute identifier identifier block import_from_statement dotted_name identifier dotted_name identifier return_statement list_comprehension call identifier argument_list identifier for_in_clause identifier call attribute identifier identifier argument_list identifier | Return list of Path objects. |
def delete_keyring(service):
keyring = _keyring_path(service)
if not os.path.exists(keyring):
log('Keyring does not exist at %s' % keyring, level=WARNING)
return
os.remove(keyring)
log('Deleted ring at %s.' % keyring, level=INFO) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end identifier keyword_argument identifier identifier return_statement expression_statement call attribute identifier identifier argument_list identifier expression_statement call identifier argument_list binary_operator string string_start string_content string_end identifier keyword_argument identifier identifier | Delete an existing Ceph keyring. |
def load_config(config_file_override=False):
supernova_config = get_config_file(config_file_override)
supernova_config_dir = get_config_directory(config_file_override)
if not supernova_config and not supernova_config_dir:
raise Exception("Couldn't find a valid configuration file to parse")
nova_creds = ConfigObj()
if supernova_config:
try:
nova_creds.merge(ConfigObj(supernova_config))
except:
raise("There's an error in your configuration file")
if supernova_config_dir:
for dir_file in os.listdir(supernova_config_dir):
full_path = ''.join((supernova_config_dir, dir_file))
try:
nova_creds.merge(ConfigObj(full_path))
except:
msg = "Skipping '%s', Parsing Error.".format(full_path)
print(msg)
create_dynamic_configs(nova_creds)
return nova_creds | module function_definition identifier parameters default_parameter identifier false block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier if_statement boolean_operator not_operator identifier 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 if_statement identifier block try_statement block expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier except_clause block raise_statement parenthesized_expression string string_start string_content string_end if_statement identifier block for_statement identifier call attribute identifier identifier argument_list identifier block expression_statement assignment identifier call attribute string string_start string_end identifier argument_list tuple identifier identifier try_statement block expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier except_clause block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier expression_statement call identifier argument_list identifier expression_statement call identifier argument_list identifier return_statement identifier | Pulls the supernova configuration file and reads it |
def items(self):
content_type = ContentType.objects.get_for_model(Entry)
return comments.get_model().objects.filter(
content_type=content_type, is_public=True).order_by(
'-submit_date')[:self.limit] | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier return_statement subscript call attribute call attribute attribute call attribute identifier identifier argument_list identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier true identifier argument_list string string_start string_content string_end slice attribute identifier identifier | Items are the discussions on the entries. |
def check_predefined_conditions():
try:
node_info = current_k8s_corev1_api_client.list_node()
for node in node_info.items:
for condition in node.status.conditions:
if not condition.status:
return False
except ApiException as e:
log.error('Something went wrong while getting node information.')
log.error(e)
return False
return True | module function_definition identifier parameters block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list for_statement identifier attribute identifier identifier block for_statement identifier attribute attribute identifier identifier identifier block if_statement not_operator attribute identifier identifier block return_statement false except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier return_statement false return_statement true | Check k8s predefined conditions for the nodes. |
def job(request):
job_id = request.GET.get("job_id")
recent_jobs = JobRecord.objects.order_by("-start_time")[0:100]
recent_trials = TrialRecord.objects \
.filter(job_id=job_id) \
.order_by("-start_time")
trial_records = []
for recent_trial in recent_trials:
trial_records.append(get_trial_info(recent_trial))
current_job = JobRecord.objects \
.filter(job_id=job_id) \
.order_by("-start_time")[0]
if len(trial_records) > 0:
param_keys = trial_records[0]["params"].keys()
else:
param_keys = []
metric_keys = ["episode_reward", "accuracy", "loss"]
context = {
"current_job": get_job_info(current_job),
"recent_jobs": recent_jobs,
"recent_trials": trial_records,
"param_keys": param_keys,
"param_num": len(param_keys),
"metric_keys": metric_keys,
"metric_num": len(metric_keys)
}
return render(request, "job.html", context) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier subscript call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end slice integer integer expression_statement assignment identifier call attribute call attribute attribute identifier identifier line_continuation identifier argument_list keyword_argument identifier identifier line_continuation identifier argument_list string string_start string_content string_end expression_statement assignment identifier list for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier expression_statement assignment identifier subscript call attribute call attribute attribute identifier identifier line_continuation identifier argument_list keyword_argument identifier identifier line_continuation identifier argument_list string string_start string_content string_end integer if_statement comparison_operator call identifier argument_list identifier integer block expression_statement assignment identifier call attribute subscript subscript identifier integer string string_start string_content string_end identifier argument_list else_clause block expression_statement assignment identifier list expression_statement assignment identifier list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier dictionary pair string string_start string_content string_end call identifier argument_list 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 pair string string_start string_content string_end call identifier argument_list identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end call identifier argument_list identifier return_statement call identifier argument_list identifier string string_start string_content string_end identifier | View for a single job. |
def commit_fw_db(self):
fw_dict = self.get_fw_dict()
self.update_fw_db(fw_dict.get('fw_id'), fw_dict) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end identifier | Calls routine to update the FW DB. |
def compute_near_isotropic_downsampling_scales(size,
voxel_size,
dimensions_to_downsample,
max_scales=DEFAULT_MAX_DOWNSAMPLING_SCALES,
max_downsampling=DEFAULT_MAX_DOWNSAMPLING,
max_downsampled_size=DEFAULT_MAX_DOWNSAMPLED_SIZE):
num_dims = len(voxel_size)
cur_scale = np.ones((num_dims, ), dtype=int)
scales = [tuple(cur_scale)]
while (len(scales) < max_scales and (np.prod(cur_scale) < max_downsampling) and
(size / cur_scale).max() > max_downsampled_size):
cur_voxel_size = cur_scale * voxel_size
smallest_cur_voxel_size_dim = dimensions_to_downsample[np.argmin(cur_voxel_size[
dimensions_to_downsample])]
cur_scale[smallest_cur_voxel_size_dim] *= 2
target_voxel_size = cur_voxel_size[smallest_cur_voxel_size_dim] * 2
for d in dimensions_to_downsample:
if d == smallest_cur_voxel_size_dim:
continue
d_voxel_size = cur_voxel_size[d]
if abs(d_voxel_size - target_voxel_size) > abs(d_voxel_size * 2 - target_voxel_size):
cur_scale[d] *= 2
scales.append(tuple(cur_scale))
return scales | module function_definition identifier parameters identifier identifier identifier default_parameter identifier identifier default_parameter identifier identifier default_parameter identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list tuple identifier keyword_argument identifier identifier expression_statement assignment identifier list call identifier argument_list identifier while_statement parenthesized_expression boolean_operator boolean_operator comparison_operator call identifier argument_list identifier identifier parenthesized_expression comparison_operator call attribute identifier identifier argument_list identifier identifier comparison_operator call attribute parenthesized_expression binary_operator identifier identifier identifier argument_list identifier block expression_statement assignment identifier binary_operator identifier identifier expression_statement assignment identifier subscript identifier call attribute identifier identifier argument_list subscript identifier identifier expression_statement augmented_assignment subscript identifier identifier integer expression_statement assignment identifier binary_operator subscript identifier identifier integer for_statement identifier identifier block if_statement comparison_operator identifier identifier block continue_statement expression_statement assignment identifier subscript identifier identifier if_statement comparison_operator call identifier argument_list binary_operator identifier identifier call identifier argument_list binary_operator binary_operator identifier integer identifier block expression_statement augmented_assignment subscript identifier identifier integer expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier return_statement identifier | Compute a list of successive downsampling factors. |
def render_title_tag(context, is_og=False):
request = context['request']
content = ''
if context.get('object'):
try:
content = context['object'].get_meta_title()
except AttributeError:
pass
elif context.get('meta_tagger'):
content = context['meta_tagger'].get('title')
if not content:
try:
content = request.current_page.get_page_title()
if not content:
content = request.current_page.get_title()
except (AttributeError, NoReverseMatch):
pass
if not is_og:
return content
else:
return mark_safe('<meta property="og:title" content="{content}">'.format(content=content)) | module function_definition identifier parameters identifier default_parameter identifier false block expression_statement assignment identifier subscript identifier string string_start string_content string_end 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 try_statement block expression_statement assignment identifier call attribute subscript identifier string string_start string_content string_end identifier argument_list except_clause identifier block pass_statement elif_clause call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier call attribute subscript identifier string string_start string_content string_end identifier argument_list string string_start string_content string_end if_statement not_operator identifier block try_statement block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list if_statement not_operator identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list except_clause tuple identifier identifier block pass_statement if_statement not_operator identifier block return_statement identifier else_clause block return_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier identifier | Returns the title as string or a complete open graph meta tag. |
def string(self):
for term in self._terms:
if isinstance(term, String):
return str(term)
return None | module function_definition identifier parameters identifier block for_statement identifier attribute identifier identifier block if_statement call identifier argument_list identifier identifier block return_statement call identifier argument_list identifier return_statement none | Return the first string term in the conjunction, or `None`. |
def show_geonode_uploader(self):
from safe.gui.tools.geonode_uploader import GeonodeUploaderDialog
dialog = GeonodeUploaderDialog(self.iface.mainWindow())
dialog.show() | module function_definition identifier parameters identifier block import_from_statement dotted_name identifier identifier identifier identifier dotted_name identifier expression_statement assignment identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list | Show the Geonode uploader dialog. |
def save_report_to_html(self):
html = self.page().mainFrame().toHtml()
if self.report_path is not None:
html_to_file(html, self.report_path)
else:
msg = self.tr('report_path is not set')
raise InvalidParameterError(msg) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute call attribute call attribute identifier identifier argument_list identifier argument_list identifier argument_list if_statement comparison_operator attribute identifier identifier none block expression_statement call identifier argument_list identifier attribute identifier identifier else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end raise_statement call identifier argument_list identifier | Save report in the dock to html. |
def add_package(package_name, package_path='templates', encoding='utf-8'):
if not _has_jinja:
raise RuntimeError(_except_text)
_jload.add_loader(PackageLoader(package_name, package_path, encoding)) | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end default_parameter identifier string string_start string_content string_end block if_statement not_operator identifier block raise_statement call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier identifier identifier | Adds the given package to the template search routine |
def _start_vnc(self):
self._display = self._get_free_display_port()
if shutil.which("Xvfb") is None or shutil.which("x11vnc") is None:
raise DockerError("Please install Xvfb and x11vnc before using the VNC support")
self._xvfb_process = yield from asyncio.create_subprocess_exec("Xvfb", "-nolisten", "tcp", ":{}".format(self._display), "-screen", "0", self._console_resolution + "x16")
self._x11vnc_process = yield from asyncio.create_subprocess_exec("x11vnc", "-forever", "-nopw", "-shared", "-geometry", self._console_resolution, "-display", "WAIT:{}".format(self._display), "-rfbport", str(self.console), "-rfbportv6", str(self.console), "-noncache", "-listen", self._manager.port_manager.console_host)
x11_socket = os.path.join("/tmp/.X11-unix/", "X{}".format(self._display))
yield from wait_for_file_creation(x11_socket) | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list if_statement boolean_operator comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end none comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end none block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment attribute identifier identifier yield call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier string string_start string_content string_end string string_start string_content string_end binary_operator attribute identifier identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier yield call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end attribute identifier identifier string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier string string_start string_content string_end call identifier argument_list attribute identifier identifier string string_start string_content string_end call identifier argument_list attribute identifier identifier string string_start string_content string_end string string_start string_content string_end attribute attribute attribute identifier identifier identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier expression_statement yield call identifier argument_list identifier | Start a VNC server for this container |
def solve_lp(clusters, quota, work_dir="work", Nmax=0,
self_match=False, solver="SCIP", verbose=False):
qb, qa = quota
nodes, constraints_x, constraints_y = get_constraints(
clusters, (qa, qb), Nmax=Nmax)
if self_match:
constraints_x = constraints_y = constraints_x | constraints_y
lp_data = format_lp(nodes, constraints_x, qa, constraints_y, qb)
if solver == "SCIP":
filtered_list = SCIPSolver(lp_data, work_dir, verbose=verbose).results
if not filtered_list:
print("SCIP fails... trying GLPK", file=sys.stderr)
filtered_list = GLPKSolver(
lp_data, work_dir, verbose=verbose).results
elif solver == "GLPK":
filtered_list = GLPKSolver(lp_data, work_dir, verbose=verbose).results
if not filtered_list:
print("GLPK fails... trying SCIP", file=sys.stderr)
filtered_list = SCIPSolver(
lp_data, work_dir, verbose=verbose).results
return filtered_list | module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_content string_end default_parameter identifier integer default_parameter identifier false default_parameter identifier string string_start string_content string_end default_parameter identifier false block expression_statement assignment pattern_list identifier identifier identifier expression_statement assignment pattern_list identifier identifier identifier call identifier argument_list identifier tuple identifier identifier keyword_argument identifier identifier if_statement identifier block expression_statement assignment identifier assignment identifier binary_operator identifier identifier expression_statement assignment identifier call identifier argument_list identifier identifier identifier identifier identifier if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier attribute call identifier argument_list identifier identifier keyword_argument identifier identifier identifier if_statement not_operator identifier block expression_statement call identifier argument_list string string_start string_content string_end keyword_argument identifier attribute identifier identifier expression_statement assignment identifier attribute call identifier argument_list identifier identifier keyword_argument identifier identifier identifier elif_clause comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier attribute call identifier argument_list identifier identifier keyword_argument identifier identifier identifier if_statement not_operator identifier block expression_statement call identifier argument_list string string_start string_content string_end keyword_argument identifier attribute identifier identifier expression_statement assignment identifier attribute call identifier argument_list identifier identifier keyword_argument identifier identifier identifier return_statement identifier | Solve the formatted LP instance |
def _make_bright_pixel_mask(intensity_mean, mask_factor=5.0):
mask = np.zeros((intensity_mean.data.shape), bool)
nebins = len(intensity_mean.data)
sum_intensity = intensity_mean.data.sum(0)
mean_intensity = sum_intensity.mean()
for i in range(nebins):
mask[i, 0:] = sum_intensity > (mask_factor * mean_intensity)
return HpxMap(mask, intensity_mean.hpx) | module function_definition identifier parameters identifier default_parameter identifier float block expression_statement assignment identifier call attribute identifier identifier argument_list parenthesized_expression attribute attribute identifier identifier identifier identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list integer expression_statement assignment identifier call attribute identifier identifier argument_list for_statement identifier call identifier argument_list identifier block expression_statement assignment subscript identifier identifier slice integer comparison_operator identifier parenthesized_expression binary_operator identifier identifier return_statement call identifier argument_list identifier attribute identifier identifier | Make of mask of all the brightest pixels |
def ResolveHostnameToIP(host, port):
ip_addrs = socket.getaddrinfo(host, port, socket.AF_UNSPEC, 0,
socket.IPPROTO_TCP)
result = ip_addrs[0][4][0]
if compatibility.PY2:
result = result.decode("ascii")
return result | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier attribute identifier identifier integer attribute identifier identifier expression_statement assignment identifier subscript subscript subscript identifier integer integer integer if_statement attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end return_statement identifier | Resolves a hostname to an IP address. |
def _time_show(self):
if not self._time_visible:
self._time_visible = True
self._time_window = tk.Toplevel(self)
self._time_window.attributes("-topmost", True)
self._time_window.overrideredirect(True)
self._time_label = ttk.Label(self._time_window)
self._time_label.grid()
self._time_window.lift()
x, y = self.master.winfo_pointerxy()
geometry = "{0}x{1}+{2}+{3}".format(
self._time_label.winfo_width(),
self._time_label.winfo_height(),
x - 15,
self._canvas_ticks.winfo_rooty() - 10)
self._time_window.wm_geometry(geometry)
self._time_label.config(text=TimeLine.get_time_string(self.time, self._unit)) | module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block expression_statement assignment attribute identifier identifier true expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end true expression_statement call attribute attribute identifier identifier identifier argument_list true expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement assignment pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list binary_operator identifier integer binary_operator call attribute attribute identifier identifier identifier argument_list integer expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier | Show the time marker window |
def cancelAllPendingResults( self ):
jobs = self.pendingResults()
if len(jobs) > 0:
self._abortJobs(jobs)
self.notebook().cancelAllPendingResults() | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator call identifier argument_list identifier integer block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute call attribute identifier identifier argument_list identifier argument_list | Cancel all pending results. |
def mk_set_headers(self, data, columns):
columns = tuple(columns)
lens = []
for key in columns:
value_len = max(len(str(each.get(key, ''))) for each in data)
lens.append(max(value_len, len(self._get_name(key))))
fmt = self.mk_fmt(*lens)
return fmt | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier list for_statement identifier identifier block expression_statement assignment identifier call identifier generator_expression call identifier argument_list call identifier argument_list call attribute identifier identifier argument_list identifier string string_start string_end for_in_clause identifier identifier expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier call identifier argument_list call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list list_splat identifier return_statement identifier | figure out sizes and create header fmt |
def connectExec(connection, protocol, commandLine):
deferred = connectSession(connection, protocol)
@deferred.addCallback
def requestSubsystem(session):
return session.requestExec(commandLine)
return deferred | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier decorated_definition decorator attribute identifier identifier function_definition identifier parameters identifier block return_statement call attribute identifier identifier argument_list identifier return_statement identifier | Connect a Protocol to a ssh exec session |
def secure_password(length=20, use_random=True):
try:
length = int(length)
pw = ''
while len(pw) < length:
if HAS_RANDOM and use_random:
while True:
try:
char = salt.utils.stringutils.to_str(get_random_bytes(1))
break
except UnicodeDecodeError:
continue
pw += re.sub(
salt.utils.stringutils.to_str(r'\W'),
str(),
char
)
else:
pw += random.SystemRandom().choice(string.ascii_letters + string.digits)
return pw
except Exception as exc:
log.exception('Failed to generate secure passsword')
raise CommandExecutionError(six.text_type(exc)) | module function_definition identifier parameters default_parameter identifier integer default_parameter identifier true block try_statement block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier string string_start string_end while_statement comparison_operator call identifier argument_list identifier identifier block if_statement boolean_operator identifier identifier block while_statement true block try_statement block expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list call identifier argument_list integer break_statement except_clause identifier block continue_statement expression_statement augmented_assignment identifier call attribute identifier identifier argument_list call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end call identifier argument_list identifier else_clause block expression_statement augmented_assignment identifier call attribute call attribute identifier identifier argument_list identifier argument_list binary_operator attribute identifier identifier attribute identifier identifier return_statement identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end raise_statement call identifier argument_list call attribute identifier identifier argument_list identifier | Generate a secure password. |
def cleanup(self):
"Remove the directory containin the clone and virtual environment."
log.info('Removing temp dir %s', self._tempdir.name)
self._tempdir.cleanup() | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute attribute identifier identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list | Remove the directory containin the clone and virtual environment. |
def ok(self, *args, cb=None):
self.clear_widgets()
if cb:
cb()
self.idx += 1
self.advance_dialog() | module function_definition identifier parameters identifier list_splat_pattern identifier default_parameter identifier none block expression_statement call attribute identifier identifier argument_list if_statement identifier block expression_statement call identifier argument_list expression_statement augmented_assignment attribute identifier identifier integer expression_statement call attribute identifier identifier argument_list | Clear dialog widgets, call ``cb`` if provided, and advance the dialog queue |
def _serialize_date(value):
if not isinstance(value, date):
raise ValueError(u'The received object was not a date: '
u'{} {}'.format(type(value), value))
return value.isoformat() | module function_definition identifier parameters identifier block if_statement not_operator call identifier argument_list identifier identifier block raise_statement call identifier argument_list call attribute concatenated_string string string_start string_content string_end string string_start string_content string_end identifier argument_list call identifier argument_list identifier identifier return_statement call attribute identifier identifier argument_list | Serialize a Date object to its proper ISO-8601 representation. |
def publishToOther(self, roomId, name, data):
tmpList = self.getRoom(roomId)
userList = [x for x in tmpList if x is not self]
self.publishToRoom(roomId, name, data, userList) | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier list_comprehension identifier for_in_clause identifier identifier if_clause comparison_operator identifier identifier expression_statement call attribute identifier identifier argument_list identifier identifier identifier identifier | Publish to only other people than myself |
def log_likelihood(self):
ll = GP.log_likelihood(self)
jacobian = self.warping_function.fgrad_y(self.Y_untransformed)
return ll + np.log(jacobian).sum() | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier return_statement binary_operator identifier call attribute call attribute identifier identifier argument_list identifier identifier argument_list | Notice we add the jacobian of the warping function here. |
def wild_card_logs():
file_name = 'GLWC.TXT'
z = get_zip_file(wild_card_url)
data = pd.read_csv(z.open(file_name), header=None, sep=',', quotechar='"')
data.columns = gamelog_columns
return data | module function_definition identifier parameters block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier keyword_argument identifier none keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier identifier return_statement identifier | Pull Retrosheet Wild Card Game Logs |
def new_file(self, path: str, checksum: str=None, to_archive: bool=False,
tags: List[models.Tag]=None) -> models.File:
new_file = self.File(path=path, checksum=checksum, to_archive=to_archive, tags=tags)
return new_file | module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_default_parameter identifier type identifier none typed_default_parameter identifier type identifier false typed_default_parameter identifier type generic_type identifier type_parameter type attribute identifier identifier none type attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier return_statement identifier | Create a new file. |
def setup_environment():
try:
from gi.repository import GLib
user_data_folder = GLib.get_user_data_dir()
except ImportError:
user_data_folder = join(os.path.expanduser("~"), ".local", "share")
rafcon_root_path = dirname(realpath(rafcon.__file__))
user_library_folder = join(user_data_folder, "rafcon", "libraries")
if not os.environ.get('RAFCON_LIB_PATH', None):
if exists(user_library_folder):
os.environ['RAFCON_LIB_PATH'] = user_library_folder
else:
os.environ['RAFCON_LIB_PATH'] = join(dirname(dirname(rafcon_root_path)), 'share', 'libraries')
if sys.version_info >= (3,):
import builtins as builtins23
else:
import __builtin__ as builtins23
if "_" not in builtins23.__dict__:
builtins23.__dict__["_"] = lambda s: s | module function_definition identifier parameters block try_statement block import_from_statement dotted_name identifier identifier dotted_name identifier expression_statement assignment identifier call attribute identifier identifier argument_list except_clause identifier block expression_statement assignment identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call identifier argument_list call identifier argument_list attribute identifier identifier expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end string string_start string_content string_end if_statement not_operator call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end none block if_statement call identifier argument_list identifier block expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end identifier else_clause block expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end call identifier argument_list call identifier argument_list call identifier argument_list identifier string string_start string_content string_end string string_start string_content string_end if_statement comparison_operator attribute identifier identifier tuple integer block import_statement aliased_import dotted_name identifier identifier else_clause block import_statement aliased_import dotted_name identifier identifier if_statement comparison_operator string string_start string_content string_end attribute identifier identifier block expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end lambda lambda_parameters identifier identifier | Ensures that the environmental variable RAFCON_LIB_PATH is existent |
def _attach(cls, disk_id, vm_id, options=None):
options = options or {}
oper = cls.call('hosting.vm.disk_attach', vm_id, disk_id, options)
return oper | module function_definition identifier parameters identifier identifier identifier default_parameter identifier none block expression_statement assignment identifier boolean_operator identifier dictionary expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier identifier return_statement identifier | Attach a disk to a vm. |
def from_jsons(graph_json_str: str, check_version: bool = True) -> BELGraph:
graph_json_dict = json.loads(graph_json_str)
return from_json(graph_json_dict, check_version=check_version) | module function_definition identifier parameters typed_parameter identifier type identifier typed_default_parameter identifier type identifier true type identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement call identifier argument_list identifier keyword_argument identifier identifier | Read a BEL graph from a Node-Link JSON string. |
def _assert_valid_key(self, name):
if name not in self._measurements:
raise NotAMeasurementError('Not a measurement', name, self._measurements) | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end identifier attribute identifier identifier | Raises if name is not a valid measurement. |
def std(self, bias=False, *args, **kwargs):
nv.validate_window_func('std', args, kwargs)
return _zsqrt(self.var(bias=bias, **kwargs)) | module function_definition identifier parameters identifier default_parameter identifier false list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier return_statement call identifier argument_list call attribute identifier identifier argument_list keyword_argument identifier identifier dictionary_splat identifier | Exponential weighted moving stddev. |
def lookup_id_action(self, text, loc, var):
exshared.setpos(loc, text)
if DEBUG > 0:
print("EXP_VAR:",var)
if DEBUG == 2: self.symtab.display()
if DEBUG > 2: return
var_index = self.symtab.lookup_symbol(var.name, [SharedData.KINDS.GLOBAL_VAR, SharedData.KINDS.PARAMETER, SharedData.KINDS.LOCAL_VAR])
if var_index == None:
raise SemanticException("'%s' undefined" % var.name)
return var_index | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement call attribute identifier identifier argument_list identifier identifier if_statement comparison_operator identifier integer block expression_statement call identifier argument_list string string_start string_content string_end identifier if_statement comparison_operator identifier integer block expression_statement call attribute attribute identifier identifier identifier argument_list if_statement comparison_operator identifier integer block return_statement expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier list attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier if_statement comparison_operator identifier none block raise_statement call identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier return_statement identifier | Code executed after recognising an identificator in expression |
def upload_nginx_site_conf(site_name, template_name=None, context=None, enable=True):
template_name = template_name or [u'nginx/%s.conf' % site_name, u'nginx/site.conf']
site_available = u'/etc/nginx/sites-available/%s' % site_name
upload_template(template_name, site_available, context=context, use_sudo=True)
if enable:
enable_site(site_name) | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none default_parameter identifier true block expression_statement assignment identifier boolean_operator identifier list binary_operator string string_start string_content string_end identifier string string_start string_content string_end expression_statement assignment identifier binary_operator string string_start string_content string_end identifier expression_statement call identifier argument_list identifier identifier keyword_argument identifier identifier keyword_argument identifier true if_statement identifier block expression_statement call identifier argument_list identifier | Upload Nginx site configuration from a template. |
def _prepare_ogc_request_params(self):
self.ogc_request.image_format = MimeType.TIFF_d32f
if self.ogc_request.custom_url_params is None:
self.ogc_request.custom_url_params = {}
self.ogc_request.custom_url_params.update({
CustomUrlParam.SHOWLOGO: False,
CustomUrlParam.TRANSPARENT: True,
CustomUrlParam.EVALSCRIPT: S2_BANDS_EVALSCRIPT if self.all_bands else MODEL_EVALSCRIPT,
CustomUrlParam.ATMFILTER: 'NONE'
})
self.ogc_request.create_request(reset_wfs_iterator=False) | module function_definition identifier parameters identifier block expression_statement assignment attribute attribute identifier identifier identifier attribute identifier identifier if_statement comparison_operator attribute attribute identifier identifier identifier none block expression_statement assignment attribute attribute identifier identifier identifier dictionary expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list dictionary pair attribute identifier identifier false pair attribute identifier identifier true pair attribute identifier identifier conditional_expression identifier attribute identifier identifier identifier pair attribute identifier identifier string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier false | Method makes sure that correct parameters will be used for download of S-2 bands. |
def to_text_format(self):
return '\n'.join(itertools.chain(
(self.fetch_date.strftime('%Y%m%d%H%M%S'), ),
(rr.to_text() for rr in self.resource_records),
(),
)) | module function_definition identifier parameters identifier block return_statement call attribute string string_start string_content escape_sequence string_end identifier argument_list call attribute identifier identifier argument_list tuple call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end generator_expression call attribute identifier identifier argument_list for_in_clause identifier attribute identifier identifier tuple | Format as detached DNS information as text. |
def _POInitBuilder(env, **kw):
import SCons.Action
from SCons.Tool.GettextCommon import _init_po_files, _POFileBuilder
action = SCons.Action.Action(_init_po_files, None)
return _POFileBuilder(env, action=action, target_alias='$POCREATE_ALIAS') | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block import_statement dotted_name identifier identifier import_from_statement dotted_name identifier identifier identifier dotted_name identifier dotted_name identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier none return_statement call identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier string string_start string_content string_end | Create builder object for `POInit` builder. |
def run(files, temp_folder):
"Check flake8 errors in the code base."
try:
import flake8
except ImportError:
return NO_FLAKE_MSG
try:
from flake8.engine import get_style_guide
except ImportError:
from flake8.api.legacy import get_style_guide
py_files = filter_python_files(files)
if not py_files:
return
DEFAULT_CONFIG = join(temp_folder, get_config_file())
with change_folder(temp_folder):
flake8_style = get_style_guide(config_file=DEFAULT_CONFIG)
out, err = StringIO(), StringIO()
with redirected(out, err):
flake8_style.check_files(py_files)
return out.getvalue().strip() + err.getvalue().strip() | module function_definition identifier parameters identifier identifier block expression_statement string string_start string_content string_end try_statement block import_statement dotted_name identifier except_clause identifier block return_statement identifier try_statement block import_from_statement dotted_name identifier identifier dotted_name identifier except_clause identifier block import_from_statement dotted_name identifier identifier identifier dotted_name identifier expression_statement assignment identifier call identifier argument_list identifier if_statement not_operator identifier block return_statement expression_statement assignment identifier call identifier argument_list identifier call identifier argument_list with_statement with_clause with_item call identifier argument_list identifier block expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier expression_statement assignment pattern_list identifier identifier expression_list call identifier argument_list call identifier argument_list with_statement with_clause with_item call identifier argument_list identifier identifier block expression_statement call attribute identifier identifier argument_list identifier return_statement binary_operator call attribute call attribute identifier identifier argument_list identifier argument_list call attribute call attribute identifier identifier argument_list identifier argument_list | Check flake8 errors in the code base. |
def delete(self, event):
super(CeleryReceiver, self).delete(event)
AsyncResult(event.id).revoke(terminate=True) | module function_definition identifier parameters identifier identifier block expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list identifier expression_statement call attribute call identifier argument_list attribute identifier identifier identifier argument_list keyword_argument identifier true | Abort running task if it exists. |
def row_value(self, row):
irow = int(row)
i = self._get_key_index(irow)
if i == -1:
return 0.0
if i == len(self.keys) - 1:
return self.keys[-1].value
return TrackKey.interpolate(self.keys[i], self.keys[i + 1], row) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier unary_operator integer block return_statement float if_statement comparison_operator identifier binary_operator call identifier argument_list attribute identifier identifier integer block return_statement attribute subscript attribute identifier identifier unary_operator integer identifier return_statement call attribute identifier identifier argument_list subscript attribute identifier identifier identifier subscript attribute identifier identifier binary_operator identifier integer identifier | Get the tracks value at row |
def text_assert_any(self, anchors, byte=False):
found = False
for anchor in anchors:
if self.text_search(anchor, byte=byte):
found = True
break
if not found:
raise DataNotFound(u'Substrings not found: %s'
% ', '.join(anchors)) | module function_definition identifier parameters identifier identifier default_parameter identifier false block expression_statement assignment identifier false for_statement identifier identifier block if_statement call attribute identifier identifier argument_list identifier keyword_argument identifier identifier block expression_statement assignment identifier true break_statement if_statement not_operator identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list identifier | If no `anchors` were found then raise `DataNotFound` exception. |
def _prepare_document(self):
self._xml = ET.Element("Document")
self._xml.set("xmlns",
"urn:iso:std:iso:20022:tech:xsd:" + self.schema)
self._xml.set("xmlns:xsi",
"http://www.w3.org/2001/XMLSchema-instance")
ET.register_namespace("",
"urn:iso:std:iso:20022:tech:xsd:" + self.schema)
ET.register_namespace("xsi",
"http://www.w3.org/2001/XMLSchema-instance")
n = ET.Element(self.root_el)
self._xml.append(n) | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end binary_operator string string_start string_content string_end attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_end binary_operator string string_start string_content string_end attribute identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Build the main document node and set xml namespaces. |
def node_validate(node_dict, node_num, cmd_name):
req_lu = {"run": ["stopped", "Already Running"],
"stop": ["running", "Already Stopped"],
"connect": ["running", "Can't Connect, Node Not Running"],
"details": [node_dict[node_num].state, ""]}
tm = {True: ("Node {1}{2}{0} ({5}{3}{0} on {1}{4}{0})".
format(C_NORM, C_WARN, node_num,
node_dict[node_num].name,
node_dict[node_num].cloud_disp, C_TI)),
False: req_lu[cmd_name][1]}
node_valid = bool(req_lu[cmd_name][0] == node_dict[node_num].state)
node_info = tm[node_valid]
return node_valid, node_info | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end list string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end list string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end list string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end list attribute subscript identifier identifier identifier string string_start string_end expression_statement assignment identifier dictionary pair true parenthesized_expression call attribute string string_start string_content string_end identifier argument_list identifier identifier identifier attribute subscript identifier identifier identifier attribute subscript identifier identifier identifier identifier pair false subscript subscript identifier identifier integer expression_statement assignment identifier call identifier argument_list comparison_operator subscript subscript identifier identifier integer attribute subscript identifier identifier identifier expression_statement assignment identifier subscript identifier identifier return_statement expression_list identifier identifier | Validate that command can be performed on target node. |
def emitFragment(fw, fragID, libID, shredded_seq, clr=None, qvchar='l', fasta=False):
if fasta:
s = SeqRecord(shredded_seq, id=fragID, description="")
SeqIO.write([s], fw, "fasta")
return
seq = str(shredded_seq)
slen = len(seq)
qvs = qvchar * slen
if clr is None:
clr_beg, clr_end = 0, slen
else:
clr_beg, clr_end = clr
print(frgTemplate.format(fragID=fragID, libID=libID,
seq=seq, qvs=qvs, clr_beg=clr_beg, clr_end=clr_end), file=fw) | module function_definition identifier parameters identifier identifier identifier identifier default_parameter identifier none default_parameter identifier string string_start string_content string_end default_parameter identifier false block if_statement identifier block expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier string string_start string_end expression_statement call attribute identifier identifier argument_list list identifier identifier string string_start string_content string_end return_statement expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier binary_operator identifier identifier if_statement comparison_operator identifier none block expression_statement assignment pattern_list identifier identifier expression_list integer identifier else_clause block expression_statement assignment pattern_list identifier identifier identifier expression_statement call identifier argument_list call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier | Print out the shredded sequence. |
def _add_request_parameters(func):
async def decorated_func(*args, handle_ratelimit=None, max_tries=None, request_timeout=None, **kwargs):
return await func(*args, handle_ratelimit=handle_ratelimit, max_tries=max_tries,
request_timeout=request_timeout, **kwargs)
return decorated_func | module function_definition identifier parameters identifier block function_definition identifier parameters list_splat_pattern identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none dictionary_splat_pattern identifier block return_statement await call identifier argument_list list_splat identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier dictionary_splat identifier return_statement identifier | Adds the ratelimit and request timeout parameters to a function. |
def xy_positions(self):
if self._xy_positions is None or len(self._xy_positions) == 0:
xy_pos = []
for dom_id, pos in self.dom_positions.items():
if self.domid2floor(dom_id) == 1:
xy_pos.append(np.array([pos[0], pos[1]]))
self._xy_positions = np.array(xy_pos)
return self._xy_positions | module function_definition identifier parameters identifier block if_statement boolean_operator comparison_operator attribute identifier identifier none comparison_operator call identifier argument_list attribute identifier identifier integer block expression_statement assignment identifier list for_statement pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list block if_statement comparison_operator call attribute identifier identifier argument_list identifier integer block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list list subscript identifier integer subscript identifier integer expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier return_statement attribute identifier identifier | XY positions of the DUs, given by the DOMs on floor 1. |
def refund(self):
from longclaw.utils import GATEWAY
now = datetime.strftime(datetime.now(), "%b %d %Y %H:%M:%S")
if GATEWAY.issue_refund(self.transaction_id, self.total):
self.status = self.REFUNDED
self.status_note = "Refunded on {}".format(now)
else:
self.status_note = "Refund failed on {}".format(now)
self.save() | module function_definition identifier parameters identifier block import_from_statement dotted_name identifier identifier dotted_name identifier expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end if_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier block expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier call attribute string string_start string_content string_end identifier argument_list identifier else_clause block expression_statement assignment attribute identifier identifier call attribute string string_start string_content string_end identifier argument_list identifier expression_statement call attribute identifier identifier argument_list | Issue a full refund for this order |
def spawn_daemon(fork=None, pgrpfile=None, outfile='out.txt'):
'causes run to be executed in a newly spawned daemon process'
global LAST_PGRP_PATH
fork = fork or os.fork
open(outfile, 'a').close()
if pgrpfile and os.path.exists(pgrpfile):
try:
cur_pid = int(open(pgrpfile).read().rstrip("\n"))
os.killpg(cur_pid, 0)
raise Exception("arbiter still running with pid:" + str(cur_pid))
except (OSError, ValueError):
pass
if fork():
return True
else:
os.setsid()
if fork():
os._exit(0)
LAST_PGRP_PATH = pgrpfile
if pgrpfile:
with open(pgrpfile, 'w') as f:
f.write(str(os.getpgrp()) + "\n")
logging.root.addHandler(SysLogHandler())
rotating_out = RotatingStdoutFile(outfile)
rotating_out.start()
return False | module function_definition identifier parameters default_parameter identifier none default_parameter identifier none default_parameter identifier string string_start string_content string_end block expression_statement string string_start string_content string_end global_statement identifier expression_statement assignment identifier boolean_operator identifier attribute identifier identifier expression_statement call attribute call identifier argument_list identifier string string_start string_content string_end identifier argument_list if_statement boolean_operator identifier call attribute attribute identifier identifier identifier argument_list identifier block try_statement block expression_statement assignment identifier call identifier argument_list call attribute call attribute call identifier argument_list identifier identifier argument_list identifier argument_list string string_start string_content escape_sequence string_end expression_statement call attribute identifier identifier argument_list identifier integer raise_statement call identifier argument_list binary_operator string string_start string_content string_end call identifier argument_list identifier except_clause tuple identifier identifier block pass_statement if_statement call identifier argument_list block return_statement true else_clause block expression_statement call attribute identifier identifier argument_list if_statement call identifier argument_list block expression_statement call attribute identifier identifier argument_list integer expression_statement assignment identifier identifier if_statement identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list binary_operator call identifier argument_list call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end expression_statement call attribute attribute identifier identifier identifier argument_list call identifier argument_list expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list return_statement false | causes run to be executed in a newly spawned daemon process |
def match_length(self):
length = 0
for match in self.get_matching_blocks():
a, b, size = match
length += self._text_length(self.a[a:a+size])
return length | module function_definition identifier parameters identifier block expression_statement assignment identifier integer for_statement identifier call attribute identifier identifier argument_list block expression_statement assignment pattern_list identifier identifier identifier identifier expression_statement augmented_assignment identifier call attribute identifier identifier argument_list subscript attribute identifier identifier slice identifier binary_operator identifier identifier return_statement identifier | Find the total length of all words that match between the two sequences. |
def rstjinja(app, docname, source):
if app.builder.format != 'html':
return
src = source[0]
rendered = app.builder.templates.render_string(
src, app.config.html_context
)
source[0] = rendered | module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator attribute attribute identifier identifier identifier string string_start string_content string_end block return_statement expression_statement assignment identifier subscript identifier integer expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list identifier attribute attribute identifier identifier identifier expression_statement assignment subscript identifier integer identifier | Render our pages as a jinja template for fancy templating goodness. |
def _createGsshaPyObjects(self, cell):
gridCell = GridPipeCell(cellI=cell['i'],
cellJ=cell['j'],
numPipes=cell['numPipes'])
gridCell.gridPipeFile = self
for spipe in cell['spipes']:
gridNode = GridPipeNode(linkNumber=spipe['linkNumber'],
nodeNumber=spipe['nodeNumber'],
fractPipeLength=spipe['fraction'])
gridNode.gridPipeCell = gridCell | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list keyword_argument identifier subscript identifier string string_start string_content string_end keyword_argument identifier subscript identifier string string_start string_content string_end keyword_argument identifier subscript identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier identifier for_statement identifier subscript identifier string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list keyword_argument identifier subscript identifier string string_start string_content string_end keyword_argument identifier subscript identifier string string_start string_content string_end keyword_argument identifier subscript identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier identifier | Create GSSHAPY GridPipeCell and GridPipeNode Objects Method |
def _update_tree_feature_weights(X, feature_names, clf, feature_weights):
tree_value = clf.tree_.value
if tree_value.shape[1] == 1:
squeeze_axis = 1
else:
assert tree_value.shape[2] == 1
squeeze_axis = 2
tree_value = np.squeeze(tree_value, axis=squeeze_axis)
tree_feature = clf.tree_.feature
_, indices = clf.decision_path(X).nonzero()
if isinstance(clf, DecisionTreeClassifier):
norm = lambda x: x / x.sum()
else:
norm = lambda x: x
feature_weights[feature_names.bias_idx] += norm(tree_value[0])
for parent_idx, child_idx in zip(indices, indices[1:]):
assert tree_feature[parent_idx] >= 0
feature_idx = tree_feature[parent_idx]
diff = norm(tree_value[child_idx]) - norm(tree_value[parent_idx])
feature_weights[feature_idx] += diff | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier attribute attribute identifier identifier identifier if_statement comparison_operator subscript attribute identifier identifier integer integer block expression_statement assignment identifier integer else_clause block assert_statement comparison_operator subscript attribute identifier identifier integer integer expression_statement assignment identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment pattern_list identifier identifier call attribute call attribute identifier identifier argument_list identifier identifier argument_list if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier lambda lambda_parameters identifier binary_operator identifier call attribute identifier identifier argument_list else_clause block expression_statement assignment identifier lambda lambda_parameters identifier identifier expression_statement augmented_assignment subscript identifier attribute identifier identifier call identifier argument_list subscript identifier integer for_statement pattern_list identifier identifier call identifier argument_list identifier subscript identifier slice integer block assert_statement comparison_operator subscript identifier identifier integer expression_statement assignment identifier subscript identifier identifier expression_statement assignment identifier binary_operator call identifier argument_list subscript identifier identifier call identifier argument_list subscript identifier identifier expression_statement augmented_assignment subscript identifier identifier identifier | Update tree feature weights using decision path method. |
def parent(self):
if self._has_parent is None:
_parent = self._ctx.backend.get_parent(self._ctx.dev)
self._has_parent = _parent is not None
if self._has_parent:
self._parent = Device(_parent, self._ctx.backend)
else:
self._parent = None
return self._parent | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list attribute attribute identifier identifier identifier expression_statement assignment attribute identifier identifier comparison_operator identifier none if_statement attribute identifier identifier block expression_statement assignment attribute identifier identifier call identifier argument_list identifier attribute attribute identifier identifier identifier else_clause block expression_statement assignment attribute identifier identifier none return_statement attribute identifier identifier | Return the parent device. |
def connect(self, address, **kws):
return yield_(Connect(self, address, timeout=self._timeout, **kws)) | module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block return_statement call identifier argument_list call identifier argument_list identifier identifier keyword_argument identifier attribute identifier identifier dictionary_splat identifier | Connect to a remote socket at _address_. |
def groups_get_integrations(self, room_id, **kwargs):
return self.__call_api_get('groups.getIntegrations', roomId=room_id, kwargs=kwargs) | module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block return_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier identifier | Retrieves the integrations which the group has |
def classify(self, encoding, num=1):
probDist = numpy.exp(encoding) / numpy.sum(numpy.exp(encoding))
sortIdx = numpy.argsort(probDist)
return sortIdx[-num:].tolist() | module function_definition identifier parameters identifier identifier default_parameter identifier integer block expression_statement assignment identifier binary_operator call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement call attribute subscript identifier slice unary_operator identifier identifier argument_list | Classify with basic one-hot local incoding |
def clear(self):
for ax in self.flat_grid:
for im_h in ax.findobj(AxesImage):
im_h.remove() | module function_definition identifier parameters identifier block for_statement identifier attribute identifier identifier block for_statement identifier call attribute identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list | Clears all the axes to start fresh. |
def resize(image, width=None, height=None, crop=False, namespace="resized"):
return resize_lazy(image=image, width=width, height=height, crop=crop,
namespace=namespace, as_url=True) | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none default_parameter identifier false default_parameter identifier string string_start string_content string_end block return_statement call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier true | Returns the url of the resized image |
def ShowNotifications(self, reset=True):
shown_notifications = self.Schema.SHOWN_NOTIFICATIONS()
pending = self.Get(self.Schema.PENDING_NOTIFICATIONS, [])
for notification in pending:
shown_notifications.Append(notification)
notifications = self.Get(self.Schema.SHOWN_NOTIFICATIONS, [])
for notification in notifications:
shown_notifications.Append(notification)
if reset:
self.Set(shown_notifications)
self.Set(self.Schema.PENDING_NOTIFICATIONS())
self.Flush()
return shown_notifications | module function_definition identifier parameters identifier default_parameter identifier true block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list attribute attribute identifier identifier identifier list for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute attribute identifier identifier identifier list for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list identifier if_statement identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list return_statement identifier | A generator of current notifications. |
def fetchText(cls, url, data, textSearch, optional):
if textSearch:
match = textSearch.search(data[0])
if match:
text = match.group(1)
out.debug(u'matched text %r with pattern %s' % (text, textSearch.pattern))
return unescape(text).strip()
if optional:
return None
else:
raise ValueError("Pattern %s not found at URL %s." % (textSearch.pattern, url))
else:
return None | module function_definition identifier parameters identifier identifier identifier identifier identifier block if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list subscript identifier integer if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list integer expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple identifier attribute identifier identifier return_statement call attribute call identifier argument_list identifier identifier argument_list if_statement identifier block return_statement none else_clause block raise_statement call identifier argument_list binary_operator string string_start string_content string_end tuple attribute identifier identifier identifier else_clause block return_statement none | Search text entry for given text pattern in a HTML page. |
def parent_organisations(self):
class ParentOrg:
def __init__(self, sdo_id, org_id):
self.sdo_id = sdo_id
self.org_id = org_id
with self._mutex:
if not self._parent_orgs:
for sdo in self._obj.get_organizations():
if not sdo:
continue
owner = sdo.get_owner()
if owner:
sdo_id = owner._narrow(SDOPackage.SDO).get_sdo_id()
else:
sdo_id = ''
org_id = sdo.get_organization_id()
self._parent_orgs.append(ParentOrg(sdo_id, org_id))
return self._parent_orgs | module function_definition identifier parameters identifier block class_definition identifier block function_definition identifier parameters identifier identifier identifier block expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier identifier with_statement with_clause with_item attribute identifier identifier block if_statement not_operator attribute identifier identifier block for_statement identifier call attribute attribute identifier identifier identifier argument_list block if_statement not_operator identifier block continue_statement expression_statement assignment identifier call attribute identifier identifier argument_list if_statement identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list attribute identifier identifier identifier argument_list else_clause block expression_statement assignment identifier string string_start string_end expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list call identifier argument_list identifier identifier return_statement attribute identifier identifier | The organisations this RTC belongs to. |
def _check_error(response):
if 'error' in response:
raise InfluxDBError(response['error'])
elif 'results' in response:
for statement in response['results']:
if 'error' in statement:
msg = '{d[error]} (statement {d[statement_id]})'
raise InfluxDBError(msg.format(d=statement)) | module function_definition identifier parameters identifier block if_statement comparison_operator string string_start string_content string_end identifier block raise_statement call identifier argument_list subscript identifier string string_start string_content string_end elif_clause comparison_operator string string_start string_content string_end identifier block for_statement identifier subscript identifier string string_start string_content string_end block if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier string string_start string_content string_end raise_statement call identifier argument_list call attribute identifier identifier argument_list keyword_argument identifier identifier | Checks for JSON error messages and raises Python exception |
def clean(self):
if self.lookup == '?':
return
else:
lookups = self.lookup.split(LOOKUP_SEP)
opts = self.model_def.model_class()._meta
valid = True
while len(lookups):
lookup = lookups.pop(0)
try:
field = opts.get_field(lookup)
except FieldDoesNotExist:
valid = False
else:
if isinstance(field, models.ForeignKey):
opts = get_remote_field_model(field)._meta
elif len(lookups):
valid = False
finally:
if not valid:
msg = _("This field doesn't exist")
raise ValidationError({'lookup': [msg]}) | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block return_statement else_clause block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier attribute call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier true while_statement call identifier argument_list identifier block expression_statement assignment identifier call attribute identifier identifier argument_list integer try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list identifier except_clause identifier block expression_statement assignment identifier false else_clause block if_statement call identifier argument_list identifier attribute identifier identifier block expression_statement assignment identifier attribute call identifier argument_list identifier identifier elif_clause call identifier argument_list identifier block expression_statement assignment identifier false finally_clause block if_statement not_operator identifier block expression_statement assignment identifier call identifier argument_list string string_start string_content string_end raise_statement call identifier argument_list dictionary pair string string_start string_content string_end list identifier | Make sure the lookup makes sense |
def check_header_comment(filename):
name = os.path.basename( filename )
sourcefile = open( filename, "rU" )
content = sourcefile.read()
sourcefile.close()
match = re.search(r'\$Id\$', content)
if match == None:
match = re.search(r'\$Id: ' + name + r'\s+[^$]+\$', content)
if match != None:
return False
return True | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator binary_operator string string_start string_content string_end identifier string string_start string_content string_end identifier if_statement comparison_operator identifier none block return_statement false return_statement true | Checks if the header-comment of the given file needs fixing. |
def _required_attr(self, attr, key):
assert isinstance(attr, dict)
if key not in attr:
raise AttributeError("Required attribute {} not found.".format(key))
return attr[key] | module function_definition identifier parameters identifier identifier identifier block assert_statement call identifier argument_list identifier identifier if_statement comparison_operator identifier identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier return_statement subscript identifier identifier | Wrapper for getting required attributes. |
def _normalize_file_paths(self, *args):
paths = []
for arg in args:
if arg is None:
continue
elif self._is_valid_file(arg):
paths.append(arg)
elif isinstance(arg, list) and all(self._is_valid_file(_) for _ in arg):
paths = paths + arg
elif not self.ignore_errors:
raise TypeError('Config file paths must be string path or list of paths!')
return paths | module function_definition identifier parameters identifier list_splat_pattern identifier block expression_statement assignment identifier list for_statement identifier identifier block if_statement comparison_operator identifier none block continue_statement elif_clause call attribute identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier elif_clause boolean_operator call identifier argument_list identifier identifier call identifier generator_expression call attribute identifier identifier argument_list identifier for_in_clause identifier identifier block expression_statement assignment identifier binary_operator identifier identifier elif_clause not_operator attribute identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end return_statement identifier | Returns all given configuration file paths as one list. |
def page_not_found(request, template_name="errors/404.html"):
context = {
"STATIC_URL": settings.STATIC_URL,
"request_path": request.path,
}
t = get_template(template_name)
return HttpResponseNotFound(t.render(context, request)) | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier expression_statement assignment identifier call identifier argument_list identifier return_statement call identifier argument_list call attribute identifier identifier argument_list identifier identifier | Mimics Django's 404 handler but with a different template path. |
def check_ipv4(ip_str):
try:
socket.inet_pton(socket.AF_INET, ip_str)
except AttributeError:
try:
socket.inet_aton(ip_str)
except socket.error:
return False
return ip_str.count('.') == 3
except socket.error:
return False
return True | module function_definition identifier parameters identifier block try_statement block expression_statement call attribute identifier identifier argument_list attribute identifier identifier identifier except_clause identifier block try_statement block expression_statement call attribute identifier identifier argument_list identifier except_clause attribute identifier identifier block return_statement false return_statement comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end integer except_clause attribute identifier identifier block return_statement false return_statement true | Return True if is a valid IP v4 |
def node_to_object(self, node, object):
"Map a single node to one object's attributes"
attribute = self.to_lower(node.tag)
attribute = "_yield" if attribute == "yield" else attribute
try:
valueString = node.text or ""
value = float(valueString)
except ValueError:
value = node.text
try:
setattr(object, attribute, value)
except AttributeError():
sys.stderr.write("Attribute <%s> not supported." % attribute) | module function_definition identifier parameters identifier identifier identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier conditional_expression string string_start string_content string_end comparison_operator identifier string string_start string_content string_end identifier try_statement block expression_statement assignment identifier boolean_operator attribute identifier identifier string string_start string_end expression_statement assignment identifier call identifier argument_list identifier except_clause identifier block expression_statement assignment identifier attribute identifier identifier try_statement block expression_statement call identifier argument_list identifier identifier identifier except_clause call identifier argument_list block expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content string_end identifier | Map a single node to one object's attributes |
def watch(cams, path=None, delay=10):
while True:
for c in cams:
c.snap(path)
time.sleep(delay) | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier integer block while_statement true block for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier | Get screenshots from all cams at defined intervall. |
def hydrate_bundles(bundles_field, glob_match_error_behavior):
path_globs_with_match_errors = [
pg.copy(glob_match_error_behavior=glob_match_error_behavior)
for pg in bundles_field.path_globs_list
]
snapshot_list = yield [Get(Snapshot, PathGlobs, pg) for pg in path_globs_with_match_errors]
spec_path = bundles_field.address.spec_path
bundles = []
zipped = zip(bundles_field.bundles,
bundles_field.filespecs_list,
snapshot_list)
for bundle, filespecs, snapshot in zipped:
rel_spec_path = getattr(bundle, 'rel_path', spec_path)
kwargs = bundle.kwargs()
kwargs['fileset'] = _eager_fileset_with_spec(rel_spec_path,
filespecs,
snapshot,
include_dirs=True)
bundles.append(BundleAdaptor(**kwargs))
yield HydratedField('bundles', bundles) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list_comprehension call attribute identifier identifier argument_list keyword_argument identifier identifier for_in_clause identifier attribute identifier identifier expression_statement assignment identifier yield list_comprehension call identifier argument_list identifier identifier identifier for_in_clause identifier identifier expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier list expression_statement assignment identifier call identifier argument_list attribute identifier identifier attribute identifier identifier identifier for_statement pattern_list identifier identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment subscript identifier string string_start string_content string_end call identifier argument_list identifier identifier identifier keyword_argument identifier true expression_statement call attribute identifier identifier argument_list call identifier argument_list dictionary_splat identifier expression_statement yield call identifier argument_list string string_start string_content string_end identifier | Given a BundlesField, request Snapshots for each of its filesets and create BundleAdaptors. |
def _notify_fn(self):
self._notifyrunning = True
while self._notifyrunning:
try:
with IHCController._mutex:
if self._newnotifyids:
self.client.enable_runtime_notifications(
self._newnotifyids)
self._newnotifyids = []
changes = self.client.wait_for_resource_value_changes()
if changes is False:
self.re_authenticate(True)
continue
for ihcid in changes:
value = changes[ihcid]
if ihcid in self._ihcevents:
for callback in self._ihcevents[ihcid]:
callback(ihcid, value)
except Exception as exp:
self.re_authenticate(True) | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier true while_statement attribute identifier identifier block try_statement block with_statement with_clause with_item attribute identifier identifier block if_statement attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier list expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list if_statement comparison_operator identifier false block expression_statement call attribute identifier identifier argument_list true continue_statement for_statement identifier identifier block expression_statement assignment identifier subscript identifier identifier if_statement comparison_operator identifier attribute identifier identifier block for_statement identifier subscript attribute identifier identifier identifier block expression_statement call identifier argument_list identifier identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list true | The notify thread function. |
def save_uca(self, rootpath, raw=False, as_int=False):
self.save_array(self.uca, None, 'uca', rootpath, raw, as_int=as_int) | module function_definition identifier parameters identifier identifier default_parameter identifier false default_parameter identifier false block expression_statement call attribute identifier identifier argument_list attribute identifier identifier none string string_start string_content string_end identifier identifier keyword_argument identifier identifier | Saves the upstream contributing area to a file |
def discovery_zookeeper(self):
self.context.install_bundle("pelix.remote.discovery.zookeeper").start()
with use_waiting_list(self.context) as ipopo:
ipopo.add(
rs.FACTORY_DISCOVERY_ZOOKEEPER,
"pelix-discovery-zookeeper",
{
"application.id": "sample.rs",
"zookeeper.hosts": self.arguments.zk_hosts,
"zookeeper.prefix": self.arguments.zk_prefix,
},
) | module function_definition identifier parameters identifier block expression_statement call attribute call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier argument_list with_statement with_clause with_item as_pattern call identifier argument_list attribute identifier identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list attribute identifier 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 attribute attribute identifier identifier identifier pair string string_start string_content string_end attribute attribute identifier identifier identifier | Installs the ZooKeeper discovery bundles and instantiates components |
def _category_slugs(self, category):
key = self._category_key(category)
slugs = self.r.smembers(key)
return slugs | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier return_statement identifier | Returns a set of the metric slugs for the given category |
def affected_files(self):
added, modified, deleted = self._changes_cache
return list(added.union(modified).union(deleted)) | module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier identifier attribute identifier identifier return_statement call identifier argument_list call attribute call attribute identifier identifier argument_list identifier identifier argument_list identifier | Get's a fast accessible file changes for given changeset |
def subscribe(hub, callback_url, topic_url, lease_seconds, secret,
endpoint_hook_data):
for validate in hub.validators:
error = validate(callback_url, topic_url, lease_seconds, secret,
endpoint_hook_data)
if error:
send_denied(hub, callback_url, topic_url, error)
return
if intent_verified(hub, callback_url, 'subscribe', topic_url,
lease_seconds):
hub.storage[topic_url, callback_url] = {
'lease_seconds': lease_seconds,
'secret': secret,
} | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier block for_statement identifier attribute identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier identifier identifier identifier if_statement identifier block expression_statement call identifier argument_list identifier identifier identifier identifier return_statement if_statement call identifier argument_list identifier identifier string string_start string_content string_end identifier identifier block expression_statement assignment subscript attribute identifier identifier identifier identifier dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier | 5.2 Subscription Validation |
def validate(self):
if not isinstance(self.fold_scope_location, FoldScopeLocation):
raise TypeError(u'Expected FoldScopeLocation fold_scope_location, got: {} {}'.format(
type(self.fold_scope_location), self.fold_scope_location))
allowed_block_types = (GremlinFoldedFilter, GremlinFoldedTraverse, Backtrack)
for block in self.folded_ir_blocks:
if not isinstance(block, allowed_block_types):
raise AssertionError(
u'Found invalid block of type {} in folded_ir_blocks: {} '
u'Allowed types are {}.'
.format(type(block), self.folded_ir_blocks, allowed_block_types))
if not isinstance(self.field_type, GraphQLList):
raise ValueError(u'Invalid value of "field_type", expected a list type but got: '
u'{}'.format(self.field_type))
inner_type = strip_non_null_from_type(self.field_type.of_type)
if isinstance(inner_type, GraphQLList):
raise GraphQLCompilationError(
u'Outputting list-valued fields in a @fold context is currently '
u'not supported: {} {}'.format(self.fold_scope_location, self.field_type.of_type)) | module function_definition identifier parameters identifier block if_statement not_operator call identifier argument_list attribute identifier identifier identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list call identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement assignment identifier tuple identifier identifier identifier for_statement identifier attribute identifier identifier block if_statement not_operator call identifier argument_list identifier identifier block raise_statement call identifier argument_list call attribute concatenated_string string string_start string_content string_end string string_start string_content string_end identifier argument_list call identifier argument_list identifier attribute identifier identifier identifier if_statement not_operator call identifier argument_list attribute identifier identifier identifier block raise_statement call identifier argument_list call attribute concatenated_string string string_start string_content string_end string string_start string_content string_end identifier argument_list attribute identifier identifier expression_statement assignment identifier call identifier argument_list attribute attribute identifier identifier identifier if_statement call identifier argument_list identifier identifier block raise_statement call identifier argument_list call attribute concatenated_string string string_start string_content string_end string string_start string_content string_end identifier argument_list attribute identifier identifier attribute attribute identifier identifier identifier | Validate that the GremlinFoldedContextField is correctly representable. |
def save_params(step_num, model, trainer, ckpt_dir):
param_path = os.path.join(ckpt_dir, '%07d.params'%step_num)
trainer_path = os.path.join(ckpt_dir, '%07d.states'%step_num)
logging.info('[step %d] Saving checkpoints to %s, %s.',
step_num, param_path, trainer_path)
model.save_parameters(param_path)
trainer.save_states(trainer_path) | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier binary_operator string string_start string_content string_end identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier binary_operator string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier | Save the model parameter, marked by step_num. |
def cache(self, private=False, max_age=31536000, s_maxage=None, no_cache=False, no_store=False,
must_revalidate=False, **overrides):
parts = ('private' if private else 'public', 'max-age={0}'.format(max_age),
's-maxage={0}'.format(s_maxage) if s_maxage is not None else None, no_cache and 'no-cache',
no_store and 'no-store', must_revalidate and 'must-revalidate')
return self.add_response_headers({'cache-control': ', '.join(filter(bool, parts))}, **overrides) | module function_definition identifier parameters identifier default_parameter identifier false default_parameter identifier integer default_parameter identifier none default_parameter identifier false default_parameter identifier false default_parameter identifier false dictionary_splat_pattern identifier block expression_statement assignment identifier tuple conditional_expression string string_start string_content string_end identifier string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list identifier conditional_expression call attribute string string_start string_content string_end identifier argument_list identifier comparison_operator identifier none none boolean_operator identifier string string_start string_content string_end boolean_operator identifier string string_start string_content string_end boolean_operator identifier string string_start string_content string_end return_statement call attribute identifier identifier argument_list dictionary pair string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list call identifier argument_list identifier identifier dictionary_splat identifier | Convenience method for quickly adding cache header to route |
def render_config(config: Config, indent: str = "") -> str:
new_indent = indent + " "
return "".join([
"{\n",
f'{new_indent}"type": "{config.typ3}",\n' if config.typ3 else '',
"".join(_render(item, new_indent) for item in config.items),
indent,
"}\n"
]) | module function_definition identifier parameters typed_parameter identifier type identifier typed_default_parameter identifier type identifier string string_start string_end type identifier block expression_statement assignment identifier binary_operator identifier string string_start string_content string_end return_statement call attribute string string_start string_end identifier argument_list list string string_start string_content escape_sequence string_end conditional_expression string string_start interpolation identifier string_content interpolation attribute identifier identifier string_content escape_sequence string_end attribute identifier identifier string string_start string_end call attribute string string_start string_end identifier generator_expression call identifier argument_list identifier identifier for_in_clause identifier attribute identifier identifier identifier string string_start string_content escape_sequence string_end | Pretty-print a config in sort-of-JSON+comments. |
def _compute_one_step(self, t, fields, pars):
fields, pars = self._hook(t, fields, pars)
self.dt = (self.tmax - t
if self.tmax and (t + self.dt >= self.tmax)
else self.dt)
before_compute = time.process_time()
t, fields = self._scheme(t, fields, self.dt,
pars, hook=self._hook)
after_compute = time.process_time()
self._last_running = after_compute - before_compute
self._total_running += self._last_running
self._last_timestamp = self._actual_timestamp
self._actual_timestamp = pendulum.now()
return t, fields, pars | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier identifier identifier expression_statement assignment attribute identifier identifier parenthesized_expression conditional_expression binary_operator attribute identifier identifier identifier boolean_operator attribute identifier identifier parenthesized_expression comparison_operator binary_operator identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier identifier attribute identifier identifier identifier keyword_argument identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier binary_operator identifier identifier expression_statement augmented_assignment attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list return_statement expression_list identifier identifier identifier | Compute one step of the simulation, then update the timers. |
def send(self, **kwargs):
return_full_object = kwargs.get('return_full_object', False)
_verbose = kwargs.get('_verbose', False)
traversal = kwargs.get('traversal', None)
timeout = kwargs.get('_timeout', 5)
self.output['url'] = self.render_url()
with VerboseContextManager(verbose=_verbose):
try:
resp = Response(self.action.format(), request(timeout=timeout, **self.output), traversal)
except HTTPError as err:
raise ResponseException(self.action.format(), err)
except socket.timeout:
raise RequestTimeout(functools.partial(self.send, **kwargs))
except URLError as err:
if isinstance(err.reason, socket.timeout):
raise RequestTimeout(functools.partial(self.send, **kwargs))
else:
raise
if return_full_object:
return resp
else:
return resp.read() | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end false expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end false expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end none expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end integer expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end call attribute identifier identifier argument_list with_statement with_clause with_item call identifier argument_list keyword_argument identifier identifier block try_statement block expression_statement assignment identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list call identifier argument_list keyword_argument identifier identifier dictionary_splat attribute identifier identifier identifier except_clause as_pattern identifier as_pattern_target identifier block raise_statement call identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier except_clause attribute identifier identifier block raise_statement call identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier dictionary_splat identifier except_clause as_pattern identifier as_pattern_target identifier block if_statement call identifier argument_list attribute identifier identifier attribute identifier identifier block raise_statement call identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier dictionary_splat identifier else_clause block raise_statement if_statement identifier block return_statement identifier else_clause block return_statement call attribute identifier identifier argument_list | Send the request defined by the data stored in the object. |
def _valid_date(self):
date = self._parse_date(self.date)
if not date:
exit_after_echo(INVALID_DATE)
try:
date = datetime.strptime(date, '%Y%m%d')
except ValueError:
exit_after_echo(INVALID_DATE)
offset = date - datetime.today()
if offset.days not in range(-1, 50):
exit_after_echo(INVALID_DATE)
return datetime.strftime(date, '%Y-%m-%d') | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier if_statement not_operator identifier block expression_statement call identifier argument_list identifier try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list identifier string string_start string_content string_end except_clause identifier block expression_statement call identifier argument_list identifier expression_statement assignment identifier binary_operator identifier call attribute identifier identifier argument_list if_statement comparison_operator attribute identifier identifier call identifier argument_list unary_operator integer integer block expression_statement call identifier argument_list identifier return_statement call attribute identifier identifier argument_list identifier string string_start string_content string_end | Check and return a valid query date. |
def find_by_any(self, identifier, how):
if "i" in how:
match = self.find_by_id(identifier)
if match:
return match
if "l" in how:
match = self.find_by_localpath(identifier)
if match:
return match
if "c" in how:
match = self.find_by_canonical(identifier)
if match:
return match | module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement identifier block return_statement identifier if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement identifier block return_statement identifier if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement identifier block return_statement identifier | how should be a string with any or all of the characters "ilc" |
def _check_valid(key, val, valid):
if val not in valid:
raise ValueError('%s must be one of %s, not "%s"'
% (key, valid, val)) | module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator identifier identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier identifier | Helper to check valid options |
def chunker(f, n):
f = iter(f)
x = []
while 1:
if len(x) < n:
try:
x.append(f.next())
except StopIteration:
if len(x) > 0:
yield tuple(x)
break
else:
yield tuple(x)
x = [] | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier list while_statement integer block if_statement comparison_operator call identifier argument_list identifier identifier block try_statement block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list except_clause identifier block if_statement comparison_operator call identifier argument_list identifier integer block expression_statement yield call identifier argument_list identifier break_statement else_clause block expression_statement yield call identifier argument_list identifier expression_statement assignment identifier list | Utility function to split iterable `f` into `n` chunks |
def _getEventsByWeek(self, request, year, month):
return getAllEventsByWeek(request, year, month, home=self) | module function_definition identifier parameters identifier identifier identifier identifier block return_statement call identifier argument_list identifier identifier identifier keyword_argument identifier identifier | Return my child events for the given month grouped by week. |
def draw_image(pixelmap, img):
for item in pixelmap:
color = item[2]
pixelbox = (item[0][0], item[0][1], item[1][0], item[1][1])
draw = ImageDraw.Draw(img)
draw.rectangle(pixelbox, fill=color) | module function_definition identifier parameters identifier identifier block for_statement identifier identifier block expression_statement assignment identifier subscript identifier integer expression_statement assignment identifier tuple subscript subscript identifier integer integer subscript subscript identifier integer integer subscript subscript identifier integer integer subscript subscript identifier integer integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier identifier | Draws the image based on the given pixelmap. |
def save_csv(p, sheet):
'Save as single CSV file, handling column names as first line.'
with p.open_text(mode='w') as fp:
cw = csv.writer(fp, **csvoptions())
colnames = [col.name for col in sheet.visibleCols]
if ''.join(colnames):
cw.writerow(colnames)
for r in Progress(sheet.rows, 'saving'):
cw.writerow([col.getDisplayValue(r) for col in sheet.visibleCols]) | module function_definition identifier parameters identifier identifier block expression_statement string string_start string_content string_end with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list keyword_argument identifier string string_start string_content string_end as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier dictionary_splat call identifier argument_list expression_statement assignment identifier list_comprehension attribute identifier identifier for_in_clause identifier attribute identifier identifier if_statement call attribute string string_start string_end identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier for_statement identifier call identifier argument_list attribute identifier identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list list_comprehension call attribute identifier identifier argument_list identifier for_in_clause identifier attribute identifier identifier | Save as single CSV file, handling column names as first line. |
def build_and_run(self, images):
from harpoon.ship.builder import Builder
Builder().make_image(self, images)
try:
Runner().run_container(self, images)
except DockerAPIError as error:
raise BadImage("Failed to start the container", error=error) | module function_definition identifier parameters identifier identifier block import_from_statement dotted_name identifier identifier identifier dotted_name identifier expression_statement call attribute call identifier argument_list identifier argument_list identifier identifier try_statement block expression_statement call attribute call identifier argument_list identifier argument_list identifier identifier except_clause as_pattern identifier as_pattern_target identifier block raise_statement call identifier argument_list string string_start string_content string_end keyword_argument identifier identifier | Make this image and run it |
def total(self):
feats = imap(lambda name: self[name], self._counters())
return sum(chain(*map(lambda mset: map(abs, mset.values()), feats))) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list lambda lambda_parameters identifier subscript identifier identifier call attribute identifier identifier argument_list return_statement call identifier argument_list call identifier argument_list list_splat call identifier argument_list lambda lambda_parameters identifier call identifier argument_list identifier call attribute identifier identifier argument_list identifier | Returns sum of all counts in all features that are multisets. |
def isEmpty(self):
return self.x0 == self.x1 or self.y0 == self.y1 | module function_definition identifier parameters identifier block return_statement boolean_operator comparison_operator attribute identifier identifier attribute identifier identifier comparison_operator attribute identifier identifier attribute identifier identifier | Check if rectangle area is empty. |
def addNode(self, node):
self.msg(4, "addNode", node)
try:
self.graph.restore_node(node.graphident)
except GraphError:
self.graph.add_node(node.graphident, node) | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list integer string string_start string_content string_end identifier try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier except_clause identifier block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier identifier | Add a node to the graph referenced by the root |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.