code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def empty_bar_plot(ax):
plt.sca(ax)
plt.setp(plt.gca(),xticks=[],xticklabels=[])
return ax | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list keyword_argument identifier list keyword_argumen... | Delete all axis ticks and labels |
def backend(self):
"Internal property that returns the Node script running harness"
if self._backend is None:
with io.open(path.join(path.abspath(path.dirname(__file__)), "runner.js")) as runner_file:
runner_source = runner_file.read()
self._backend = execjs.ExternalRuntime(name="Node.js (V8... | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end if_statement comparison_operator attribute identifier identifier none block with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list call attribu... | Internal property that returns the Node script running harness |
def replay(self, start_block=1, end_block=None, filter_by=list(), **kwargs):
return self.stream(
filter_by=filter_by,
start=start_block,
stop=end_block,
mode=self.mode,
**kwargs
) | module function_definition identifier parameters identifier default_parameter identifier integer default_parameter identifier none default_parameter identifier call identifier argument_list dictionary_splat_pattern identifier block return_statement call attribute identifier identifier argument_list keyword_argument ide... | Same as ``stream`` with different prototyp |
def _set_config(c):
glformat = QGLFormat()
glformat.setRedBufferSize(c['red_size'])
glformat.setGreenBufferSize(c['green_size'])
glformat.setBlueBufferSize(c['blue_size'])
glformat.setAlphaBufferSize(c['alpha_size'])
if QT5_NEW_API:
glformat.setSwapBehavior(glformat.DoubleBuffer if c['do... | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list expression_statement call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end expression_statement call attribute identi... | Set the OpenGL configuration |
def add_identities(cls, db, identities, backend):
logger.info("Adding the identities to SortingHat")
total = 0
for identity in identities:
try:
cls.add_identity(db, identity, backend)
total += 1
except Exception as e:
logger... | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier integer for_statement identifier identifier block try_statem... | Load identities list from backend in Sorting Hat |
def ping(self, callback=None, **kwargs):
self.client.fetch(
self.mk_req('', method='HEAD', **kwargs),
callback = callback
) | module function_definition identifier parameters identifier default_parameter identifier none dictionary_splat_pattern identifier block expression_statement call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_end keyword_a... | Ping request to check status of elasticsearch host |
def write_targets(targets, **params):
handler = ReplacementHandler(**params)
for target, regexer in regexer_for_targets(targets):
with open(target) as fh:
lines = fh.readlines()
lines = replace_lines(regexer, handler, lines)
with open(target, "w") as fh:
fh.writel... | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list dictionary_splat identifier for_statement pattern_list identifier identifier call identifier argument_list identifier block with_statement with_c... | Writes version info into version file |
def to_json(self):
return {
'wind_speed': self.wind_speed,
'wind_direction': self.wind_direction,
'rain': self.rain,
'snow_on_ground': self.snow_on_ground
} | module function_definition identifier parameters identifier block return_statement dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute... | Convert the Wind Condition to a dictionary. |
def find_exe(env_dir, name):
if platform.system() == "Windows":
name = name + ".exe"
exe_name = os.path.join(env_dir, name)
if not os.path.exists(exe_name):
exe_name = os.path.join(env_dir, "bin", name)
if not os.path.exists(exe_name):
exe_name = os.path.join(env_dir, "Sc... | module function_definition identifier parameters identifier identifier block if_statement comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier binary_operator identifier string string_start string_content st... | Finds a exe with that name in the environment path |
def copy(self):
inst = super(type(self), type(self)).empty(**self.dimensions)
inst.__attributes__ = {k: v.copy() for k, v in self.__attributes__.items()}
inst.__fields__ = {k: v.copy() for k, v in self.__fields__.items()}
inst.__relations__ = {k: v.copy() for k, v in self.__relations__.i... | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute call identifier argument_list call identifier argument_list identifier call identifier argument_list identifier identifier argument_list dictionary_splat attribute identifier identifier expression... | Create a copy of this ChemicalEntity |
def _enable_logpersist(self):
if not self._ad.is_rootable:
return
logpersist_warning = ('%s encountered an error enabling persistent'
' logs, logs may not get saved.')
if not self._ad.adb.has_shell_command('logpersist.start'):
logging.warning... | module function_definition identifier parameters identifier block if_statement not_operator attribute attribute identifier identifier identifier block return_statement expression_statement assignment identifier parenthesized_expression concatenated_string string string_start string_content string_end string string_star... | Attempts to enable logpersist daemon to persist logs. |
def serial_connect(self):
self.serial_get()
try:
self.serial_connection.start()
except c1218.errors.C1218IOError as error:
self.logger.error('serial connection has been opened but the meter is unresponsive')
raise error
self._serial_connected = True
return True | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list except_clause as_pattern attribute attribute identifier identifier id... | Connect to the serial device. |
def concatenate_and_rewrite(self, paths, output_filename, variant=None):
stylesheets = []
for path in paths:
def reconstruct(match):
quote = match.group(1) or ''
asset_path = match.group(2)
if NON_REWRITABLE_URL.match(asset_path):
... | module function_definition identifier parameters identifier identifier identifier default_parameter identifier none block expression_statement assignment identifier list for_statement identifier identifier block function_definition identifier parameters identifier block expression_statement assignment identifier boolea... | Concatenate together files and rewrite urls |
def barracks_correct_placement(self) -> Point2:
if len(self.upper2_for_ramp_wall) == 2:
if self.barracks_can_fit_addon:
return self.barracks_in_middle
else:
return self.barracks_in_middle.offset((-2, 0))
raise Exception("Not implemented. Trying to ... | module function_definition identifier parameters identifier type identifier block if_statement comparison_operator call identifier argument_list attribute identifier identifier integer block if_statement attribute identifier identifier block return_statement attribute identifier identifier else_clause block return_stat... | Corrected placement so that an addon can fit |
def create_stack(self, name):
deployment = find_exact(self.api.deployments, name=name)
if not deployment:
try:
self.api.client.post(
'/api/deployments',
data={'deployment[name]': name},
)
exce... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list attribute attribute identifier identifier identifier keyword_argument identifier identifier if_statement not_operator identifier block try_statement block expression_stat... | Creates stack if necessary. |
def mark_sentence_boundaries(sequences, drop=0.0):
for sequence in sequences:
sequence.insert(0, "-EOL-")
sequence.insert(0, "-EOL-")
sequence.append("-EOL-")
sequence.append("-EOL-")
return sequences, None | module function_definition identifier parameters identifier default_parameter identifier float block for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list integer string string_start string_content string_end expression_statement call attribute identifier iden... | Pad sentence sequences with EOL markers. |
def index(request, template_name='staffmembers/index.html'):
return render_to_response(template_name,
{'staff': StaffMember.objects.active()},
context_instance=RequestContext(request)) | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end block return_statement call identifier argument_list identifier dictionary pair string string_start string_content string_end call attribute attribute identifier identifier identifier a... | The list of employees or staff members |
def inet_ntop(af, addr):
if af == socket.AF_INET:
return inet_ntoa(addr)
elif af == socket.AF_INET6:
if len(addr) != 16:
raise Exception("Illegal syntax for IP address")
parts = []
for left in [0, 2, 4, 6, 8, 10, 12, 14]:
try:
value = stru... | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block return_statement call identifier argument_list identifier elif_clause comparison_operator identifier attribute identifier identifier block if_statement compariso... | Convert an IP address from binary form into text represenation |
def no_sleep():
mode = power.ES.continuous | power.ES.system_required
handle_nonzero_success(power.SetThreadExecutionState(mode))
try:
yield
finally:
handle_nonzero_success(power.SetThreadExecutionState(power.ES.continuous)) | module function_definition identifier parameters block expression_statement assignment identifier binary_operator attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier expression_statement call identifier argument_list call attribute identifier identifier argument_lis... | Context that prevents the computer from going to sleep. |
def cleanup_datastore(self):
print_header('CLEANING UP ENTIRE DATASTORE')
kinds_to_delete = [u'Submission', u'SubmissionType',
u'DatasetImage', u'DatasetBatch',
u'AdversarialImage', u'AdversarialBatch',
u'Work', u'WorkType',
... | module function_definition identifier parameters identifier block expression_statement call 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_sta... | Cleans up datastore and deletes all information about current round. |
def repopulateWinowMenu(self, actionGroup):
for action in self.windowMenu.actions():
self.windowMenu.removeAction(action)
for action in actionGroup.actions():
self.windowMenu.addAction(action) | module function_definition identifier parameters identifier identifier block for_statement identifier call attribute attribute identifier identifier identifier argument_list block expression_statement call attribute attribute identifier identifier identifier argument_list identifier for_statement identifier call attrib... | Clear the window menu and fills it with the actions of the actionGroup |
def remove_api_gateway_logs(self, project_name):
for rest_api in self.get_rest_apis(project_name):
for stage in self.apigateway_client.get_stages(restApiId=rest_api['id'])['item']:
self.remove_log_group('API-Gateway-Execution-Logs_{}/{}'.format(rest_api['id'], stage['stageName'])) | module function_definition identifier parameters identifier identifier block for_statement identifier call attribute identifier identifier argument_list identifier block for_statement identifier subscript call attribute attribute identifier identifier identifier argument_list keyword_argument identifier subscript ident... | Removed all logs that are assigned to a given rest api id. |
def make(game, state=State.DEFAULT, inttype=retro.data.Integrations.DEFAULT, **kwargs):
try:
retro.data.get_romfile_path(game, inttype)
except FileNotFoundError:
if not retro.data.get_file_path(game, "rom.sha", inttype):
raise
else:
raise FileNotFoundError('Game n... | module function_definition identifier parameters identifier default_parameter identifier attribute identifier identifier default_parameter identifier attribute attribute attribute identifier identifier identifier identifier dictionary_splat_pattern identifier block try_statement block expression_statement call attribut... | Create a Gym environment for the specified game |
def _clean_empty(d):
if not isinstance(d, (dict, list)):
return d
if isinstance(d, list):
return [v for v in (_clean_empty(v) for v in d) if v is not None]
return {
k: v for k, v in
((k, _clean_empty(v)) for k, v in d.items())
if v is not None
} | module function_definition identifier parameters identifier block if_statement not_operator call identifier argument_list identifier tuple identifier identifier block return_statement identifier if_statement call identifier argument_list identifier identifier block return_statement list_comprehension identifier for_in_... | Remove None values from a dict. |
def sub(value, arg):
try:
nvalue, narg = handle_float_decimal_combinations(
valid_numeric(value), valid_numeric(arg), '-')
return nvalue - narg
except (ValueError, TypeError):
try:
return value - arg
except Exception:
return '' | module function_definition identifier parameters identifier identifier block try_statement block expression_statement assignment pattern_list identifier identifier call identifier argument_list call identifier argument_list identifier call identifier argument_list identifier string string_start string_content string_en... | Subtract the arg from the value. |
def security_errors(self):
errors = ErrorDict()
for f in ["honeypot", "timestamp", "security_hash"]:
if f in self.errors:
errors[f] = self.errors[f]
return errors | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list 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 block if_stat... | Return just those errors associated with security |
def create_widget(self):
d = self.declaration
button_type = UIButton.UIButtonTypeSystem if d.flat else UIButton.UIButtonTypeRoundedRect
self.widget = UIButton(buttonWithType=button_type) | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier conditional_expression attribute identifier identifier attribute identifier identifier attribute identifier identifier expression_statem... | Create the toolkit widget for the proxy object. |
def __AddAdditionalPropertyType(self, name, property_schema):
new_type_name = 'AdditionalProperty'
property_schema = dict(property_schema)
property_schema.pop('description', None)
description = 'An additional property for a %s object.' % name
schema = {
'id': new_type... | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute identifier identifier a... | Add a new nested AdditionalProperty message. |
def _self_destruct(self):
self._kill = threading.Timer(15, lambda: os._exit(0))
self._kill.start() | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list integer lambda call attribute identifier identifier argument_list integer expression_statement call attribute attribute identifier identifi... | Auto quit exec if parent process failed |
def remove(self, timer):
with self.lock:
if timer in self.timers:
self._remove(timer)
return False
else:
return True | module function_definition identifier parameters identifier identifier block with_statement with_clause with_item attribute identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier ret... | Remove a timer from the heap, return True if already run |
def isRectangular(self):
upper = (self.ur - self.ul).unit
if not bool(upper):
return False
right = (self.lr - self.ur).unit
if not bool(right):
return False
left = (self.ll - self.ul).unit
if not bool(left):
return False
lower ... | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute parenthesized_expression binary_operator attribute identifier identifier attribute identifier identifier identifier if_statement not_operator call identifier argument_list identifier block return_state... | Check if quad is rectangular. |
def _clean_message(message):
message = message.replace('zonecfg: ', '')
message = message.splitlines()
for line in message:
if line.startswith('On line'):
message.remove(line)
return "\n".join(message) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end expression_statement assignment identifier call attribute identifier identifier arg... | Internal helper to sanitize message output |
def install_from_zip(url):
fname = 'tmp.zip'
downlad_file(url, fname)
unzip_file(fname)
print("Removing {}".format(fname))
os.unlink(fname) | module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_content string_end expression_statement call identifier argument_list identifier identifier expression_statement call identifier argument_list identifier expression_statement call iden... | Download and unzip from url. |
def do_shutdown(self, restart):
print("in shutdown function")
if self.hist_file:
with open(self.hist_file, 'wb') as fid:
data = '\n'.join(self.hist_cache[-self.max_hist_cache:])
fid.write(data.encode('utf-8'))
if self.mva:
self.mva._endsas(... | module function_definition identifier parameters identifier identifier block expression_statement call identifier argument_list string string_start string_content string_end if_statement attribute identifier identifier block with_statement with_clause with_item as_pattern call identifier argument_list attribute identif... | Shut down the app gracefully, saving history. |
def encode_list(dynamizer, value):
encoded_list = []
dict(map(dynamizer.raw_encode, value))
for v in value:
encoded_type, encoded_value = dynamizer.raw_encode(v)
encoded_list.append({
encoded_type: encoded_value,
})
return 'L', encoded_list | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list expression_statement call identifier argument_list call identifier argument_list attribute identifier identifier identifier for_statement identifier identifier block expression_statement assignme... | Encode a list for the DynamoDB format |
def main(fast=False):
print('Running benchmarks...\n')
results = bench_run(fast=fast)
bench_report(results) | module function_definition identifier parameters default_parameter identifier false block expression_statement call identifier argument_list string string_start string_content escape_sequence string_end expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier expre... | Run all benchmarks and print report to the console. |
def turn_emails_off(view_func):
EMAIL_BACKEND_DUMMY = 'django.core.mail.backends.dummy.EmailBackend'
def decorated(request, *args, **kwargs):
orig_email_backend = settings.EMAIL_BACKEND
settings.EMAIL_BACKEND = EMAIL_BACKEND_DUMMY
response = view_func(request, *args, **kwargs)
se... | module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_content string_end function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifi... | Turns emails off so no emails will be sent. |
def _resolve_import(name):
if name in sys.modules:
return getattr(sys.modules[name], '__file__', name + '.so')
return _resolve_import_versioned(name) | module function_definition identifier parameters identifier block if_statement comparison_operator identifier attribute identifier identifier block return_statement call identifier argument_list subscript attribute identifier identifier identifier string string_start string_content string_end binary_operator identifier... | Helper function for resolve_import. |
def types(self):
if self._types == '' and self.details != None and 'types' in self.details:
self._icon = self.details['types']
return self._types | module function_definition identifier parameters identifier block if_statement boolean_operator boolean_operator comparison_operator attribute identifier identifier string string_start string_end comparison_operator attribute identifier identifier none comparison_operator string string_start string_content string_end a... | Returns a list of feature types describing the given result. |
def keypress(self, event):
try:
self.choice.set(self.shortcuts[event.keysym])
except KeyError:
pass | module function_definition identifier parameters identifier identifier block try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list subscript attribute identifier identifier attribute identifier identifier except_clause identifier block pass_statement | Allow keys typed in widget to select items |
def get(self, table_name):
assert table_name in self.tabs, \
"Table not avaiable. Avaiable tables: {}".format(
", ".join(self.tabs.keys())
)
return self.tabs[table_name] | module function_definition identifier parameters identifier identifier block assert_statement comparison_operator identifier attribute identifier identifier call attribute string string_start string_content string_end identifier argument_list call attribute string string_start string_content string_end identifier argum... | Load table class by name, class not yet initialized |
def connect(self):
self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._socket.settimeout(self._connect_timeout)
SocketError.wrap(self._socket.connect, (self.host, self.port))
self._socket.settimeout(None)
self._socket_file = self._socket.makefile('rb') | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement call attribute attribute identifier identifier identif... | Connect to beanstalkd server. |
def predict(self, features):
scores = defaultdict(float)
for feat in features:
if feat not in self.weights:
continue
weights = self.weights[feat]
for label, weight in weights.items():
scores[label] += weight
return max(self.clas... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier for_statement identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block continue_statement expression_state... | Dot-product the features and current weights and return the best label. |
def create_from_source(cls, name, config, **kwargs):
coordsys = kwargs.pop('coordsys', 'CEL')
roi = cls(config, src_radius=None, src_roiwidth=None,
srcname=name, **kwargs)
src = roi.get_source_by_name(name)
return cls.create_from_position(src.skydir, config,
... | module function_definition identifier parameters identifier identifier identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end expression... | Create an ROI centered on the given source. |
def rq_link(self):
if self.rq_job:
url = reverse('rq_job_detail',
kwargs={'job_id': self.rq_id, 'queue_index': queue_index_by_name(self.rq_origin)})
return '<a href="{}">{}</a>'.format(url, self.rq_id) | module function_definition identifier parameters identifier block if_statement attribute identifier identifier block expression_statement assignment identifier call identifier argument_list string string_start string_content string_end keyword_argument identifier dictionary pair string string_start string_content strin... | Link to Django-RQ status page for this job |
def _check_svcaller(item):
allowed = set(reduce(operator.add, [list(d.keys()) for d in structural._CALLERS.values()]) + [None, False])
svs = item["algorithm"].get("svcaller")
if not isinstance(svs, (list, tuple)):
svs = [svs]
problem = [x for x in svs if x not in allowed]
if len(problem) > 0... | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list binary_operator call identifier argument_list attribute identifier identifier list_comprehension call identifier argument_list call attribute identifier identifier argument_list for... | Ensure the provide structural variant caller is valid. |
def create():
if ctypes:
inotify = _CtypesLibcINotifyWrapper()
if inotify.init():
return inotify
if inotify_syscalls:
inotify = _INotifySyscallsWrapper()
if inotify.init():
return inotify | module function_definition identifier parameters block if_statement identifier block expression_statement assignment identifier call identifier argument_list if_statement call attribute identifier identifier argument_list block return_statement identifier if_statement identifier block expression_statement assignment id... | Factory method instanciating and returning the right wrapper. |
def _next_ifd(self, ifd):
entries = self.s2n(ifd, 2)
next_ifd = self.s2n(ifd + 2 + 12 * entries, 4)
if next_ifd == ifd:
return 0
else:
return next_ifd | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator binary_operator iden... | Return the pointer to next IFD. |
def _path_to_value(cls, path, parent_dict):
keys = cls._path_to_keys(path)
child_dict = parent_dict
for key in keys[:-1]:
child_dict = child_dict.get(key)
if child_dict is None:
return
return child_dict.get(keys[-1]) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier identifier for_statement identifier subscript identifier slice unary_operator intege... | Return a value from a dictionary at the given path |
def store_output_files(self, dir_path):
if self.last_result:
for entry in os.listdir(self.last_result["output_dir"]):
path = os.path.join(self.last_result["output_dir"], entry)
if os.path.isfile(path):
shutil.copy(path, os.path.join(dir_path, entry... | module function_definition identifier parameters identifier identifier block if_statement attribute identifier identifier block for_statement identifier call attribute identifier identifier argument_list subscript attribute identifier identifier string string_start string_content string_end block expression_statement a... | Store OSLOM output files to a directory. |
def to_vec3(self):
vec3 = Vector3()
vec3.x = self.x
vec3.y = self.y
vec3.z = self.z
if self.w != 0:
vec3 /= self.w
return vec3 | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier attribute identifier ... | Convert this vector4 instance into a vector3 instance. |
def get(self, **user_parameters):
plugin, open_args = self._create_open_args(user_parameters)
data_source = plugin(**open_args)
data_source.catalog_object = self._catalog
data_source.name = self.name
data_source.description = self._description
data_source.cat = self._cata... | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list dictionary_splat... | Instantiate the DataSource for the given parameters |
def get(self, key):
self._started = self._backend_client.load()
self._needs_save = True
return self._backend_client.get(key) | module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier true return_statement call attribute attrib... | Retrieve a value from the session dictionary |
def calcPeriod(self):
return eq.KeplersThirdLaw(self.a, self.star.M).P | module function_definition identifier parameters identifier block return_statement attribute call attribute identifier identifier argument_list attribute identifier identifier attribute attribute identifier identifier identifier identifier | calculates period using a and stellar mass |
def _process_hist(self, hist):
self.cyclic = hist.get_dimension(0).cyclic
x = hist.kdims[0]
edges = hist.interface.coords(hist, x, edges=True)
values = hist.dimension_values(1)
hist_vals = np.array(values)
xlim = hist.range(0)
ylim = hist.range(1)
is_datet... | module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier attribute call attribute identifier identifier argument_list integer identifier expression_statement assignment identifier subscript attribute identifier identifier integer expres... | Get data from histogram, including bin_ranges and values. |
def emit(self, record):
if not record.name == "amqp":
data = {}
for k, v in record.__dict__.items():
if (self.__includes and k in self.__includes) or (self.__excludes and k not in self.__excludes):
data[k] = v
self.__producer.publish(data, ... | module function_definition identifier parameters identifier identifier block if_statement not_operator comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement assignment identifier dictionary for_statement pattern_list identifier identifier call attri... | The amqp module also print the log when call publish, this will cause maximum recursion depth exceeded. |
def badnick(self, me=None, nick=None, **kw):
if me == '*':
self.bot.set_nick(self.bot.nick + '_')
self.bot.log.debug('Trying to regain nickname in 30s...')
self.nick_handle = self.bot.loop.call_later(
30, self.bot.set_nick, self.bot.original_nick) | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none dictionary_splat_pattern identifier block if_statement comparison_operator identifier string string_start string_content string_end block expression_statement call attribute attribute identifi... | Use alt nick on nick error |
def write_json_to_temp_file(data):
fp = tempfile.NamedTemporaryFile(delete=False)
fp.write(json.dumps(data).encode('utf-8'))
fp.close()
return fp.name | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier false expression_statement call attribute identifier identifier argument_list call attribute call attribute identifier identifier ar... | Writes JSON data to a temporary file and returns the path to it |
def make_declarative_base(self, metadata=None):
return make_declarative_base(self.session,
Model=self.Model,
metadata=metadata) | module function_definition identifier parameters identifier default_parameter identifier none block return_statement call identifier argument_list attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier | Override parent function with alchy's |
def create(config, group, type):
if type not in ('user', 'service'):
raise click.BadOptionUsage(
"--grouptype must be 'user' or 'service'")
client = Client()
client.prepare_connection()
group_api = API(client)
group_api.create(group, type) | module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator identifier tuple string string_start string_content string_end string string_start string_content string_end block raise_statement call attribute identifier identifier argument_list string string_sta... | Create an LDAP group. |
def _paint_line_number_bg(self, im):
if not self.line_numbers:
return
if self.line_number_fg is None:
return
draw = ImageDraw.Draw(im)
recth = im.size[-1]
rectw = self.image_pad + self.line_number_width - self.line_number_pad
draw.rectangle([(0, 0)... | module function_definition identifier parameters identifier identifier block if_statement not_operator attribute identifier identifier block return_statement if_statement comparison_operator attribute identifier identifier none block return_statement expression_statement assignment identifier call attribute identifier ... | Paint the line number background on the image. |
def node_contained_in_layer_area_validation(self):
if self.layer and isinstance(self.layer.area, Polygon) and not self.layer.area.contains(self.geometry):
raise ValidationError(_('Node must be inside layer area')) | module function_definition identifier parameters identifier block if_statement boolean_operator boolean_operator attribute identifier identifier call identifier argument_list attribute attribute identifier identifier identifier identifier not_operator call attribute attribute attribute identifier identifier identifier ... | if layer defines an area, ensure node coordinates are contained in the area |
def file_current(self, fname, md5):
return os.path.isfile(fname) and util.md5_file(fname) == md5 | module function_definition identifier parameters identifier identifier identifier block return_statement boolean_operator call attribute attribute identifier identifier identifier argument_list identifier comparison_operator call attribute identifier identifier argument_list identifier identifier | Checksum a file and compare the md5 with the known md5 |
def _premium(fn):
@_functools.wraps(fn)
def _fn(self, *args, **kwargs):
if self._lite:
raise RuntimeError('Premium API not available in lite access.')
return fn(self, *args, **kwargs)
return _fn | module function_definition identifier parameters identifier block decorated_definition decorator call attribute identifier identifier argument_list identifier function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block if_statement attribute identifier id... | Premium decorator for APIs that require premium access level. |
def PLAY(self):
message = "PLAY " + self.session.url + " RTSP/1.0\r\n"
message += self.sequence
message += self.authentication
message += self.user_agent
message += self.session_id
message += '\r\n'
return message | module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator binary_operator string string_start string_content string_end attribute attribute identifier identifier identifier string string_start string_content escape_sequence escape_sequence string_end ex... | RTSP session is ready to send data. |
def merge_true_table():
writer = pd.ExcelWriter("True Table.xlsx")
for p in Path(__file__).parent.select_by_ext(".csv"):
df = pd.read_csv(p.abspath, index_col=0)
df.to_excel(writer, p.fname, index=True)
writer.save() | module function_definition identifier parameters block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end for_statement identifier call attribute attribute call identifier argument_list identifier identifier identifier argument_lis... | Merge all true table into single excel file. |
def write(self, garbage=0, clean=0, deflate=0, ascii=0, expand=0, linear=0, pretty=0, decrypt=1):
if self.isClosed or self.isEncrypted:
raise ValueError("operation illegal for closed / encrypted doc")
if self.pageCount < 1:
raise ValueError("cannot write with zero pages")
... | module function_definition identifier parameters identifier default_parameter identifier integer default_parameter identifier integer default_parameter identifier integer default_parameter identifier integer default_parameter identifier integer default_parameter identifier integer default_parameter identifier integer d... | Write document to a bytes object. |
def add(self, command_template, job_class):
job = JobTemplate(command_template.alias,
command_template=command_template,
depends_on=command_template.depends_on, queue=self.queue,
job_class=job_class)
self.queue.push(job) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier ... | Given a command template, add it as a job to the queue. |
def save(self, *args, **kwargs):
if not self.pluralName:
self.pluralName = self.name + 's'
super(self.__class__, self).save(*args, **kwargs) | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block if_statement not_operator attribute identifier identifier block expression_statement assignment attribute identifier identifier binary_operator attribute identifier identifier string strin... | Just add "s" if no plural name given. |
def __telnet_event_listener(self, ip, callback):
tn = telnetlib.Telnet(ip, 2708)
self._last_event = ""
self._telnet_running = True
while self._telnet_running:
try:
raw_string = tn.read_until(b'.\n', 5)
if len(raw_string) >= 2 and raw_string[-2:... | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier integer expression_statement assignment attribute identifier identifier string string_start string_end expression_statement ass... | creates a telnet connection to the lightpad |
def read_tuple(self):
cmd = self.read_command()
source = cmd["comp"]
stream = cmd["stream"]
values = cmd["tuple"]
val_type = self._source_tuple_types[source].get(stream)
return Tuple(
cmd["id"],
source,
stream,
cmd["task"],
... | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier subscri... | Read a tuple from the pipe to Storm. |
def setup_ufw():
if not env.ENABLE_UFW: return
ufw_state = server_state('ufw_installed')
if ufw_state and not env.overwrite or ufw_state == str(env.HOST_SSH_PORT): return
ufw = run("dpkg -l | grep 'ufw' | awk '{print $2}'").strip()
if not ufw:
if env.verbosity:
print env.host, "I... | module function_definition identifier parameters block if_statement not_operator attribute identifier identifier block return_statement expression_statement assignment identifier call identifier argument_list string string_start string_content string_end if_statement boolean_operator boolean_operator identifier not_ope... | Setup basic ufw rules just for ssh login |
def retrieve_old_notifications(self):
date = ago(days=DELETE_OLD)
return Notification.objects.filter(added__lte=date) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier return_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier | Retrieve notifications older than X days, where X is specified in settings |
def columnize(items, width=None, file=sys.stdout):
if not items:
return
if width is None:
width = shutil.get_terminal_size()[0] if file is sys.stdout else 80
items = [rendering.vtmlrender(x) for x in items]
maxcol = max(items, key=len)
colsize = len(maxcol) + 2
cols = width // co... | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier attribute identifier identifier block if_statement not_operator identifier block return_statement if_statement comparison_operator identifier none block expression_statement assignment identifier c... | Smart display width handling when showing a list of stuff. |
def start_server(port):
s = socket(AF_INET, SOCK_STREAM)
s.settimeout(None)
try:
from socket import SO_REUSEPORT
s.setsockopt(SOL_SOCKET, SO_REUSEPORT, 1)
except ImportError:
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
s.bind(('', port))
pydev_log.info("Bound to port :%s", ... | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list none try_statement block import_from_statement dotted_name identifier dotted_name ident... | binds to a port, waits for the debugger to connect |
def ae_latent_sample(latents_dense, inputs, ed, embed, iters, hparams):
if hparams.num_decode_blocks < 2 and hparams.sampling_temp == 0.0:
tf.logging.info("Running beam-search for latents with beam size 1.")
return ae_latent_sample_beam(latents_dense, inputs, ed, embed, hparams)
latents_pred = decode_transf... | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier block if_statement boolean_operator comparison_operator attribute identifier identifier integer comparison_operator attribute identifier identifier float block expression_statement call attribute attribute... | Sample from the latent space in the autoencoder. |
def persistant_success(request, message, extra_tags='', fail_silently=False, *args, **kwargs):
add_message(request, SUCCESS_PERSISTENT, message, extra_tags=extra_tags,
fail_silently=fail_silently, *args, **kwargs) | module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_end default_parameter identifier false list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement call identifier argument_list identifier identifier identifie... | Adds a persistant message with the ``SUCCESS`` level. |
def last_sleep_breakdown(self):
try:
stages = self.intervals[1]['stages']
except KeyError:
return None
breakdown = {'awake': 0, 'light': 0, 'deep': 0, 'rem': 0}
for stage in stages:
if stage['stage'] == 'awake':
breakdown['awake'] += st... | module function_definition identifier parameters identifier block try_statement block expression_statement assignment identifier subscript subscript attribute identifier identifier integer string string_start string_content string_end except_clause identifier block return_statement none expression_statement assignment ... | Return durations of sleep stages for last complete session. |
def _update_cluster_view(self):
logger.log(5, "Update the cluster view.")
cluster_ids = [int(c) for c in self.clustering.cluster_ids]
self.cluster_view.set_rows(cluster_ids) | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list integer string string_start string_content string_end expression_statement assignment identifier list_comprehension call identifier argument_list identifier for_in_clause identifier ... | Initialize the cluster view with cluster data. |
def _serve_individual_audio(self, request):
tag = request.args.get('tag')
run = request.args.get('run')
index = int(request.args.get('index'))
sample = int(request.args.get('sample', 0))
events = self._filter_by_sample(self._multiplexer.Tensors(run, tag), sample)
data = tensor_util.make_ndarray(... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier ide... | Serve encoded audio data. |
def move_red_left(self):
self = self.flip()
if self.right is not NULL and self.right.left.red:
self = self._replace(right=self.right.rotate_right())
self = self.rotate_left().flip()
return self | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement boolean_operator comparison_operator attribute identifier identifier identifier attribute attribute attribute identifier identifier identifier iden... | Shuffle red to the left of a tree. |
def listdir(self, pathobj):
stat = self.stat(pathobj)
if not stat.is_dir:
raise OSError(20, "Not a directory: %s" % str(pathobj))
return stat.children | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement not_operator attribute identifier identifier block raise_statement call identifier argument_list integer binary_operator stri... | Returns a list of immediate sub-directories and files in path |
def find_schemas(self, schema_path, schema_type=SCHEMA_TYPE_PROCESS, verbosity=1):
schema_matches = []
if not os.path.isdir(schema_path):
if verbosity > 0:
self.stdout.write("Invalid path {}".format(schema_path))
return
if schema_type not in [SCHEMA_TYPE_P... | module function_definition identifier parameters identifier identifier default_parameter identifier identifier default_parameter identifier integer block expression_statement assignment identifier list if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block if_... | Find schemas in packages that match filters. |
def _readfloat(self, length, start):
if not (start + self._offset) % 8:
startbyte = (start + self._offset) // 8
if length == 32:
f, = struct.unpack('>f', bytes(self._datastore.getbyteslice(startbyte, startbyte + 4)))
elif length == 64:
f, = str... | module function_definition identifier parameters identifier identifier identifier block if_statement not_operator binary_operator parenthesized_expression binary_operator identifier attribute identifier identifier integer block expression_statement assignment identifier binary_operator parenthesized_expression binary_o... | Read bits and interpret as a float. |
def cdssequencethreads(self):
for i in range(self.cpus):
threads = Thread(target=self.cdssequence, args=())
threads.setDaemon(True)
threads.start()
for sample in self.metadata.samples:
sample[self.analysistype].coresequence = dict()
self.sequen... | module function_definition identifier parameters identifier block for_statement identifier call identifier argument_list attribute identifier identifier block expression_statement assignment identifier call identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier ... | Extracts the sequence of each gene for each strain |
def generate_id(self):
if self.use_repeatable_ids:
self.repeatable_id_counter += 1
return 'autobaked-{}'.format(self.repeatable_id_counter)
else:
return str(uuid4()) | module function_definition identifier parameters identifier block if_statement attribute identifier identifier block expression_statement augmented_assignment attribute identifier identifier integer return_statement call attribute string string_start string_content string_end identifier argument_list attribute identifi... | Generate a fresh id |
def send_lockedtransfer(
transfer_description: TransferDescriptionWithSecretState,
channel_state: NettingChannelState,
message_identifier: MessageID,
block_number: BlockNumber,
) -> SendLockedTransfer:
assert channel_state.token_network_identifier == transfer_description.token_networ... | module function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type identifier typed_parameter identifier type identifier typed_parameter identifier type identifier type identifier block assert_statement comparison_operator attribute identifier identifier attribut... | Create a mediated transfer using channel. |
def _process_meta(self, response):
for key in self.META_ENVELOPES:
self.meta[key] = response.get(key) | module function_definition identifier parameters identifier identifier block for_statement identifier attribute identifier identifier block expression_statement assignment subscript attribute identifier identifier identifier call attribute identifier identifier argument_list identifier | Process additional data sent in response |
def join(self):
if self.thread:
self.thread.join()
self.thread = None
else:
logger.debug("Cannot join {0}, as the state hasn't been started, yet or is already finished!".format(self)) | module function_definition identifier parameters identifier block if_statement attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier none else_clause block expression_statement ca... | Waits until the state finished execution. |
def coerce_indexer_dtype(indexer, categories):
length = len(categories)
if length < _int8_max:
return ensure_int8(indexer)
elif length < _int16_max:
return ensure_int16(indexer)
elif length < _int32_max:
return ensure_int32(indexer)
return ensure_int64(indexer) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator identifier identifier block return_statement call identifier argument_list identifier elif_clause comparison_operator identifi... | coerce the indexer input array to the smallest dtype possible |
def fix_e301(self, result):
cr = '\n'
self.source[result['line'] - 1] = cr + self.source[result['line'] - 1] | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier string string_start string_content escape_sequence string_end expression_statement assignment subscript attribute identifier identifier binary_operator subscript identifier string string_start string_... | Add missing blank line. |
def on_train_end(self, logs):
duration = timeit.default_timer() - self.train_start
print('done, took {:.3f} seconds'.format(duration)) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier binary_operator call attribute identifier identifier argument_list attribute identifier identifier expression_statement call identifier argument_list call attribute string string_start string_content ... | Print training time at end of training |
def delete_keypair(kwargs=None, call=None):
if call != 'function':
log.error(
'The delete_keypair function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'keyname' not in kwargs:
log.error('A keyname is required.')
... | module function_definition identifier parameters default_parameter identifier none default_parameter identifier none block if_statement comparison_operator identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list string string_start string_co... | Delete an SSH keypair |
def input_dim(self):
n_cont = len(self.get_continuous_dims())
n_disc = len(self.get_discrete_dims())
return n_cont + n_disc | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list return... | Extracts the input dimension of the domain. |
def replace_event_annotations(event, newanns):
_humilis = event.get("_humilis", {})
if not _humilis:
event["_humilis"] = {"annotation": newanns}
else:
event["_humilis"]["annotation"] = newanns | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end dictionary if_statement not_operator identifier block expression_statement assignment subscript identif... | Replace event annotations with the provided ones. |
def requirement_spec(package_name, *args):
if not args or args == (None,):
return package_name
version_specs = []
for version_spec in args:
if isinstance(version_spec, (list, tuple)):
operator, version = version_spec
else:
assert isinstance(version_spe... | module function_definition identifier parameters identifier list_splat_pattern identifier block if_statement boolean_operator not_operator identifier comparison_operator identifier tuple none block return_statement identifier expression_statement assignment identifier list for_statement identifier identifier block if_s... | Identifier used when specifying a requirement to pip or setuptools. |
def create_empty(cls, tstart, tstop, fill=0.0, nside=64):
cth_edges = np.linspace(0, 1.0, 41)
domega = utils.edge_to_width(cth_edges) * 2.0 * np.pi
hpx = HPX(nside, True, 'CEL', ebins=cth_edges)
data = np.ones((len(cth_edges) - 1, hpx.npix)) * fill
return cls(data, hpx, cth_edges... | module function_definition identifier parameters identifier identifier identifier default_parameter identifier float default_parameter identifier integer block expression_statement assignment identifier call attribute identifier identifier argument_list integer float integer expression_statement assignment identifier b... | Create an empty livetime cube. |
def list_articles(self, project, articleset, page=1, **filters):
url = URL.article.format(**locals())
return self.get_pages(url, page=page, **filters) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier integer dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list dictionary_splat call identifier argument_li... | List the articles in a set |
def parseprofile(profilelog, out):
file = open(out, 'w')
print('Opening the profile in %s...' % profilelog)
p = pstats.Stats(profilelog, stream=file)
print('Generating the stats, please wait...')
file.write("=== All stats:\n")
p.strip_dirs().sort_stats(-1).print_stats()
file.write("=== Cumul... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end expression_statement call identifier argument_list binary_operator string string_start string_content string_end ... | Parse a profile log and print the result on screen |
def derive_child_context(self, whence):
return _HandlerContext(
container=self.container,
queue=self.queue,
field_name=None,
annotations=None,
depth=self.depth,
whence=whence,
value=bytearray(),
ion_type=None,
... | module function_definition identifier parameters identifier identifier block return_statement call identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier none keyword_argument identifier none keyword_ar... | Derives a scalar context as a child of the current context. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.