code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def disconnect(self):
for signal, kwargs in self.connections:
signal.disconnect(self, **kwargs) | module function_definition identifier parameters identifier block for_statement pattern_list identifier identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier dictionary_splat identifier | Disconnect all connected signal types from this receiver. |
def handle_error(self, request, client_address):
if self.can_ignore_error():
return
thread = threading.current_thread()
msg("Error in request ({0}): {1} in {2}\n{3}",
client_address, repr(request), thread.name, traceback.format_exc()) | module function_definition identifier parameters identifier identifier identifier block if_statement call attribute identifier identifier argument_list block return_statement expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call identifier argument_list string string_start string_content escape_sequence string_end identifier call identifier argument_list identifier attribute identifier identifier call attribute identifier identifier argument_list | Handle an error gracefully. |
def Init(service_client=None):
global CONN
global label_map
global unknown_label
if service_client is None:
service_client_cls = fs_client.InsecureGRPCServiceClient
fleetspeak_message_listen_address = (
config.CONFIG["Server.fleetspeak_message_listen_address"] or None)
fleetspeak_server = config.CONFIG["Server.fleetspeak_server"] or None
if fleetspeak_message_listen_address is None and fleetspeak_server is None:
logging.warning(
"Missing config options `Server.fleetspeak_message_listen_address', "
"`Server.fleetspeak_server', at least one of which is required to "
"initialize a connection to Fleetspeak; Not using Fleetspeak.")
return
service_client = service_client_cls(
"GRR",
fleetspeak_message_listen_address=fleetspeak_message_listen_address,
fleetspeak_server=fleetspeak_server,
threadpool_size=50)
unknown_label = config.CONFIG["Server.fleetspeak_unknown_label"]
label_map = {}
for entry in config.CONFIG["Server.fleetspeak_label_map"]:
key, value = entry.split(":")
label_map[key] = value
CONN = service_client
logging.info("Fleetspeak connector initialized.") | module function_definition identifier parameters default_parameter identifier none block global_statement identifier global_statement identifier global_statement identifier if_statement comparison_operator identifier none block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier parenthesized_expression boolean_operator subscript attribute identifier identifier string string_start string_content string_end none expression_statement assignment identifier boolean_operator subscript attribute identifier identifier string string_start string_content string_end none if_statement boolean_operator comparison_operator identifier none comparison_operator identifier none block expression_statement call attribute identifier identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end return_statement expression_statement assignment identifier call identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier integer expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier dictionary for_statement identifier subscript attribute identifier identifier string string_start string_content string_end block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment subscript identifier identifier identifier expression_statement assignment identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end | Initializes the Fleetspeak connector. |
def _sanitize_windows_name(cls, arcname, pathsep):
table = cls._windows_illegal_name_trans_table
if not table:
illegal = ':<>|"?*'
table = str.maketrans(illegal, '_' * len(illegal))
cls._windows_illegal_name_trans_table = table
arcname = arcname.translate(table)
arcname = (x.rstrip('.') for x in arcname.split(pathsep))
arcname = pathsep.join(x for x in arcname if x)
return arcname | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier attribute identifier identifier if_statement not_operator identifier block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier binary_operator string string_start string_content string_end call identifier argument_list identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier generator_expression call attribute identifier identifier argument_list string string_start string_content string_end for_in_clause identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier generator_expression identifier for_in_clause identifier identifier if_clause identifier return_statement identifier | Replace bad characters and remove trailing dots from parts. |
def token(self):
if self._token is None or \
datetime.datetime.now() >= self._token_expires_on:
self._generateForOAuthSecurity(self._client_id,
self._secret_id,
self._token_url)
return self._token | module function_definition identifier parameters identifier block if_statement boolean_operator comparison_operator attribute identifier identifier none line_continuation comparison_operator call attribute attribute identifier identifier identifier argument_list attribute identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier return_statement attribute identifier identifier | obtains a token from the site |
def frame_update_count(self):
result = 1000000
for column in self._columns:
for widget in column:
if widget.frame_update_count > 0:
result = min(result, widget.frame_update_count)
return result | module function_definition identifier parameters identifier block expression_statement assignment identifier integer for_statement identifier attribute identifier identifier block for_statement identifier identifier block if_statement comparison_operator attribute identifier identifier integer block expression_statement assignment identifier call identifier argument_list identifier attribute identifier identifier return_statement identifier | The number of frames before this Layout should be updated. |
def resources_preparing_factory(app, wrapper):
settings = app.app.registry.settings
config = settings.get(CONFIG_RESOURCES, None)
if not config:
return
resources = [(k, [wrapper(r, GroupResource(k, v)) for r in v])
for k, v in config]
settings[CONFIG_RESOURCES] = resources | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute attribute attribute identifier identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier none if_statement not_operator identifier block return_statement expression_statement assignment identifier list_comprehension tuple identifier list_comprehension call identifier argument_list identifier call identifier argument_list identifier identifier for_in_clause identifier identifier for_in_clause pattern_list identifier identifier identifier expression_statement assignment subscript identifier identifier identifier | Factory which wrap all resources in settings. |
def seek(self, offset, whence=SEEK_SET):
if whence == SEEK_SET:
self.__sf.seek(offset)
elif whence == SEEK_CUR:
self.__sf.seek(self.tell() + offset)
elif whence == SEEK_END:
self.__sf.seek(self.__sf.filesize - offset) | module function_definition identifier parameters identifier identifier default_parameter identifier identifier block if_statement comparison_operator identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier elif_clause comparison_operator identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator call attribute identifier identifier argument_list identifier elif_clause comparison_operator identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator attribute attribute identifier identifier identifier identifier | Reposition the file pointer. |
def _nested_transactional(fn):
@wraps(fn)
def wrapped(self, *args, **kwargs):
try:
rv = fn(self, *args, **kwargs)
except _TransactionalPolicyViolationError as e:
getattr(self, _TX_HOLDER_ATTRIBUTE).rollback()
rv = e.result
return rv
return wrapped | module function_definition identifier parameters identifier block decorated_definition decorator call identifier argument_list identifier function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block try_statement block expression_statement assignment identifier call identifier argument_list identifier list_splat identifier dictionary_splat identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list expression_statement assignment identifier attribute identifier identifier return_statement identifier return_statement identifier | In a transactional method create a nested transaction. |
def diff(self, filename, wildcard='*'):
other = MAVParmDict()
if not other.load(filename):
return
keys = sorted(list(set(self.keys()).union(set(other.keys()))))
for k in keys:
if not fnmatch.fnmatch(str(k).upper(), wildcard.upper()):
continue
if not k in other:
print("%-16.16s %12.4f" % (k, self[k]))
elif not k in self:
print("%-16.16s %12.4f" % (k, other[k]))
elif abs(self[k] - other[k]) > self.mindelta:
print("%-16.16s %12.4f %12.4f" % (k, other[k], self[k])) | module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list if_statement not_operator call attribute identifier identifier argument_list identifier block return_statement expression_statement assignment identifier call identifier argument_list call identifier argument_list call attribute call identifier argument_list call attribute identifier identifier argument_list identifier argument_list call identifier argument_list call attribute identifier identifier argument_list for_statement identifier identifier block if_statement not_operator call attribute identifier identifier argument_list call attribute call identifier argument_list identifier identifier argument_list call attribute identifier identifier argument_list block continue_statement if_statement not_operator comparison_operator identifier identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end tuple identifier subscript identifier identifier elif_clause not_operator comparison_operator identifier identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end tuple identifier subscript identifier identifier elif_clause comparison_operator call identifier argument_list binary_operator subscript identifier identifier subscript identifier identifier attribute identifier identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end tuple identifier subscript identifier identifier subscript identifier identifier | show differences with another parameter file |
def WSDLUriToVersion(self, uri):
value = self._wsdl_uri_mapping.get(uri)
if value is not None:
return value
raise ValueError(
'Unsupported SOAP envelope uri: %s' % uri
) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier if_statement comparison_operator identifier none block return_statement identifier raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier | Return the WSDL version related to a WSDL namespace uri. |
def to_glyphs_kerning(self):
for master_id, source in self._sources.items():
for (left, right), value in source.font.kerning.items():
left_match = UFO_KERN_GROUP_PATTERN.match(left)
right_match = UFO_KERN_GROUP_PATTERN.match(right)
if left_match:
left = "@MMK_L_{}".format(left_match.group(2))
if right_match:
right = "@MMK_R_{}".format(right_match.group(2))
self.font.setKerningForPair(master_id, left, right, value) | module function_definition identifier parameters identifier block for_statement pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list block for_statement pattern_list tuple_pattern identifier identifier identifier call attribute attribute attribute identifier identifier identifier identifier argument_list block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list call attribute identifier identifier argument_list integer if_statement identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list call attribute identifier identifier argument_list integer expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier identifier identifier | Add UFO kerning to GSFont. |
def close(self):
logging.debug('Closing for user {user}'.format(user=self.id.name))
self.id.release_name()
for room in self._rooms.values():
room.disconnect(self) | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier attribute attribute identifier identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list for_statement identifier call attribute attribute identifier identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list identifier | Closes the connection by removing the user from all rooms |
def _find_ble_controllers(self):
controllers = self.bable.list_controllers()
return [ctrl for ctrl in controllers if ctrl.powered and ctrl.low_energy] | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list return_statement list_comprehension identifier for_in_clause identifier identifier if_clause boolean_operator attribute identifier identifier attribute identifier identifier | Get a list of the available and powered BLE controllers |
def dot(vec1, vec2):
if isinstance(vec1, Vector3) and isinstance(vec2, Vector3):
return (vec1.x * vec2.x) + (vec1.y * vec2.y) + (vec1.z * vec2.z)
elif isinstance(vec1, Vector4) and isinstance(vec2, Vector4):
return (vec1.x * vec2.x) + (vec1.y * vec2.y) + (vec1.z * vec2.z) + (vec1.w * vec2.w)
else:
raise TypeError("vec1 and vec2 must a Vector type") | module function_definition identifier parameters identifier identifier block if_statement boolean_operator call identifier argument_list identifier identifier call identifier argument_list identifier identifier block return_statement binary_operator binary_operator parenthesized_expression binary_operator attribute identifier identifier attribute identifier identifier parenthesized_expression binary_operator attribute identifier identifier attribute identifier identifier parenthesized_expression binary_operator attribute identifier identifier attribute identifier identifier elif_clause boolean_operator call identifier argument_list identifier identifier call identifier argument_list identifier identifier block return_statement binary_operator binary_operator binary_operator parenthesized_expression binary_operator attribute identifier identifier attribute identifier identifier parenthesized_expression binary_operator attribute identifier identifier attribute identifier identifier parenthesized_expression binary_operator attribute identifier identifier attribute identifier identifier parenthesized_expression binary_operator attribute identifier identifier attribute identifier identifier else_clause block raise_statement call identifier argument_list string string_start string_content string_end | Returns the dot product of two Vectors |
def _load_image(cls, rkey):
v = cls._stock[rkey]
img = None
itype = v['type']
if itype in ('stock', 'data'):
img = tk.PhotoImage(format=v['format'], data=v['data'])
elif itype == 'created':
img = v['image']
else:
img = tk.PhotoImage(file=v['filename'])
cls._cached[rkey] = img
logger.info('Loaded resource %s.' % rkey)
return img | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier identifier expression_statement assignment identifier none expression_statement assignment identifier subscript identifier string string_start string_content string_end if_statement comparison_operator identifier tuple string string_start string_content string_end string string_start string_content string_end block expression_statement assignment identifier call attribute identifier 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 elif_clause comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier subscript identifier string string_start string_content string_end else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier subscript identifier string string_start string_content string_end expression_statement assignment subscript attribute identifier identifier identifier identifier expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier return_statement identifier | Load image from file or return the cached instance. |
def _initialize_progress_bar(self):
widgets = ['Download: ', Percentage(), ' ', Bar(),
' ', AdaptiveETA(), ' ', FileTransferSpeed()]
self._downloadProgressBar = ProgressBar(
widgets=widgets, max_value=self._imageCount).start() | module function_definition identifier parameters identifier block expression_statement assignment identifier list string string_start string_content string_end call identifier argument_list string string_start string_content string_end call identifier argument_list string string_start string_content string_end call identifier argument_list string string_start string_content string_end call identifier argument_list expression_statement assignment attribute identifier identifier call attribute call identifier argument_list keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier identifier argument_list | Initializes the progress bar |
def _next_channel(self):
chanid = self._channel_counter
while self._channels.get(chanid) is not None:
self._channel_counter = (self._channel_counter + 1) & 0xffffff
chanid = self._channel_counter
self._channel_counter = (self._channel_counter + 1) & 0xffffff
return chanid | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier while_statement comparison_operator call attribute attribute identifier identifier identifier argument_list identifier none block expression_statement assignment attribute identifier identifier binary_operator parenthesized_expression binary_operator attribute identifier identifier integer integer expression_statement assignment identifier attribute identifier identifier expression_statement assignment attribute identifier identifier binary_operator parenthesized_expression binary_operator attribute identifier identifier integer integer return_statement identifier | you are holding the lock |
def to_native_units(self, motor):
assert abs(self.degrees_per_minute) <= motor.max_dpm,\
"invalid degrees-per-minute: {} max DPM is {}, {} was requested".format(
motor, motor.max_dpm, self.degrees_per_minute)
return self.degrees_per_minute/motor.max_dpm * motor.max_speed | module function_definition identifier parameters identifier identifier block assert_statement comparison_operator call identifier argument_list attribute identifier identifier attribute identifier identifier call attribute string string_start string_content string_end identifier argument_list identifier attribute identifier identifier attribute identifier identifier return_statement binary_operator binary_operator attribute identifier identifier attribute identifier identifier attribute identifier identifier | Return the native speed measurement required to achieve desired degrees-per-minute |
def login_password(self, value):
password = self.selenium.find_element(*self._password_input_locator)
password.clear()
password.send_keys(value) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list list_splat attribute identifier identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier | Set the value of the login password field. |
def _gcs_list_keys(bucket, pattern):
data = [{'Name': obj.metadata.name,
'Type': obj.metadata.content_type,
'Size': obj.metadata.size,
'Updated': obj.metadata.updated_on}
for obj in _gcs_get_keys(bucket, pattern)]
return google.datalab.utils.commands.render_dictionary(data, ['Name', 'Type', 'Size', 'Updated']) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list_comprehension dictionary 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 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 for_in_clause identifier call identifier argument_list identifier identifier return_statement call attribute attribute attribute attribute identifier identifier identifier identifier identifier argument_list identifier list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end | List all Google Cloud Storage keys in a specified bucket that match a pattern. |
def create_command_dir(self):
cmd_dir = os.path.join(self.archive_dir, "insights_commands")
os.makedirs(cmd_dir, 0o700)
return cmd_dir | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier integer return_statement identifier | Create the "sos_commands" dir |
def static_method(cls, f):
setattr(cls, f.__name__, staticmethod(f))
return f | module function_definition identifier parameters identifier identifier block expression_statement call identifier argument_list identifier attribute identifier identifier call identifier argument_list identifier return_statement identifier | Decorator which dynamically binds static methods to the model for later use. |
def reduce_output_path(path=None, pdb_name=None):
if not path:
if not pdb_name:
raise NameError(
"Cannot save an output for a temporary file without a PDB"
"code specified")
pdb_name = pdb_name.lower()
output_path = Path(global_settings['structural_database']['path'],
pdb_name[1:3].lower(), pdb_name[:4].lower(),
'reduce', pdb_name + '_reduced.mmol')
else:
input_path = Path(path)
if len(input_path.parents) > 1:
output_path = input_path.parents[1] / 'reduce' / \
(input_path.stem + '_reduced' + input_path.suffix)
else:
output_path = input_path.parent / \
(input_path.stem + '_reduced' + input_path.suffix)
return output_path | module function_definition identifier parameters default_parameter identifier none default_parameter identifier none block if_statement not_operator identifier block if_statement not_operator identifier block raise_statement call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list subscript subscript identifier string string_start string_content string_end string string_start string_content string_end call attribute subscript identifier slice integer integer identifier argument_list call attribute subscript identifier slice integer identifier argument_list string string_start string_content string_end binary_operator identifier string string_start string_content string_end else_clause block expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator call identifier argument_list attribute identifier identifier integer block expression_statement assignment identifier binary_operator binary_operator subscript attribute identifier identifier integer string string_start string_content string_end line_continuation parenthesized_expression binary_operator binary_operator attribute identifier identifier string string_start string_content string_end attribute identifier identifier else_clause block expression_statement assignment identifier binary_operator attribute identifier identifier line_continuation parenthesized_expression binary_operator binary_operator attribute identifier identifier string string_start string_content string_end attribute identifier identifier return_statement identifier | Defines location of Reduce output files relative to input files. |
def serialize_tag(tag, *, indent=None, compact=False, quote=None):
serializer = Serializer(indent=indent, compact=compact, quote=quote)
return serializer.serialize(tag) | module function_definition identifier parameters identifier keyword_separator default_parameter identifier none default_parameter identifier false default_parameter identifier none block expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier return_statement call attribute identifier identifier argument_list identifier | Serialize an nbt tag to its literal representation. |
def _sync_projects(self, projects_json):
for project_json in projects_json:
project_id = project_json['id']
self.projects[project_id] = Project(project_json, self) | module function_definition identifier parameters identifier identifier block for_statement identifier identifier block expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment subscript attribute identifier identifier identifier call identifier argument_list identifier identifier | Populate the user's projects from a JSON encoded list. |
def create_note(self, from_email, content):
if from_email is None or not isinstance(from_email, six.string_types):
raise MissingFromEmail(from_email)
endpoint = '/'.join((self.endpoint, self.id, 'notes'))
add_headers = {'from': from_email, }
return self.noteFactory.create(
endpoint=endpoint,
api_key=self.api_key,
add_headers=add_headers,
data={'content': content},
) | module function_definition identifier parameters identifier identifier identifier block if_statement boolean_operator comparison_operator identifier none not_operator call identifier argument_list identifier attribute identifier identifier block raise_statement call identifier argument_list identifier expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list tuple attribute identifier identifier attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier return_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier keyword_argument identifier dictionary pair string string_start string_content string_end identifier | Create a note for this incident. |
def getPollingRate(self):
print '%s call getPollingRate' % self.port
sPollingRate = self.__sendCommand('pollperiod')[0]
try:
iPollingRate = int(sPollingRate)/1000
fPollingRate = round(float(sPollingRate)/1000, 3)
return fPollingRate if fPollingRate > iPollingRate else iPollingRate
except Exception, e:
ModuleHelper.WriteIntoDebugLogger("getPollingRate() Error: " + str(e)) | module function_definition identifier parameters identifier block print_statement binary_operator string string_start string_content string_end attribute identifier identifier expression_statement assignment identifier subscript call attribute identifier identifier argument_list string string_start string_content string_end integer try_statement block expression_statement assignment identifier binary_operator call identifier argument_list identifier integer expression_statement assignment identifier call identifier argument_list binary_operator call identifier argument_list identifier integer integer return_statement conditional_expression identifier comparison_operator identifier identifier identifier except_clause identifier identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end call identifier argument_list identifier | get data polling rate for sleepy end device |
def clone(url, tmpdir=None):
if tmpdir is None:
tmpdir = tempfile.mkdtemp()
name = os.path.basename(url).replace('.git', '')
dest = '%s/%s' %(tmpdir,name)
return_code = os.system('git clone %s %s' %(url,dest))
if return_code == 0:
return dest
bot.error('Error cloning repo.')
sys.exit(return_code) | module function_definition identifier parameters identifier default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute call attribute attribute identifier identifier identifier argument_list identifier identifier argument_list string string_start string_content string_end string string_start string_end expression_statement assignment identifier binary_operator string string_start string_content string_end tuple identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier if_statement comparison_operator identifier integer block return_statement identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier | clone a repository from Github |
def after_third_friday(day=None):
day = day if day is not None else datetime.datetime.now()
now = day.replace(day=1, hour=16, minute=0, second=0, microsecond=0)
now += relativedelta.relativedelta(weeks=2, weekday=relativedelta.FR)
return day > now | module function_definition identifier parameters default_parameter identifier none block expression_statement assignment identifier conditional_expression identifier comparison_operator identifier none call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier integer keyword_argument identifier integer keyword_argument identifier integer keyword_argument identifier integer keyword_argument identifier integer expression_statement augmented_assignment identifier call attribute identifier identifier argument_list keyword_argument identifier integer keyword_argument identifier attribute identifier identifier return_statement comparison_operator identifier identifier | check if day is after month's 3rd friday |
def find_subclass(cls, name):
if name == cls.__name__:
return cls
for sc in cls.__sub_classes__:
r = sc.find_subclass(name)
if r != None:
return r | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block return_statement identifier for_statement identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier none block return_statement identifier | Find a subclass with a given name |
def calculate_tree_length(self):
tree_length = 0
for ext in self.tree:
tree_length += len(ext) + 2
for relpath in self.tree[ext]:
tree_length += len(relpath) + 2
for filename in self.tree[ext][relpath]:
tree_length += len(filename) + 1 + 18
return tree_length + 1 | module function_definition identifier parameters identifier block expression_statement assignment identifier integer for_statement identifier attribute identifier identifier block expression_statement augmented_assignment identifier binary_operator call identifier argument_list identifier integer for_statement identifier subscript attribute identifier identifier identifier block expression_statement augmented_assignment identifier binary_operator call identifier argument_list identifier integer for_statement identifier subscript subscript attribute identifier identifier identifier identifier block expression_statement augmented_assignment identifier binary_operator binary_operator call identifier argument_list identifier integer integer return_statement binary_operator identifier integer | Walks the tree and calculate the tree length |
def on_new_request(self, task):
task['status'] = self.taskdb.ACTIVE
self.insert_task(task)
self.put_task(task)
project = task['project']
self._cnt['5m'].event((project, 'pending'), +1)
self._cnt['1h'].event((project, 'pending'), +1)
self._cnt['1d'].event((project, 'pending'), +1)
self._cnt['all'].event((project, 'pending'), +1)
logger.info('new task %(project)s:%(taskid)s %(url)s', task)
return task | module function_definition identifier parameters identifier identifier block expression_statement assignment subscript identifier string string_start string_content string_end attribute attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement call attribute subscript attribute identifier identifier string string_start string_content string_end identifier argument_list tuple identifier string string_start string_content string_end unary_operator integer expression_statement call attribute subscript attribute identifier identifier string string_start string_content string_end identifier argument_list tuple identifier string string_start string_content string_end unary_operator integer expression_statement call attribute subscript attribute identifier identifier string string_start string_content string_end identifier argument_list tuple identifier string string_start string_content string_end unary_operator integer expression_statement call attribute subscript attribute identifier identifier string string_start string_content string_end identifier argument_list tuple identifier string string_start string_content string_end unary_operator integer expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier return_statement identifier | Called when a new request is arrived |
def _decode_request(self, encoded_request):
obj = self.serializer.loads(encoded_request)
return request_from_dict(obj, self.spider) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier return_statement call identifier argument_list identifier attribute identifier identifier | Decode an request previously encoded |
def authorized_tenants(self):
if self.is_authenticated and self._authorized_tenants is None:
endpoint = self.endpoint
try:
self._authorized_tenants = utils.get_project_list(
user_id=self.id,
auth_url=endpoint,
token=self.unscoped_token,
is_federated=self.is_federated)
except (keystone_exceptions.ClientException,
keystone_exceptions.AuthorizationFailure):
LOG.exception('Unable to retrieve project list.')
return self._authorized_tenants or [] | module function_definition identifier parameters identifier block if_statement boolean_operator attribute identifier identifier comparison_operator attribute identifier identifier none block expression_statement assignment identifier attribute identifier identifier try_statement block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier except_clause tuple attribute identifier identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement boolean_operator attribute identifier identifier list | Returns a memoized list of tenants this user may access. |
def get(self, uri):
return self.send_request(
"{0}://{1}:{2}{3}{4}".format(
self.get_protocol(),
self.host,
self.port,
uri,
self.client_id
)
) | module function_definition identifier parameters identifier identifier block return_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier identifier attribute identifier identifier | Send a request to given uri. |
def auth_oauth2(self) -> dict:
oauth_data = {
'client_id': self._app_id,
'display': 'mobile',
'response_type': 'token',
'scope': '+66560',
'v': self.API_VERSION
}
response = self.post(self.OAUTH_URL, oauth_data)
url_params = get_url_params(response.url, fragment=True)
if 'access_token' in url_params:
return url_params
action_url = get_base_url(response.text)
if action_url:
response = self.get(action_url)
return get_url_params(response.url)
response_json = response.json()
if 'error' in response_json['error']:
exception_msg = '{}: {}'.format(response_json['error'],
response_json['error_description'])
raise VVKAuthException(exception_msg) | module function_definition identifier parameters identifier type identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier keyword_argument identifier true if_statement comparison_operator string string_start string_content string_end identifier block return_statement identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement call identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator string string_start string_content string_end subscript identifier string string_start string_content string_end block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end raise_statement call identifier argument_list identifier | Authorizes a user by OAuth2 to get access token |
def _has_fr_route(self):
if self._should_use_fr_error_handler():
return True
if not request.url_rule:
return False
return self.owns_endpoint(request.url_rule.endpoint) | module function_definition identifier parameters identifier block if_statement call attribute identifier identifier argument_list block return_statement true if_statement not_operator attribute identifier identifier block return_statement false return_statement call attribute identifier identifier argument_list attribute attribute identifier identifier identifier | Encapsulating the rules for whether the request was to a Flask endpoint |
def refreshLabels( self ):
itemCount = self.itemCount()
title = self.itemsTitle()
if ( not itemCount ):
self._itemsLabel.setText(' %s per page' % title)
else:
msg = ' %s per page, %i %s total' % (title, itemCount, title)
self._itemsLabel.setText(msg) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list if_statement parenthesized_expression not_operator identifier block expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content string_end identifier else_clause block expression_statement assignment identifier binary_operator string string_start string_content string_end tuple identifier identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Refreshes the labels to display the proper title and count information. |
def create_mysql_cymysql(username, password, host, port, database, **kwargs):
return create_engine(
_create_mysql_cymysql(username, password, host, port, database),
**kwargs
) | module function_definition identifier parameters identifier identifier identifier identifier identifier dictionary_splat_pattern identifier block return_statement call identifier argument_list call identifier argument_list identifier identifier identifier identifier identifier dictionary_splat identifier | create an engine connected to a mysql database using cymysql. |
def _get_dis_func(self, union):
union_types = union.__args__
if NoneType in union_types:
union_types = tuple(
e for e in union_types if e is not NoneType
)
if not all(hasattr(e, "__attrs_attrs__") for e in union_types):
raise ValueError(
"Only unions of attr classes supported "
"currently. Register a loads hook manually."
)
return create_uniq_field_dis_func(*union_types) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator identifier identifier block expression_statement assignment identifier call identifier generator_expression identifier for_in_clause identifier identifier if_clause comparison_operator identifier identifier if_statement not_operator call identifier generator_expression call identifier argument_list identifier string string_start string_content string_end for_in_clause identifier identifier block raise_statement call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end return_statement call identifier argument_list list_splat identifier | Fetch or try creating a disambiguation function for a union. |
def chunk_iter(iterable, chunk_size):
while True:
chunk = []
try:
for _ in range(chunk_size): chunk.append(next(iterable))
yield chunk
except StopIteration:
if chunk: yield chunk
break | module function_definition identifier parameters identifier identifier block while_statement true block expression_statement assignment identifier list try_statement block for_statement identifier call identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier expression_statement yield identifier except_clause identifier block if_statement identifier block expression_statement yield identifier break_statement | A generator that yields chunks of iterable, chunk_size at a time. |
def _cdist_scipy(x, y, exponent=1):
metric = 'euclidean'
if exponent != 1:
metric = 'sqeuclidean'
distances = _spatial.distance.cdist(x, y, metric=metric)
if exponent != 1:
distances **= exponent / 2
return distances | module function_definition identifier parameters identifier identifier default_parameter identifier integer block expression_statement assignment identifier string string_start string_content string_end if_statement comparison_operator identifier integer block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier keyword_argument identifier identifier if_statement comparison_operator identifier integer block expression_statement augmented_assignment identifier binary_operator identifier integer return_statement identifier | Pairwise distance between the points in two sets. |
def MarkDone(self, responses):
client_id = responses.request.client_id
self.AddResultsToCollection(responses, client_id)
self.MarkClientDone(client_id) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list identifier | Mark a client as done. |
def update(self):
con = self.subpars.pars.control
self(con.ypoints.shape[0]) | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute attribute attribute identifier identifier identifier identifier expression_statement call identifier argument_list subscript attribute attribute identifier identifier identifier integer | Determine the number of branches |
def _assert_transition(self, event):
state = self.domain.state()[0]
if event not in STATES_MAP[state]:
raise RuntimeError("State transition %s not allowed" % event) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier subscript call attribute attribute identifier identifier identifier argument_list integer if_statement comparison_operator identifier subscript identifier identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier | Asserts the state transition validity. |
def _invoke_callbacks(self, *args, **kwargs):
for callback in self._done_callbacks:
_helpers.safe_invoke_callback(callback, *args, **kwargs) | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier list_splat identifier dictionary_splat identifier | Invoke all done callbacks. |
def send(self, enc, load, tries=1, timeout=60):
payload = {'enc': enc}
payload['load'] = load
pkg = self.serial.dumps(payload)
self.socket.send(pkg)
self.poller.register(self.socket, zmq.POLLIN)
tried = 0
while True:
polled = self.poller.poll(timeout * 1000)
tried += 1
if polled:
break
if tries > 1:
log.info(
'SaltReqTimeoutError: after %s seconds. (Try %s of %s)',
timeout, tried, tries
)
if tried >= tries:
self.clear_socket()
raise SaltReqTimeoutError(
'SaltReqTimeoutError: after {0} seconds, ran {1} '
'tries'.format(timeout * tried, tried)
)
return self.serial.loads(self.socket.recv()) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier integer default_parameter identifier integer block expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement assignment identifier integer while_statement true block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list binary_operator identifier integer expression_statement augmented_assignment identifier integer if_statement identifier block break_statement if_statement comparison_operator identifier integer block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier identifier if_statement comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list 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 binary_operator identifier identifier identifier return_statement call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list | Takes two arguments, the encryption type and the base payload |
def list_buckets(self, offset=0, limit=100):
if limit > 100:
raise Exception("Zenobase can't handle limits over 100")
return self._get("/users/{}/buckets/?order=label&offset={}&limit={}".format(self.client_id, offset, limit)) | module function_definition identifier parameters identifier default_parameter identifier integer default_parameter identifier integer block if_statement comparison_operator identifier integer block raise_statement call identifier argument_list string string_start string_content string_end return_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier identifier identifier | Limit breaks above 100 |
def dump_database(self):
db_file = self.create_file_name(self.databases['source']['name'])
self.print_message("Dumping postgres database '%s' to file '%s'"
% (self.databases['source']['name'], db_file))
self.export_pgpassword('source')
args = [
"pg_dump",
"-Fc",
"--no-acl",
"--no-owner",
"--dbname=%s" % self.databases['source']['name'],
"--file=%s" % db_file,
]
args.extend(self.databases['source']['args'])
subprocess.check_call(args)
return db_file | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list subscript subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple subscript subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end binary_operator string string_start string_content string_end subscript subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end binary_operator string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list subscript subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Create dumpfile from postgres database, and return filename. |
def __get_user(self):
storage = object.__getattribute__(self, '_LazyUser__storage')
user = getattr(self.__auth, 'get_user')()
setattr(storage, self.__user_name, user)
return user | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier string string_start string_content string_end expression_statement assignment identifier call call identifier argument_list attribute identifier identifier string string_start string_content string_end argument_list expression_statement call identifier argument_list identifier attribute identifier identifier identifier return_statement identifier | Return the real user object. |
def file_resolve(backend, filepath):
recipe = DKRecipeDisk.find_recipe_name()
if recipe is None:
raise click.ClickException('You must be in a recipe folder.')
click.secho("%s - Resolving conflicts" % get_datetime())
for file_to_resolve in filepath:
if not os.path.exists(file_to_resolve):
raise click.ClickException('%s does not exist' % file_to_resolve)
check_and_print(DKCloudCommandRunner.resolve_conflict(file_to_resolve)) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator identifier none block raise_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end call identifier argument_list for_statement identifier identifier block if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block raise_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement call identifier argument_list call attribute identifier identifier argument_list identifier | Mark a conflicted file as resolved, so that a merge can be completed |
def device_changed(self, old_state, new_state):
if (self._mounter.is_addable(new_state)
and not self._mounter.is_addable(old_state)
and not self._mounter.is_removable(old_state)):
self.auto_add(new_state) | module function_definition identifier parameters identifier identifier identifier block if_statement parenthesized_expression boolean_operator boolean_operator call attribute attribute identifier identifier identifier argument_list identifier not_operator call attribute attribute identifier identifier identifier argument_list identifier not_operator call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier | Mount newly mountable devices. |
def _find_recorder(recorder, tokens, index):
if recorder is None:
for recorder_factory in _RECORDERS:
recorder = recorder_factory.maybe_start_recording(tokens,
index)
if recorder is not None:
return recorder
return recorder | module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator identifier none block for_statement identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier if_statement comparison_operator identifier none block return_statement identifier return_statement identifier | Given a current recorder and a token index, try to find a recorder. |
def initiate_forgot_password(self):
params = {
'ClientId': self.client_id,
'Username': self.username
}
self._add_secret_hash(params, 'SecretHash')
self.client.forgot_password(**params) | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list dictionary_splat identifier | Sends a verification code to the user to use to change their password. |
def get(self, name):
lxc_meta_path = self._service.lxc_path(name,
constants.LXC_META_FILENAME)
meta = LXCMeta.load_from_file(lxc_meta_path)
lxc = self._loader.load(name, meta)
return lxc | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier return_statement identifier | Retrieves a single LXC by name |
def _normalizeCursor(self, x, y):
width, height = self.get_size()
assert width != 0 and height != 0, 'can not print on a console with a width or height of zero'
while x >= width:
x -= width
y += 1
while y >= height:
if self._scrollMode == 'scroll':
y -= 1
self.scroll(0, -1)
elif self._scrollMode == 'error':
self._cursor = (0, 0)
raise TDLError('Cursor has reached the end of the console')
return (x, y) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list assert_statement boolean_operator comparison_operator identifier integer comparison_operator identifier integer string string_start string_content string_end while_statement comparison_operator identifier identifier block expression_statement augmented_assignment identifier identifier expression_statement augmented_assignment identifier integer while_statement comparison_operator identifier identifier block if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement augmented_assignment identifier integer expression_statement call attribute identifier identifier argument_list integer unary_operator integer elif_clause comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement assignment attribute identifier identifier tuple integer integer raise_statement call identifier argument_list string string_start string_content string_end return_statement tuple identifier identifier | return the normalized the cursor position. |
def toggle_deriv(self, evt=None, value=None):
"toggle derivative of data"
if value is None:
self.conf.data_deriv = not self.conf.data_deriv
expr = self.conf.data_expr or ''
if self.conf.data_deriv:
expr = "deriv(%s)" % expr
self.write_message("plotting %s" % expr, panel=0)
self.conf.process_data() | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none block expression_statement string string_start string_content string_end if_statement comparison_operator identifier none block expression_statement assignment attribute attribute identifier identifier identifier not_operator attribute attribute identifier identifier identifier expression_statement assignment identifier boolean_operator attribute attribute identifier identifier identifier string string_start string_end if_statement attribute attribute identifier identifier identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier keyword_argument identifier integer expression_statement call attribute attribute identifier identifier identifier argument_list | toggle derivative of data |
def convert(self,label,units=None,conversion_function=convert_time):
label_no = self.get_label_no(label)
new_label, new_column = self.get_converted(label_no,units,conversion_function)
labels = [LabelDimension(l) for l in self.labels]
labels[label_no] = new_label
matrix = self.matrix.copy()
matrix[:,label_no] = new_column
return LabeledMatrix(matrix,labels) | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier identifier identifier expression_statement assignment identifier list_comprehension call identifier argument_list identifier for_in_clause identifier attribute identifier identifier expression_statement assignment subscript identifier identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment subscript identifier slice identifier identifier return_statement call identifier argument_list identifier identifier | converts a dimension in place |
def validate_config(self):
if self.location == 'localhost':
if 'browserName' not in self.config.keys():
msg = "Add the 'browserName' in your local_config: e.g.: 'Firefox', 'Chrome', 'Safari'"
self.runner.critical_log(msg)
raise BromeBrowserConfigException(msg)
elif self.location == 'ec2':
self.validate_ec2_browser_config()
elif self.location == 'virtualbox':
self.validate_virtualbox_config() | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block if_statement comparison_operator string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list block expression_statement assignment identifier string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list identifier raise_statement call identifier argument_list identifier elif_clause comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list elif_clause comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list | Validate that the browser config contains all the needed config |
def validate(self, value, redis):
value = super().validate(value, redis)
if is_hashed(value):
return value
return make_password(value) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute call identifier argument_list identifier argument_list identifier identifier if_statement call identifier argument_list identifier block return_statement identifier return_statement call identifier argument_list identifier | hash passwords given via http |
def local_address(self):
if not self._local_address:
self._local_address = self.proto.reader._transport.get_extra_info('sockname')
if len(self._local_address) == 4:
self._local_address = self._local_address[:2]
return self._local_address | module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block expression_statement assignment attribute identifier identifier call attribute attribute attribute attribute identifier identifier identifier identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator call identifier argument_list attribute identifier identifier integer block expression_statement assignment attribute identifier identifier subscript attribute identifier identifier slice integer return_statement attribute identifier identifier | Local endpoint address as a tuple |
def make_node(cls, node, *args):
if node is None:
node = cls()
assert isinstance(node, SymbolARGUMENT) or isinstance(node, cls)
if not isinstance(node, cls):
return cls.make_node(None, node, *args)
for arg in args:
assert isinstance(arg, SymbolARGUMENT)
node.appendChild(arg)
return node | module function_definition identifier parameters identifier identifier list_splat_pattern identifier block if_statement comparison_operator identifier none block expression_statement assignment identifier call identifier argument_list assert_statement boolean_operator call identifier argument_list identifier identifier call identifier argument_list identifier identifier if_statement not_operator call identifier argument_list identifier identifier block return_statement call attribute identifier identifier argument_list none identifier list_splat identifier for_statement identifier identifier block assert_statement call identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | This will return a node with an argument_list. |
def multidispatch(*, nargs=None, nouts=None):
def wrapper(f):
return wraps(f)(MultiDispatchFunction(f, nargs=nargs, nouts=nouts))
return wrapper | module function_definition identifier parameters keyword_separator default_parameter identifier none default_parameter identifier none block function_definition identifier parameters identifier block return_statement call call identifier argument_list identifier argument_list call identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier return_statement identifier | multidispatch decorate of both functools.singledispatch and func |
def reference_fasta(self):
if self._db_location:
ref_files = glob.glob(os.path.join(self._db_location, "*", self._REF_FASTA))
if ref_files:
return ref_files[0] | module function_definition identifier parameters identifier block if_statement attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list attribute identifier identifier string string_start string_content string_end attribute identifier identifier if_statement identifier block return_statement subscript identifier integer | Absolute path to the fasta file with EricScript reference data. |
def device_added(self, device):
if not self._mounter.is_handleable(device):
return
if self._has_actions('device_added'):
GLib.timeout_add(500, self._device_added, device)
else:
self._device_added(device) | module function_definition identifier parameters identifier identifier block if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block return_statement if_statement call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list integer attribute identifier identifier identifier else_clause block expression_statement call attribute identifier identifier argument_list identifier | Show discovery notification for specified device object. |
def vertex_normals(vertices, faces):
def normalize_v3(arr):
lens = np.sqrt(arr[:, 0]**2 + arr[:, 1]**2 + arr[:, 2]**2)
arr /= lens[:, np.newaxis]
tris = vertices[faces]
facenorms = np.cross(tris[::, 1] - tris[::, 0], tris[::, 2] - tris[::, 0])
normalize_v3(facenorms)
norm = np.zeros(vertices.shape, dtype=vertices.dtype)
norm[faces[:, 0]] += facenorms
norm[faces[:, 1]] += facenorms
norm[faces[:, 2]] += facenorms
normalize_v3(norm)
return norm | module function_definition identifier parameters identifier identifier block function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator binary_operator binary_operator subscript identifier slice integer integer binary_operator subscript identifier slice integer integer binary_operator subscript identifier slice integer integer expression_statement augmented_assignment identifier subscript identifier slice attribute identifier identifier expression_statement assignment identifier subscript identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator subscript identifier slice integer subscript identifier slice integer binary_operator subscript identifier slice integer subscript identifier slice integer expression_statement call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier attribute identifier identifier expression_statement augmented_assignment subscript identifier subscript identifier slice integer identifier expression_statement augmented_assignment subscript identifier subscript identifier slice integer identifier expression_statement augmented_assignment subscript identifier subscript identifier slice integer identifier expression_statement call identifier argument_list identifier return_statement identifier | Calculates the normals of a triangular mesh |
def resample(self, inds):
new = copy.deepcopy(self)
for arr in self.arrays:
x = getattr(new, arr)
setattr(new, arr, x[inds])
return new | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier for_statement identifier attribute identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement call identifier argument_list identifier identifier subscript identifier identifier return_statement identifier | Returns copy of constraint, with mask rearranged according to indices |
def _mod_bufsize_linux(iface, *args, **kwargs):
ret = {'result': False,
'comment': 'Requires rx=<val> tx==<val> rx-mini=<val> and/or rx-jumbo=<val>'}
cmd = '/sbin/ethtool -G ' + iface
if not kwargs:
return ret
if args:
ret['comment'] = 'Unknown arguments: ' + ' '.join([six.text_type(item)
for item in args])
return ret
eargs = ''
for kw in ['rx', 'tx', 'rx-mini', 'rx-jumbo']:
value = kwargs.get(kw)
if value is not None:
eargs += ' ' + kw + ' ' + six.text_type(value)
if not eargs:
return ret
cmd += eargs
out = __salt__['cmd.run'](cmd)
if out:
ret['comment'] = out
else:
ret['comment'] = eargs.strip()
ret['result'] = True
return ret | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end false pair string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier binary_operator string string_start string_content string_end identifier if_statement not_operator identifier block return_statement identifier if_statement identifier block expression_statement assignment subscript identifier string string_start string_content string_end binary_operator string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list list_comprehension call attribute identifier identifier argument_list identifier for_in_clause identifier identifier return_statement identifier expression_statement assignment identifier string string_start string_end for_statement identifier list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier none block expression_statement augmented_assignment identifier binary_operator binary_operator binary_operator string string_start string_content string_end identifier string string_start string_content string_end call attribute identifier identifier argument_list identifier if_statement not_operator identifier block return_statement identifier expression_statement augmented_assignment identifier identifier expression_statement assignment identifier call subscript identifier string string_start string_content string_end argument_list identifier if_statement identifier block expression_statement assignment subscript identifier string string_start string_content string_end identifier else_clause block expression_statement assignment subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list expression_statement assignment subscript identifier string string_start string_content string_end true return_statement identifier | Modify network interface buffer sizes using ethtool |
def devices(self):
self.verify_integrity()
if session.get('u2f_device_management_authorized', False):
if request.method == 'GET':
return jsonify(self.get_devices()), 200
elif request.method == 'DELETE':
response = self.remove_device(request.json)
if response['status'] == 'ok':
return jsonify(response), 200
else:
return jsonify(response), 404
return jsonify({'status': 'failed', 'error': 'Unauthorized!'}), 401 | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list if_statement call attribute identifier identifier argument_list string string_start string_content string_end false block if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block return_statement expression_list call identifier argument_list call attribute identifier identifier argument_list integer elif_clause comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier if_statement comparison_operator subscript identifier string string_start string_content string_end string string_start string_content string_end block return_statement expression_list call identifier argument_list identifier integer else_clause block return_statement expression_list call identifier argument_list identifier integer return_statement expression_list call identifier argument_list dictionary pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end integer | Manages users enrolled u2f devices |
def check_deps(deps):
if not isinstance(deps, list):
deps = [deps]
checks = list(Environment.has_apps(deps))
if not all(checks):
for name, available in list(dict(zip(deps, checks)).items()):
if not available:
error_msg = "The required application/dependency '{0}'" \
" isn't available.".format(name)
raise SystemError(error_msg) | module function_definition identifier parameters identifier block if_statement not_operator call identifier argument_list identifier identifier block expression_statement assignment identifier list identifier expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list identifier if_statement not_operator call identifier argument_list identifier block for_statement pattern_list identifier identifier call identifier argument_list call attribute call identifier argument_list call identifier argument_list identifier identifier identifier argument_list block if_statement not_operator identifier block expression_statement assignment identifier call attribute concatenated_string string string_start string_content string_end string string_start string_content string_end identifier argument_list identifier raise_statement call identifier argument_list identifier | check whether specific requirements are available. |
def extract_worker_exc(*arg, **kw):
_self = arg[0]
if not isinstance(_self, StrategyBase):
return
for _worker_prc, _main_q, _rslt_q in _self._workers:
_task = _worker_prc._task
if _task.action == 'setup':
continue
while True:
try:
_exc = _rslt_q.get(block=False, interceptor=True)
RESULT[_task.name].add(_exc)
except Empty:
break | module function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier subscript identifier integer if_statement not_operator call identifier argument_list identifier identifier block return_statement for_statement pattern_list identifier identifier identifier attribute identifier identifier block expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block continue_statement while_statement true block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier false keyword_argument identifier true expression_statement call attribute subscript identifier attribute identifier identifier identifier argument_list identifier except_clause identifier block break_statement | Get exception added by worker |
def check_dependency(self, operation, dependency):
if isinstance(dependency[1], SQLBlob):
return dependency[3] == operation
return super(MigrationAutodetector, self).check_dependency(operation, dependency) | module function_definition identifier parameters identifier identifier identifier block if_statement call identifier argument_list subscript identifier integer identifier block return_statement comparison_operator subscript identifier integer identifier return_statement call attribute call identifier argument_list identifier identifier identifier argument_list identifier identifier | Enhances default behavior of method by checking dependency for matching operation. |
def user_feature_update(self, userid, payload):
response, status_code = self.__pod__.User.post_v1_admin_user_uid_features_update(
sessionToken=self.__session__,
uid=userid,
payload=payload
).result()
self.logger.debug('%s: %s' % (status_code, response))
return status_code, response | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment pattern_list identifier identifier call attribute call attribute attribute attribute identifier identifier identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier return_statement expression_list identifier identifier | update features by user id |
def task_master(self):
if self._task_master is None:
self._task_master = build_task_master(self.config)
return self._task_master | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier return_statement attribute identifier identifier | A `TaskMaster` object for manipulating work |
def annotate_snapshot(self, snapshot):
if hasattr(snapshot, 'classes'):
return
snapshot.classes = {}
for classname in list(self.index.keys()):
total = 0
active = 0
merged = Asized(0, 0)
for tobj in self.index[classname]:
_merge_objects(snapshot.timestamp, merged, tobj)
total += tobj.get_size_at_time(snapshot.timestamp)
if tobj.birth < snapshot.timestamp and \
(tobj.death is None or tobj.death > snapshot.timestamp):
active += 1
try:
pct = total * 100.0 / snapshot.total
except ZeroDivisionError:
pct = 0
try:
avg = total / active
except ZeroDivisionError:
avg = 0
snapshot.classes[classname] = dict(sum=total,
avg=avg,
pct=pct,
active=active)
snapshot.classes[classname]['merged'] = merged | module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list identifier string string_start string_content string_end block return_statement expression_statement assignment attribute identifier identifier dictionary for_statement identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list block expression_statement assignment identifier integer expression_statement assignment identifier integer expression_statement assignment identifier call identifier argument_list integer integer for_statement identifier subscript attribute identifier identifier identifier block expression_statement call identifier argument_list attribute identifier identifier identifier identifier expression_statement augmented_assignment identifier call attribute identifier identifier argument_list attribute identifier identifier if_statement boolean_operator comparison_operator attribute identifier identifier attribute identifier identifier line_continuation parenthesized_expression boolean_operator comparison_operator attribute identifier identifier none comparison_operator attribute identifier identifier attribute identifier identifier block expression_statement augmented_assignment identifier integer try_statement block expression_statement assignment identifier binary_operator binary_operator identifier float attribute identifier identifier except_clause identifier block expression_statement assignment identifier integer try_statement block expression_statement assignment identifier binary_operator identifier identifier except_clause identifier block expression_statement assignment identifier integer expression_statement assignment subscript attribute identifier identifier identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier expression_statement assignment subscript subscript attribute identifier identifier identifier string string_start string_content string_end identifier | Store additional statistical data in snapshot. |
def create_result(self, env_name, other_val, meta, val, dividers):
args = [env_name]
if other_val is NotSpecified:
other_val = None
if not dividers:
args.extend([None, None])
elif dividers[0] == ':':
args.extend([other_val, None])
elif dividers[0] == '=':
args.extend([None, other_val])
return Environment(*args) | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier block expression_statement assignment identifier list identifier if_statement comparison_operator identifier identifier block expression_statement assignment identifier none if_statement not_operator identifier block expression_statement call attribute identifier identifier argument_list list none none elif_clause comparison_operator subscript identifier integer string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list list identifier none elif_clause comparison_operator subscript identifier integer string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list list none identifier return_statement call identifier argument_list list_splat identifier | Set default_val and set_val depending on the seperator |
def to_utf8(path, output_path=None):
if output_path is None:
basename, ext = os.path.splitext(path)
output_path = basename + "-UTF8Encode" + ext
text = smartread(path)
write(text, output_path) | module function_definition identifier parameters identifier default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier binary_operator binary_operator identifier string string_start string_content string_end identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement call identifier argument_list identifier identifier | Convert any text file to utf8 encoding. |
def _get_metrics_to_collect(self, instance_key, additional_metrics):
if instance_key not in self.metrics_to_collect_by_instance:
self.metrics_to_collect_by_instance[instance_key] = self._build_metric_list_to_collect(additional_metrics)
return self.metrics_to_collect_by_instance[instance_key] | module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment subscript attribute identifier identifier identifier call attribute identifier identifier argument_list identifier return_statement subscript attribute identifier identifier identifier | Return and cache the list of metrics to collect. |
def merge_pres_feats(pres, features):
sub = []
for psub, fsub in zip(pres, features):
exp = []
for pexp, fexp in zip(psub, fsub):
lst = []
for p, f in zip(pexp, fexp):
p.update(f)
lst.append(p)
exp.append(lst)
sub.append(exp)
return sub | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list for_statement pattern_list identifier identifier call identifier argument_list identifier identifier block expression_statement assignment identifier list for_statement pattern_list identifier identifier call identifier argument_list identifier identifier block expression_statement assignment identifier list for_statement pattern_list identifier identifier call identifier argument_list identifier identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Helper function to merge pres and features to support legacy features argument |
def poisson_consensus_se(data, k, n_runs=10, **se_params):
clusters = []
for i in range(n_runs):
assignments, means = poisson_cluster(data, k)
clusters.append(assignments)
clusterings = np.vstack(clusters)
consensus = CE.cluster_ensembles(clusterings, verbose=False, N_clusters_max=k)
init_m, init_w = nmf_init(data, consensus, k, 'basic')
M, W, ll = poisson_estimate_state(data, k, init_means=init_m, init_weights=init_w, **se_params)
return M, W, ll | module function_definition identifier parameters identifier identifier default_parameter identifier integer dictionary_splat_pattern identifier block expression_statement assignment identifier list for_statement identifier call identifier argument_list identifier block expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier false keyword_argument identifier identifier expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier identifier identifier string string_start string_content string_end expression_statement assignment pattern_list identifier identifier identifier call identifier argument_list identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier dictionary_splat identifier return_statement expression_list identifier identifier identifier | Initializes Poisson State Estimation using a consensus Poisson clustering. |
def replace(parent, idx, value, check_value=_NO_VAL):
if isinstance(parent, dict):
if idx not in parent:
raise JSONPatchError("Item does not exist")
elif isinstance(parent, list):
idx = int(idx)
if idx < 0 or idx >= len(parent):
raise JSONPatchError("List index out of range")
if check_value is not _NO_VAL:
if parent[idx] != check_value:
raise JSONPatchError("Check value did not pass")
parent[idx] = value | module function_definition identifier parameters identifier identifier identifier default_parameter identifier identifier block if_statement call identifier argument_list identifier identifier block if_statement comparison_operator identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end elif_clause call identifier argument_list identifier identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement boolean_operator comparison_operator identifier integer comparison_operator identifier call identifier argument_list identifier block raise_statement call identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier identifier block if_statement comparison_operator subscript identifier identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment subscript identifier identifier identifier | Replace a value in a dict. |
def config(self, config):
for section, data in config.items():
for variable, value in data.items():
self.set_value(section, variable, value) | module function_definition identifier parameters identifier identifier block for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list identifier identifier identifier | Set config values from config dictionary. |
def start_subscribe_worker(self, loop):
url = self.base_url + "api/0.1.0/subscribe"
task = loop.create_task(self.asynchronously_get_data(url + "?name={0}".format(self.entity_id)))
asyncio.set_event_loop(loop)
loop.run_until_complete(task)
self.event_loop = loop | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier binary_operator attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list binary_operator identifier call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier identifier | Switch to new event loop as a thread and run until complete. |
def build_groups(self, tokens):
groups = {}
for token in tokens:
match_type = MatchType.start if token.group_end else MatchType.single
groups[token.group_start] = (token, match_type)
if token.group_end:
groups[token.group_end] = (token, MatchType.end)
return groups | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary for_statement identifier identifier block expression_statement assignment identifier conditional_expression attribute identifier identifier attribute identifier identifier attribute identifier identifier expression_statement assignment subscript identifier attribute identifier identifier tuple identifier identifier if_statement attribute identifier identifier block expression_statement assignment subscript identifier attribute identifier identifier tuple identifier attribute identifier identifier return_statement identifier | Build dict of groups from list of tokens |
def subtract(self, jobShape):
self.shape = Shape(self.shape.wallTime,
self.shape.memory - jobShape.memory,
self.shape.cores - jobShape.cores,
self.shape.disk - jobShape.disk,
self.shape.preemptable) | module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier call identifier argument_list attribute attribute identifier identifier identifier binary_operator attribute attribute identifier identifier identifier attribute identifier identifier binary_operator attribute attribute identifier identifier identifier attribute identifier identifier binary_operator attribute attribute identifier identifier identifier attribute identifier identifier attribute attribute identifier identifier identifier | Subtracts the resources necessary to run a jobShape from the reservation. |
def revert(self):
if self.filepath:
if path.isfile(self.filepath):
serialised_file = open(self.filepath, "r")
try:
self.state = json.load(serialised_file)
except ValueError:
print("No JSON information could be read from the persistence file - could be empty: %s" % self.filepath)
self.state = {}
finally:
serialised_file.close()
else:
print("The persistence file has not yet been created or does not exist, so the state cannot be read from it yet.")
else:
print("Filepath to the persistence file is not set. State cannot be read.")
return False | module function_definition identifier parameters identifier block if_statement attribute identifier identifier block if_statement call attribute identifier identifier argument_list attribute identifier identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier string string_start string_content string_end try_statement block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier except_clause identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier expression_statement assignment attribute identifier identifier dictionary finally_clause block expression_statement call attribute identifier identifier argument_list else_clause block expression_statement call identifier argument_list string string_start string_content string_end else_clause block expression_statement call identifier argument_list string string_start string_content string_end return_statement false | Revert the state to the version stored on disc. |
def appointment(self):
return django_apps.get_model(self.appointment_model).objects.get(
pk=self.request.GET.get("appointment")
) | module function_definition identifier parameters identifier block return_statement call attribute attribute call attribute identifier identifier argument_list attribute identifier identifier identifier identifier argument_list keyword_argument identifier call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end | Returns the appointment instance for this request or None. |
def select(self, choice_scores):
min_num_scores = min([len(s) for s in choice_scores.values()])
if min_num_scores >= K_MIN:
logger.info('{klass}: using Best K bandit selection'.format(klass=type(self).__name__))
reward_func = self.compute_rewards
else:
logger.warning(
'{klass}: Not enough choices to do K-selection; using plain UCB1'
.format(klass=type(self).__name__))
reward_func = super(RecentKReward, self).compute_rewards
choice_rewards = {}
for choice, scores in choice_scores.items():
if choice not in self.choices:
continue
choice_rewards[choice] = reward_func(scores)
return self.bandit(choice_rewards) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list list_comprehension call identifier argument_list identifier for_in_clause identifier call attribute identifier identifier argument_list if_statement comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier attribute call identifier argument_list identifier identifier expression_statement assignment identifier attribute identifier identifier else_clause block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier attribute call identifier argument_list identifier identifier expression_statement assignment identifier attribute call identifier argument_list identifier identifier identifier expression_statement assignment identifier dictionary for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block if_statement comparison_operator identifier attribute identifier identifier block continue_statement expression_statement assignment subscript identifier identifier call identifier argument_list identifier return_statement call attribute identifier identifier argument_list identifier | Use the top k learner's scores for usage in rewards for the bandit calculation |
def __updateRequest(self, rect, dy):
if dy:
self.scroll(0, dy)
elif self._countCache[0] != self._qpart.blockCount() or \
self._countCache[1] != self._qpart.textCursor().block().lineCount():
blockHeight = self._qpart.blockBoundingRect(self._qpart.firstVisibleBlock()).height()
self.update(0, rect.y(), self.width(), rect.height() + blockHeight)
self._countCache = (self._qpart.blockCount(), self._qpart.textCursor().block().lineCount())
if rect.contains(self._qpart.viewport().rect()):
self._qpart.updateViewportMargins() | module function_definition identifier parameters identifier identifier identifier block if_statement identifier block expression_statement call attribute identifier identifier argument_list integer identifier elif_clause boolean_operator comparison_operator subscript attribute identifier identifier integer call attribute attribute identifier identifier identifier argument_list line_continuation comparison_operator subscript attribute identifier identifier integer call attribute call attribute call attribute attribute identifier identifier identifier argument_list identifier argument_list identifier argument_list block expression_statement assignment identifier call attribute call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier argument_list expression_statement call attribute identifier identifier argument_list integer call attribute identifier identifier argument_list call attribute identifier identifier argument_list binary_operator call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier tuple call attribute attribute identifier identifier identifier argument_list call attribute call attribute call attribute attribute identifier identifier identifier argument_list identifier argument_list identifier argument_list if_statement call attribute identifier identifier argument_list call attribute call attribute attribute identifier identifier identifier argument_list identifier argument_list block expression_statement call attribute attribute identifier identifier identifier argument_list | Repaint line number area if necessary |
def check_matrix(m):
if m.shape != (4, 4):
raise ValueError("The argument must be a 4x4 array.")
if max(abs(m[3, 0:3])) > eps:
raise ValueError("The given matrix does not have correct translational part")
if abs(m[3, 3] - 1.0) > eps:
raise ValueError("The lower right element of the given matrix must be 1.0.") | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier tuple integer integer block raise_statement call identifier argument_list string string_start string_content string_end if_statement comparison_operator call identifier argument_list call identifier argument_list subscript identifier integer slice integer integer identifier block raise_statement call identifier argument_list string string_start string_content string_end if_statement comparison_operator call identifier argument_list binary_operator subscript identifier integer integer float identifier block raise_statement call identifier argument_list string string_start string_content string_end | Check the sanity of the given 4x4 transformation matrix |
def add(env, securitygroup_id, network_component, server, interface):
_validate_args(network_component, server, interface)
mgr = SoftLayer.NetworkManager(env.client)
component_id = _get_component_id(env, network_component, server, interface)
ret = mgr.attach_securitygroup_component(securitygroup_id,
component_id)
if not ret:
raise exceptions.CLIAbort("Could not attach network component")
table = formatting.Table(REQUEST_COLUMNS)
table.add_row([ret['requestId']])
env.fout(table) | module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement call identifier argument_list identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier call identifier argument_list identifier identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier if_statement not_operator identifier block raise_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list list subscript identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier | Attach an interface to a security group. |
async def refresh_data(self):
queue = await self.get_queue()
history = await self.get_history()
totals = {}
for k in history:
if k[-4:] == 'size':
totals[k] = self._convert_size(history.get(k))
self.queue = {**totals, **queue} | module function_definition identifier parameters identifier block expression_statement assignment identifier await call attribute identifier identifier argument_list expression_statement assignment identifier await call attribute identifier identifier argument_list expression_statement assignment identifier dictionary for_statement identifier identifier block if_statement comparison_operator subscript identifier slice unary_operator integer string string_start string_content string_end block expression_statement assignment subscript identifier identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier dictionary dictionary_splat identifier dictionary_splat identifier | Refresh the cached SABnzbd queue data |
def stop(self):
self.state = False
with display_manager(self.display) as d:
d.record_disable_context(self.ctx)
d.ungrab_keyboard(X.CurrentTime)
with display_manager(self.display2):
d.record_disable_context(self.ctx)
d.ungrab_keyboard(X.CurrentTime) | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier false 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 expression_statement call attribute identifier identifier argument_list attribute identifier identifier with_statement with_clause with_item call identifier argument_list attribute identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier | Stop listening for keyboard input events. |
def _bdd(node):
try:
bdd = _BDDS[node]
except KeyError:
bdd = _BDDS[node] = BinaryDecisionDiagram(node)
return bdd | module function_definition identifier parameters identifier block try_statement block expression_statement assignment identifier subscript identifier identifier except_clause identifier block expression_statement assignment identifier assignment subscript identifier identifier call identifier argument_list identifier return_statement identifier | Return a unique BDD. |
def add_env(self, name, val):
if name in self.env_vars:
raise KeyError(name)
self.env_vars[name] = val | module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block raise_statement call identifier argument_list identifier expression_statement assignment subscript attribute identifier identifier identifier identifier | Add an environment variable to the docker run invocation |
def snap(self, path=None):
if path is None:
path = "/tmp"
else:
path = path.rstrip("/")
day_dir = datetime.datetime.now().strftime("%d%m%Y")
hour_dir = datetime.datetime.now().strftime("%H%M")
ensure_snapshot_dir(path+"/"+self.cam_id+"/"+day_dir+"/"+hour_dir)
f_path = "{0}/{1}/{2}/{3}/{4}.jpg".format(
path,
self.cam_id,
day_dir,
hour_dir,
datetime.datetime.now().strftime("%S"),
)
urllib.urlretrieve(
'http://{0}/snapshot.cgi?user={1}&pwd={2}'.format(
self.address,
self.user,
self.pswd,
),
f_path,
) | module function_definition identifier parameters identifier default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier string string_start string_content string_end else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute call attribute attribute identifier identifier identifier argument_list identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute call attribute attribute identifier identifier identifier argument_list identifier argument_list string string_start string_content string_end expression_statement call identifier argument_list binary_operator binary_operator binary_operator binary_operator binary_operator binary_operator identifier string string_start string_content string_end attribute identifier identifier string string_start string_content string_end identifier string string_start string_content string_end identifier expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier attribute identifier identifier identifier identifier call attribute call attribute attribute identifier identifier identifier argument_list identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier identifier | Get a snapshot and save it to disk. |
def writeline(self, x, node=None, extra=0):
self.newline(node, extra)
self.write(x) | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier integer block expression_statement call attribute identifier identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list identifier | Combination of newline and write. |
def nPercentile(requestContext, seriesList, n):
assert n, 'The requested percent is required to be greater than 0'
results = []
for s in seriesList:
s_copy = TimeSeries(s.name, s.start, s.end, s.step,
sorted(not_none(s)))
if not s_copy:
continue
perc_val = _getPercentile(s_copy, n)
if perc_val is not None:
name = 'nPercentile(%s, %g)' % (s_copy.name, n)
point_count = int((s.end - s.start)/s.step)
perc_series = TimeSeries(name, s_copy.start, s_copy.end,
s_copy.step, [perc_val] * point_count)
perc_series.pathExpression = name
results.append(perc_series)
return results | module function_definition identifier parameters identifier identifier identifier block assert_statement identifier string string_start string_content string_end expression_statement assignment identifier list for_statement identifier identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier call identifier argument_list call identifier argument_list identifier if_statement not_operator identifier block continue_statement expression_statement assignment identifier call identifier argument_list identifier identifier if_statement comparison_operator identifier none block expression_statement assignment identifier binary_operator string string_start string_content string_end tuple attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list binary_operator parenthesized_expression binary_operator attribute identifier identifier attribute identifier identifier attribute identifier identifier expression_statement assignment identifier call identifier argument_list identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier binary_operator list identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Returns n-percent of each series in the seriesList. |
def _send_textmetrics(metrics):
data = [' '.join(map(six.text_type, metric)) for metric in metrics] + ['']
return '\n'.join(data) | module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator list_comprehension call attribute string string_start string_content string_end identifier argument_list call identifier argument_list attribute identifier identifier identifier for_in_clause identifier identifier list string string_start string_end return_statement call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier | Format metrics for the carbon plaintext protocol |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.