code stringlengths 51 2.34k | docstring stringlengths 11 171 |
|---|---|
def empty_bar_plot(ax):
plt.sca(ax)
plt.setp(plt.gca(),xticks=[],xticklabels=[])
return ax | 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... | 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
) | 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... | 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... | 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
) | 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... | 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
} | 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... | 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... | 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... | 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 | 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):
... | 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 ... | 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... | 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 | 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)) | 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... | 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)) | 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',
... | 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) | 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'])) | 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... | 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
} | 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 '' | 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 | 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) | 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... | Add a new nested AdditionalProperty message. |
def _self_destruct(self):
self._kill = threading.Timer(15, lambda: os._exit(0))
self._kill.start() | 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 | 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 ... | 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) | 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) | 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(... | 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 | Encode a list for the DynamoDB format |
def main(fast=False):
print('Running benchmarks...\n')
results = bench_run(fast=fast)
bench_report(results) | 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... | 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) | 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 | 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 | 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] | 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') | 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... | 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,
... | 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) | 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... | 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 | 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 | 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]) | 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... | 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 | 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... | 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) | Retrieve a value from the session dictionary |
def calcPeriod(self):
return eq.KeplersThirdLaw(self.a, self.star.M).P | 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... | 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, ... | 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) | 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 | 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) | 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) | 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)... | 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')) | 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 | 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 | 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 | 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() | 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")
... | 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) | 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) | 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:... | 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"],
... | 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... | 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) | 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... | 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", ... | 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... | 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) | 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... | 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) | 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(... | 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 | 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 | 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... | 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... | 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... | 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()) | 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... | Create a mediated transfer using channel. |
def _process_meta(self, response):
for key in self.META_ENVELOPES:
self.meta[key] = response.get(key) | 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)) | 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) | 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] | Add missing blank line. |
def on_train_end(self, logs):
duration = timeit.default_timer() - self.train_start
print('done, took {:.3f} seconds'.format(duration)) | 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.')
... | 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 | 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 | 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... | 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... | 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) | 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... | 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,
... | 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.