code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def concurrent_slots(slots):
for i, slot in enumerate(slots):
for j, other_slot in enumerate(slots[i + 1:]):
if slots_overlap(slot, other_slot):
yield (i, j + i + 1) | module function_definition identifier parameters identifier block for_statement pattern_list identifier identifier call identifier argument_list identifier block for_statement pattern_list identifier identifier call identifier argument_list subscript identifier slice binary_operator identifier integer block if_statemen... | Yields all concurrent slot indices. |
def format_json(json_object, indent):
indent_str = "\n" + " " * indent
json_str = json.dumps(json_object, indent=2, default=serialize_json_var)
return indent_str.join(json_str.split("\n")) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier binary_operator string string_start string_content escape_sequence string_end binary_operator string string_start string_content string_end identifier expression_statement assignment identifier call a... | Pretty-format json data |
def add_backend(self, backend):
"Add a RapidSMS backend to this tenant"
if backend in self.get_backends():
return
backend_link, created = BackendLink.all_tenants.get_or_create(backend=backend)
self.backendlink_set.add(backend_link) | module function_definition identifier parameters identifier identifier block expression_statement string string_start string_content string_end if_statement comparison_operator identifier call attribute identifier identifier argument_list block return_statement expression_statement assignment pattern_list identifier id... | Add a RapidSMS backend to this tenant |
def close(self):
if self._save_filename:
self._cookie_jar.save(
self._save_filename,
ignore_discard=self._keep_session_cookies
) | module function_definition identifier parameters identifier block if_statement attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier keyword_argument identifier attribute identifier identifier | Save the cookie jar if needed. |
def _set_autocommit(connection):
if hasattr(connection.connection, "autocommit"):
if callable(connection.connection.autocommit):
connection.connection.autocommit(True)
else:
connection.connection.autocommit = True
elif hasattr(connection.connection... | module function_definition identifier parameters identifier block if_statement call identifier argument_list attribute identifier identifier string string_start string_content string_end block if_statement call identifier argument_list attribute attribute identifier identifier identifier block expression_statement call... | Make sure a connection is in autocommit mode. |
def delete_archive_file(self):
logger.debug("Deleting %s", self.archive_tmp_dir)
shutil.rmtree(self.archive_tmp_dir, True) | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier ... | Delete the directory containing the constructed archive |
def toList(value):
if type(value) == list:
return value
elif type(value) in [np.ndarray, tuple, xrange, array.array]:
return list(value)
elif isinstance(value, Vector):
return list(value.toArray())
else:
raise TypeError("Could not convert %... | module function_definition identifier parameters identifier block if_statement comparison_operator call identifier argument_list identifier identifier block return_statement identifier elif_clause comparison_operator call identifier argument_list identifier list attribute identifier identifier identifier identifier att... | Convert a value to a list, if possible. |
def parse(self, value):
if self.required and value is None:
raise ValueError("%s is required!" % self.name)
elif self.ignored and value is not None:
warn("%s is ignored for this class!" % self.name)
elif not self.multi and isinstance(value, (list, tuple)):
if ... | module function_definition identifier parameters identifier identifier block if_statement boolean_operator attribute identifier identifier comparison_operator identifier none block raise_statement call identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier... | Enforce rules and return parsed value |
def filenames(self):
if self.topic.has_file:
yield self.topic.file.filename
for reply in self.replies:
if reply.has_file:
yield reply.file.filename | module function_definition identifier parameters identifier block if_statement attribute attribute identifier identifier identifier block expression_statement yield attribute attribute attribute identifier identifier identifier identifier for_statement identifier attribute identifier identifier block if_statement attri... | Returns the filenames of all files attached to posts in the thread. |
async def _do(self, ctx, times: int, *, command):
msg = copy.copy(ctx.message)
msg.content = command
for i in range(times):
await self.bot.process_commands(msg) | module function_definition identifier parameters identifier identifier typed_parameter identifier type identifier keyword_separator identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment attribute ide... | Repeats a command a specified number of times. |
def _windows_cpudata():
grains = {}
if 'NUMBER_OF_PROCESSORS' in os.environ:
try:
grains['num_cpus'] = int(os.environ['NUMBER_OF_PROCESSORS'])
except ValueError:
grains['num_cpus'] = 1
grains['cpu_model'] = salt.utils.win_reg.read_value(
hive="HKEY_LOCAL_MACHI... | module function_definition identifier parameters block expression_statement assignment identifier dictionary if_statement comparison_operator string string_start string_content string_end attribute identifier identifier block try_statement block expression_statement assignment subscript identifier string string_start s... | Return some CPU information on Windows minions |
def cpp_best_split_full_model(X, Uy, C, S, U, noderange, delta,
save_memory=False):
return CSP.best_split_full_model(X, Uy, C, S, U, noderange, delta) | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier identifier default_parameter identifier false block return_statement call attribute identifier identifier argument_list identifier identifier identifier identifier identifier identifier identifier | wrappe calling cpp splitting function |
def to_data_rows(self, brains):
fields = self.get_field_names()
return map(lambda brain: self.get_data_record(brain, fields), brains) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list return_statement call identifier argument_list lambda lambda_parameters identifier call attribute identifier identifier argument_list identifier iden... | Returns a list of dictionaries representing the values of each brain |
def _loadable_get_(name, self):
"Used to lazily-evaluate & memoize an attribute."
func = getattr(self._attr_func_, name)
ret = func()
setattr(self._attr_data_, name, ret)
setattr(
type(self),
name,
property(
functools.partial(se... | module function_definition identifier parameters identifier identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call identifier argument_list attribute identifier identifier identifier expression_statement assignment identifier call identifier a... | Used to lazily-evaluate & memoize an attribute. |
def _get_req_rem_geo(self, ds_info):
if ds_info['dataset_groups'][0].startswith('GM'):
if self.use_tc is False:
req_geo = 'GMODO'
rem_geo = 'GMTCO'
else:
req_geo = 'GMTCO'
rem_geo = 'GMODO'
elif ds_info['dataset_grou... | module function_definition identifier parameters identifier identifier block if_statement call attribute subscript subscript identifier string string_start string_content string_end integer identifier argument_list string string_start string_content string_end block if_statement comparison_operator attribute identifier... | Find out which geolocation files are needed. |
def _instant_search(self):
_keys = []
for k,v in self.searchables.iteritems():
if self.string in v:
_keys.append(k)
self.candidates.append(_keys) | module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list block if_statement comparison_operator attribute identifier identifier identifier blo... | Determine possible keys after a push or pop |
def python(self, cmd):
python_bin = self.cmd_path('python')
cmd = '{0} {1}'.format(python_bin, cmd)
return self._execute(cmd) | 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 expression_statement assignment identifier call attribute string string_start string_content string_end... | Execute a python script using the virtual environment python. |
def move_down(self):
self.at(ardrone.at.pcmd, True, 0, 0, -self.speed, 0) | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list attribute attribute identifier identifier identifier true integer integer unary_operator attribute identifier identifier integer | Make the drone decent downwards. |
def insertIndividual(self, individual):
try:
models.Individual.create(
id=individual.getId(),
datasetId=individual.getParentContainer().getId(),
name=individual.getLocalId(),
description=individual.getDescription(),
crea... | module function_definition identifier parameters identifier identifier block try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier call attribute identifier identifier argument_list keyword_argument identifier call attribute call att... | Inserts the specified individual into this repository. |
def log_weights(self):
m = self.kernel.feature_log_prob_[self._match_class_pos()]
u = self.kernel.feature_log_prob_[self._nonmatch_class_pos()]
return self._prob_inverse_transform(m - u) | module function_definition identifier parameters identifier block expression_statement assignment identifier subscript attribute attribute identifier identifier identifier call attribute identifier identifier argument_list expression_statement assignment identifier subscript attribute attribute identifier identifier id... | Log weights as described in the FS framework. |
def _handle_metadata(self, node, scope, ctxt, stream):
self._dlog("handling node metadata {}".format(node.metadata.keyvals))
keyvals = node.metadata.keyvals
metadata_info = []
if "watch" in node.metadata.keyvals or "update" in keyvals:
metadata_info.append(
se... | module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute attribute identifier identifier identifier... | Handle metadata for the node |
def unique(self, sort=False):
unique_vals = np.unique(self.numpy())
if sort:
unique_vals = np.sort(unique_vals)
return unique_vals | module function_definition identifier parameters identifier default_parameter identifier false block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list if_statement identifier block expression_statement assignment identifier c... | Return unique set of values in image |
def stop(self):
if self._disconnector:
self._disconnector.stop()
self.client.disconnect() | 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 call attribute attribute identifier identifier identifier argument_list | Stop this gateway agent. |
def zone(self) -> Optional[str]:
if self._device_category == DC_BASEUNIT:
return None
return '{:02x}-{:02x}'.format(self._group_number, self._unit_number) | module function_definition identifier parameters identifier type generic_type identifier type_parameter type identifier block if_statement comparison_operator attribute identifier identifier identifier block return_statement none return_statement call attribute string string_start string_content string_end identifier a... | Zone the device is assigned to. |
def touch(path):
with open(path, 'a') as f:
os.utime(path, None)
f.close() | module function_definition identifier parameters identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier n... | Creates a file located at the given path. |
def endElement(self, name):
content = ''.join(self._contentList)
if name == 'xtvd':
self._progress.endItems()
else:
try:
if self._context == 'stations':
self._endStationsNode(name, content)
elif self._context == 'lineups... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute string string_start string_end identifier argument_list attribute identifier identifier if_statement comparison_operator identifier string string_start string_content string_end block e... | Callback run at the end of each XML element |
def check_cache(self, e_tag, match):
if e_tag != match:
return False
self.send_response(304)
self.send_header("ETag", e_tag)
self.send_header("Cache-Control",
"max-age={0}".format(self.server.max_age))
self.end_headers()
thread_local.s... | module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator identifier identifier block return_statement false expression_statement call attribute identifier identifier argument_list integer expression_statement call attribute identifier identifier argument_l... | Checks the ETag and sends a cache match response if it matches. |
def passwordReset1to2(old):
new = old.upgradeVersion(old.typeName, 1, 2, installedOn=None)
for iface in new.store.interfacesFor(new):
new.store.powerDown(new, iface)
new.deleteFromStore() | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier integer integer keyword_argument identifier none for_statement identifier call attribute attribute identifier identifier identif... | Power down and delete the item |
def unbake(self):
for key in self.dct:
self.dct[key].pop('__abs_time__', None)
self.is_baked = False | module function_definition identifier parameters identifier block for_statement identifier attribute identifier identifier block expression_statement call attribute subscript attribute identifier identifier identifier identifier argument_list string string_start string_content string_end none expression_statement assig... | Remove absolute times for all keys. |
def score(self, testing_features, testing_labels):
yhat = self.predict(testing_features)
return self.scoring_function(testing_labels,yhat) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement call attribute identifier identifier argument_list identifier identifier | estimates accuracy on testing set |
def start(self):
assert not self.is_running(), 'Attempted to start an energy measurement while one was already running.'
self._measurement_process = subprocess.Popen(
[self._executable, '-r'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
bufsize=10000,
... | module function_definition identifier parameters identifier block assert_statement not_operator call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list list attribu... | Starts the external measurement program. |
def nodes(self):
getnode = self._nodes.__getitem__
return [getnode(nid) for nid in self._nodeids] | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute attribute identifier identifier identifier return_statement list_comprehension call identifier argument_list identifier for_in_clause identifier attribute identifier identifier | Return the list of nodes. |
def make_channel(name, samples, data=None, verbose=False):
if verbose:
llog = log['make_channel']
llog.info("creating channel {0}".format(name))
chan = Channel('channel_{0}'.format(name))
chan.SetStatErrorConfig(0.05, "Poisson")
if data is not None:
if verbose:
llog.i... | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier false block if_statement identifier block expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement call attribut... | Create a Channel from a list of Samples |
def execute(self):
creator = make_creator(self.params.config,
storage_path=self.params.storage)
cluster_name = self.params.cluster
try:
cluster = creator.load_cluster(cluster_name)
except (ClusterNotFound, ConfigurationError) as ex:
... | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list attribute attribute identifier identifier identifier keyword_argument identifier attribute attribute identifier identifier identifier expression_statement assignment identifier attr... | Load the cluster and build a GC3Pie configuration snippet. |
def login():
form_class = _security.login_form
if request.is_json:
form = form_class(MultiDict(request.get_json()))
else:
form = form_class(request.form)
if form.validate_on_submit():
login_user(form.user, remember=form.remember.data)
after_this_request(_commit)
i... | module function_definition identifier parameters block expression_statement assignment identifier attribute identifier identifier if_statement attribute identifier identifier block expression_statement assignment identifier call identifier argument_list call identifier argument_list call attribute identifier identifier... | View function for login view |
def process_request(self, request):
restricted_request_uri = request.path.startswith(
reverse('admin:index') or "cms-toolbar-login" in request.build_absolute_uri()
)
if restricted_request_uri and request.method == 'POST':
if AllowedIP.objects.count() > 0:
... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list boolean_operator call identifier argument_list string string_start string_content string_end comparison_operator string string_s... | Check if the request is made form an allowed IP |
def unmasked(self, depth=0.01):
return 1 - (np.hstack(self._O2) +
np.hstack(self._O3) / depth) / np.hstack(self._O1) | module function_definition identifier parameters identifier default_parameter identifier float block return_statement binary_operator integer binary_operator parenthesized_expression binary_operator call attribute identifier identifier argument_list attribute identifier identifier binary_operator call attribute identif... | Return the unmasked overfitting metric for a given transit depth. |
def _add_enum_member(enum, name, value, bitmask=DEFMASK):
error = idaapi.add_enum_member(enum, name, value, bitmask)
if error:
raise _enum_member_error(error, enum, name, value, bitmask) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier identifier identifier if_statement identifier block raise_statement call ide... | Add an enum member. |
def handle_trunks(self, trunks, event_type):
LOG.debug("Trunks event received: %(event_type)s. Trunks: %(trunks)s",
{'event_type': event_type, 'trunks': trunks})
if event_type == events.DELETED:
for trunk in trunks:
self._trunks.pop(trunk.id, None)
e... | module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end dictionary pair string string_start string_content string_end identifier pair string string_start string_content s... | Trunk data model change from the server. |
def transform(function):
def transform_fn(_, result):
if isinstance(result, Nothing):
return result
lgr.debug("Transforming %r with %r", result, function)
try:
return function(result)
except:
exctype, value, tb = sys... | module function_definition identifier parameters identifier block function_definition identifier parameters identifier identifier block if_statement call identifier argument_list identifier identifier block return_statement identifier expression_statement call attribute identifier identifier argument_list string string... | Return a processor for a style's "transform" function. |
def compile(self):
result = TEMPLATE
for rule in self.rules:
if rule[2]:
arrow = '=>'
else:
arrow = '->'
repr_rule = repr(rule[0] + arrow + rule[1])
result += "algo.add_rule({repr_rule})\n".format(repr_rule=repr_rule)
... | module function_definition identifier parameters identifier block expression_statement assignment identifier identifier for_statement identifier attribute identifier identifier block if_statement subscript identifier integer block expression_statement assignment identifier string string_start string_content string_end ... | Return python code for create and execute algo. |
def create_dispatcher(self):
before_context = max(self.args.before_context, self.args.context)
after_context = max(self.args.after_context, self.args.context)
if self.args.files_with_match is not None or self.args.count or self.args.only_matching or self.args.quiet:
return Unbuffered... | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list at... | Return a dispatcher for configured channels. |
def json_encoder_default(obj):
if isinstance(obj, numbers.Integral) and (obj < min_safe_integer or obj > max_safe_integer):
return str(obj)
if isinstance(obj, np.integer):
return str(obj)
elif isinstance(obj, np.floating):
return float(obj)
elif isinstance(obj, np.ndarray):
... | module function_definition identifier parameters identifier block if_statement boolean_operator call identifier argument_list identifier attribute identifier identifier parenthesized_expression boolean_operator comparison_operator identifier identifier comparison_operator identifier identifier block return_statement ca... | JSON encoder function that handles some numpy types. |
def shutdown(self):
'Close all peer connections and stop listening for new ones'
log.info("shutting down")
for peer in self._dispatcher.peers.values():
peer.go_down(reconnect=False)
if self._listener_coro:
backend.schedule_exception(
errors._Ba... | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end for_statement identifier call attribute attribute attribute identifie... | Close all peer connections and stop listening for new ones |
def get(self, path, query, **options):
api_options = self._parse_api_options(options, query_string=True)
query_options = self._parse_query_options(options)
parameter_options = self._parse_parameter_options(options)
query = _merge(query_options, api_options, parameter_options, query)
... | module function_definition identifier parameters identifier identifier identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier true expression_statement assignment identifier call attribute ... | Parses GET request options and dispatches a request. |
def _replay_info(replay_path):
if not replay_path.lower().endswith("sc2replay"):
print("Must be a replay.")
return
run_config = run_configs.get()
with run_config.start(want_rgb=False) as controller:
info = controller.replay_info(run_config.replay_data(replay_path))
print("-" * 60)
print(info) | module function_definition identifier parameters identifier block if_statement not_operator call attribute call attribute identifier identifier argument_list identifier argument_list string string_start string_content string_end block expression_statement call identifier argument_list string string_start string_content... | Query a replay for information. |
def _check_instrument(self):
instr = INSTRUMENTS.get(self.platform_name, self.instrument.lower())
if instr != self.instrument.lower():
self.instrument = instr
LOG.warning("Inconsistent instrument/satellite input - " +
"instrument set to %s", self.instrumen... | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier call attribute attribute identifier identifier identifier argument_list if_statement comparison_operator identifier call attribu... | Check and try fix instrument name if needed |
def _load_int(self):
values = numpy.fromfile(self.filepath_int)
if self.NDIM > 0:
values = values.reshape(self.seriesshape)
return values | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier if_statement comparison_operator attribute identifier identifier integer block expression_statement assignment identifier call a... | Load internal data from file and return it. |
def dir(self, path='/', slash=True, bus=False, timeout=0):
if slash:
msg = MSG_DIRALLSLASH
else:
msg = MSG_DIRALL
if bus:
flags = self.flags | FLG_BUS_RET
else:
flags = self.flags & ~FLG_BUS_RET
ret, data = self.sendmess(msg, str2by... | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end default_parameter identifier true default_parameter identifier false default_parameter identifier integer block if_statement identifier block expression_statement assignment identifier ... | list entities at path |
def OnGoToCell(self, event):
row, col, tab = event.key
try:
self.grid.actions.cursor = row, col, tab
except ValueError:
msg = _("Cell {key} outside grid shape {shape}").format(
key=event.key, shape=self.grid.code_array.shape)
post_command_event... | module function_definition identifier parameters identifier identifier block expression_statement assignment pattern_list identifier identifier identifier attribute identifier identifier try_statement block expression_statement assignment attribute attribute attribute identifier identifier identifier identifier express... | Shift a given cell into view |
def run(configobj=None):
clean(configobj['input'],
suffix=configobj['suffix'],
stat=configobj['stat'],
maxiter=configobj['maxiter'],
sigrej=configobj['sigrej'],
lower=configobj['lower'],
upper=configobj['upper'],
binwidth=configobj['binwidth'],
... | module function_definition identifier parameters default_parameter identifier none block expression_statement call identifier argument_list subscript identifier string string_start string_content string_end keyword_argument identifier subscript identifier string string_start string_content string_end keyword_argument i... | TEAL interface for the `clean` function. |
def on_any_event(self, event):
if os.path.isfile(event.src_path):
self.callback(event.src_path, **self.kwargs) | module function_definition identifier parameters identifier identifier block if_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier dictionary_splat... | File created or modified |
def _urlopen_as_json(self, url, headers=None):
req = Request(url, headers=headers)
return json.loads(urlopen(req).read()) | module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier identifier return_statement call attribute identifier identifier argument_list call attribute cal... | Shorcut for return contents as json |
def state(self):
state = self._resource.get('state', self.default_state)
if state in State:
return state
else:
return getattr(State, state) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end attribute identifier identifier if_statement comparison_operator identifier identifier block ... | Get the Document's state |
def from_sbv(cls, file):
parser = SBVParser().read(file)
return cls(file=file, captions=parser.captions) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute call identifier argument_list identifier argument_list identifier return_statement call identifier argument_list keyword_argument identifier identifier keyword_argument identifier attri... | Reads captions from a file in YouTube SBV format. |
def unregister(self, filter_name):
if filter_name in self.filter_list:
self.filter_list.pop(filter_name) | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Unregister a filter from the filter list |
def validate_participation(self):
if self.participation not in self._participation_valid_values:
raise ValueError("participation should be one of: {valid}".format(
valid=", ".join(self._participation_valid_values)
)) | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier attribute identifier identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list keyword_argument id... | Ensure participation is of a certain type. |
def importData(directory):
dataTask = OrderedDict()
dataQueue = OrderedDict()
for fichier in sorted(os.listdir(directory)):
try:
with open("{directory}/{fichier}".format(**locals()), 'rb') as f:
fileName, fileType = fichier.rsplit('-', 1)
if fileType == "Q... | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call identifier argument_list for_statement identifier call identifier argument_list call attribute identifier identifier argument_list id... | Parse the input files and return two dictionnaries |
def which(software, strip_newline=True):
if software is None:
software = "singularity"
cmd = ['which', software ]
try:
result = run_command(cmd)
if strip_newline is True:
result['message'] = result['message'].strip('\n')
return result
except:
return No... | module function_definition identifier parameters identifier default_parameter identifier true block if_statement comparison_operator identifier none block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier list string string_start string_c... | get_install will return the path to where an executable is installed. |
def chirp_stimul():
from scipy.signal import chirp, hilbert
duration = 1.0
fs = 256
samples = int(fs * duration)
t = np.arange(samples) / fs
signal = chirp(t, 20.0, t[-1], 100.0)
signal *= (1.0 + 0.5 * np.sin(2.0 * np.pi * 3.0 * t))
analytic_signal = hilbert(signal) * 0.5
ref_abs = n... | module function_definition identifier parameters block import_from_statement dotted_name identifier identifier dotted_name identifier dotted_name identifier expression_statement assignment identifier float expression_statement assignment identifier integer expression_statement assignment identifier call identifier argu... | Amplitude modulated chirp signal |
async def jsk_hide(self, ctx: commands.Context):
if self.jsk.hidden:
return await ctx.send("Jishaku is already hidden.")
self.jsk.hidden = True
await ctx.send("Jishaku is now hidden.") | module function_definition identifier parameters identifier typed_parameter identifier type attribute identifier identifier block if_statement attribute attribute identifier identifier identifier block return_statement await call attribute identifier identifier argument_list string string_start string_content string_en... | Hides Jishaku from the help command. |
def error(self, id, errorCode, errorString):
if errorCode == 165:
sys.stderr.write("TWS INFO - %s: %s\n" % (errorCode, errorString))
elif errorCode >= 501 and errorCode < 600:
sys.stderr.write("TWS CLIENT-ERROR - %s: %s\n" % (errorCode, errorString))
elif errorCode >= 100... | module function_definition identifier parameters identifier identifier identifier identifier block if_statement comparison_operator identifier integer block expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content escape_sequence str... | Error during communication with TWS |
def _set_types(self):
for c in (self.x, self.y):
if not ( isinstance(c, int) or isinstance(c, float) ):
raise(RuntimeError('x, y coords should be int or float'))
if isinstance(self.x, int) and isinstance(self.y, int):
self._dtype = "int"
else:
... | module function_definition identifier parameters identifier block for_statement identifier tuple attribute identifier identifier attribute identifier identifier block if_statement not_operator parenthesized_expression boolean_operator call identifier argument_list identifier identifier call identifier argument_list ide... | Make sure that x, y have consistent types and set dtype. |
def _get_jvm_opts(out_file, data):
resources = config_utils.get_resources("purple", data["config"])
jvm_opts = resources.get("jvm_opts", ["-Xms750m", "-Xmx3500m"])
jvm_opts = config_utils.adjust_opts(jvm_opts, {"algorithm": {"memory_adjust":
{... | 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 subscript identifier string string_start string_content string_end expression_statement assignment iden... | Retrieve Java options, adjusting memory for available cores. |
def package_remove(name):
DETAILS = _load_state()
DETAILS['packages'].pop(name)
_save_state(DETAILS)
return DETAILS['packages'] | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list expression_statement call attribute subscript identifier string string_start string_content string_end identifier argument_list identifier expression_statement call identifier argum... | Remove a "package" on the REST server |
def token(self, value):
if value and not isinstance(value, Token):
value = Token(value)
self._token = value | module function_definition identifier parameters identifier identifier block if_statement boolean_operator identifier not_operator call identifier argument_list identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment attribute ident... | Setter to convert any token dict into Token instance |
def readme(fname):
md = open(os.path.join(os.path.dirname(__file__), fname)).read()
output = md
try:
import pypandoc
output = pypandoc.convert(md, 'rst', format='md')
except ImportError:
pass
return output | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute call identifier argument_list call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier identifier ... | Reads a markdown file and returns the contents formatted as rst |
def setup(self):
super(BaseMonitor, self).setup()
self.monitor_thread = LoopFuncThread(self._monitor_func)
self.monitor_thread.start() | module function_definition identifier parameters identifier block expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier expression_stat... | Make sure the monitor is ready for fuzzing |
def _build_cache_key(self, uri):
key = uri.clone(ext=None, version=None)
if six.PY3:
key = key.encode('utf-8')
return sha1(key).hexdigest() | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier none keyword_argument identifier none if_statement attribute identifier identifier block expression_statement assignment ... | Build sha1 hex cache key to handle key length and whitespace to be compatible with Memcached |
def render_source(self, source, variables=None):
if variables is None:
variables = {}
template = self._engine.from_string(source)
return template.render(**variables) | module function_definition identifier parameters identifier identifier default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier dictionary expression_statement assignment identifier call attribute attribute identifier identifier identifier... | Render a source with the passed variables. |
def update_feature_type_rates(sender, instance, created, *args, **kwargs):
if created:
for role in ContributorRole.objects.all():
FeatureTypeRate.objects.create(role=role, feature_type=instance, rate=0) | module function_definition identifier parameters identifier identifier identifier list_splat_pattern identifier dictionary_splat_pattern identifier block if_statement identifier block for_statement identifier call attribute attribute identifier identifier identifier argument_list block expression_statement call attribu... | Creates a default FeatureTypeRate for each role after the creation of a FeatureTypeRate. |
def refactor_module_to_package(self):
refactor = ModuleToPackage(self.project, self.resource)
return self._get_changes(refactor) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier attribute identifier identifier return_statement call attribute identifier identifier argument_list identifier | Convert the current module into a package. |
def to_localtime(time):
utc_time = time.replace(tzinfo=timezone.utc)
to_zone = timezone.get_default_timezone()
return utc_time.astimezone(to_zone) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list return... | Converts naive datetime to localtime based on settings |
def dehydrate(self):
result = {}
for attr in self.attrs:
result[attr] = getattr(self, attr)
return result | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary for_statement identifier attribute identifier identifier block expression_statement assignment subscript identifier identifier call identifier argument_list identifier identifier return_statement iden... | Return a dict representing this bucket. |
def create(ctx, scenario_name, driver_name):
args = ctx.obj.get('args')
subcommand = base._get_subcommand(__name__)
command_args = {
'subcommand': subcommand,
'driver_name': driver_name,
}
base.execute_cmdline_scenarios(scenario_name, args, command_args) | module function_definition identifier parameters identifier 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 identifier id... | Use the provisioner to start the instances. |
def write_path(self, path_value):
parent_dir = os.path.dirname(self.path)
try:
os.makedirs(parent_dir)
except OSError:
pass
with open(self.path, "w") as fph:
fph.write(path_value.value) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier try_statement block expression_statement call attribute identifier identifier argument_list iden... | this will overwrite dst path - be careful |
def parse_file(self, filename, encoding=None, debug=False):
stream = codecs.open(filename, "r", encoding)
try:
return self.parse_stream(stream, debug)
finally:
stream.close() | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier false block expression_statement assignment identifier call attribute identifier identifier argument_list identifier string string_start string_content string_end identifier try_statemen... | Parse a file and return the syntax tree. |
def _spawn_redis_connection_thread(self):
self.logger.debug("Spawn redis connection thread")
self.redis_connected = False
self._redis_thread = Thread(target=self._setup_redis)
self._redis_thread.setDaemon(True)
self._redis_thread.start() | module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment attribute identifier identifier false expression_statement assignment attribute ide... | Spawns a redis connection thread |
def change_zoom(self, zoom):
state = self.state
if self.mouse_pos:
(x,y) = (self.mouse_pos.x, self.mouse_pos.y)
else:
(x,y) = (state.width/2, state.height/2)
(lat,lon) = self.coordinates(x, y)
state.ground_width *= zoom
state.ground_width = max(sta... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute identifier identifier if_statement attribute identifier identifier block expression_statement assignment tuple_pattern identifier identifier tuple attribute attribute identifier identifier i... | zoom in or out by zoom factor, keeping centered |
def _validate(self, data):
errors = {}
if not self._enabled:
return errors
for field in self.validators:
field_errors = []
for validator in self.validators[field]:
try:
validator(data.get(field, None))
except... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary if_statement not_operator attribute identifier identifier block return_statement identifier for_statement identifier attribute identifier identifier block expression_statement assignment id... | Helper to run validators on the field data. |
def ensure():
LOGGER.debug('checking repository')
if not os.path.exists('.git'):
LOGGER.error('This command is meant to be ran in a Git repository.')
sys.exit(-1)
LOGGER.debug('repository OK') | module function_definition identifier parameters block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end if_statement not_operator call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end blo... | Makes sure the current working directory is a Git repository. |
def auth_token(cls, token):
store = goldman.sess.store
login = store.find(cls.RTYPE, 'token', token)
if not login:
msg = 'No login found with that token. It may have been revoked.'
raise AuthRejected(**{'detail': msg})
elif login.locked:
msg = 'The log... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier string string_start s... | Callback method for OAuth 2.0 bearer token middleware |
def selectedIndexes(self):
model = self.model()
indexes = []
for comp in self._selectedComponents:
index = model.indexByComponent(comp)
if index is None:
self._selectedComponents.remove(comp)
else:
indexes.append(index)
... | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier list for_statement identifier attribute identifier identifier block expression_statement assignment identifier call a... | Returns a list of QModelIndex currently in the model |
def attrib(self):
return dict([
('probability', str(self.probability)),
('strike', str(self.strike)),
('dip', str(self.dip)),
('rake', str(self.rake)),
]) | module function_definition identifier parameters identifier block return_statement call identifier argument_list list tuple string string_start string_content string_end call identifier argument_list attribute identifier identifier tuple string string_start string_content string_end call identifier argument_list attrib... | A dict of XML element attributes for this NodalPlane. |
def run_command(command, args):
for category, commands in iteritems(command_categories):
for existing_command in commands:
if existing_command.match(command):
existing_command.run(args) | module function_definition identifier parameters identifier identifier block for_statement pattern_list identifier identifier call identifier argument_list identifier block for_statement identifier identifier block if_statement call attribute identifier identifier argument_list identifier block expression_statement cal... | Run all tasks registered in a command. |
def process_form(self, instance, field, form, empty_marker=None,
emptyReturnsMarker=False):
name = field.getName()
otherName = "%s_other" % name
value = form.get(otherName, empty_marker)
regex = field.widget.field_regex
if value and not re.match(regex, value)... | module function_definition identifier parameters identifier identifier identifier identifier default_parameter identifier none default_parameter identifier false block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier binary_operator... | A typed in value takes precedence over a selected value. |
def variants(ctx, variant_id, chromosome, end_chromosome, start, end, variant_type,
sv_type):
if sv_type:
variant_type = 'sv'
adapter = ctx.obj['adapter']
if (start or end):
if not (chromosome and start and end):
LOG.warning("Regions must be specified with chromosome... | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier identifier identifier block if_statement identifier block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier subscript attri... | Display variants in the database. |
def _add_saved_device_info(self, **kwarg):
addr = kwarg.get('address')
_LOGGER.debug('Found saved device with address %s', addr)
self._saved_devices[addr] = kwarg | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string... | Register device info from the saved data file. |
def scan(subtitles):
from importlib.util import find_spec
try:
import subnuker
except ImportError:
fatal('Unable to scan subtitles. Please install subnuker.')
aeidon = find_spec('aeidon') is not None
if sys.stdin.isatty():
args = (['--aeidon'] if aeidon else []) + \
... | module function_definition identifier parameters identifier block import_from_statement dotted_name identifier identifier dotted_name identifier try_statement block import_statement dotted_name identifier except_clause identifier block expression_statement call identifier argument_list string string_start string_conten... | Remove advertising from subtitles. |
def main():
(options, _) = _parse_args()
if options.change_password:
c.keyring_set_password(c["username"])
sys.exit(0)
if options.select:
courses = client.get_courses()
c.selection_dialog(courses)
c.save()
sys.exit(0)
if options.stop:
os.system("ki... | module function_definition identifier parameters block expression_statement assignment tuple_pattern identifier identifier call identifier argument_list if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list subscript identifier string string_start str... | parse command line options and either launch some configuration dialog or start an instance of _MainLoop as a daemon |
def convert_context_to_csv(self, context):
content = []
date_headers = context['date_headers']
headers = ['Name']
headers.extend([date.strftime('%m/%d/%Y') for date in date_headers])
headers.append('Total')
content.append(headers)
summaries = context['summaries']
... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier list string string_start string_content st... | Convert the context dictionary into a CSV file. |
def setup_db(session, botconfig, confdir):
Base.metadata.create_all(session.connection())
if not session.get_bind().has_table('alembic_version'):
conf_obj = config.Config()
conf_obj.set_main_option('bot_config_path', confdir)
with resources.path('cslbot', botconfig['alembic']['script_loc... | module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list if_statement not_operator call attribute call attribute identifier identifier argument_l... | Sets up the database. |
def _format_native_types(self, na_rep='', quoting=None, **kwargs):
mask = isna(self)
if not self.is_object() and not quoting:
values = np.asarray(self).astype(str)
else:
values = np.array(self, dtype=object, copy=True)
values[mask] = na_rep
return values | module function_definition identifier parameters identifier default_parameter identifier string string_start string_end default_parameter identifier none dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement boolean_operator not_operat... | Actually format specific types of the index. |
def reverse(self, matching_name, **kwargs):
for record in self.matching_records:
if record.name == matching_name:
path_template = record.path_template
break
else:
raise NotReversed
if path_template.wildcard_name:
l = kwargs.get(... | module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block for_statement identifier attribute identifier identifier block if_statement comparison_operator attribute identifier identifier identifier block expression_statement assignment identifier attribute identifie... | Getting a matching name and URL args and return a corresponded URL |
def show_batch_runner(self):
from safe.gui.tools.batch.batch_dialog import BatchDialog
dialog = BatchDialog(
parent=self.iface.mainWindow(),
iface=self.iface,
dock=self.dock_widget)
dialog.exec_() | module function_definition identifier parameters identifier block import_from_statement dotted_name identifier identifier identifier identifier identifier dotted_name identifier expression_statement assignment identifier call identifier argument_list keyword_argument identifier call attribute attribute identifier ident... | Show the batch runner dialog. |
def _get_all(cls, parent_id=None, grandparent_id=None):
client = cls._get_client()
endpoint = cls._endpoint.format(resource_id="",
parent_id=parent_id or "",
grandparent_id=grandparent_id or "")
resources = []
... | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute attribute identifier identifier id... | Retrives all the required resources. |
def role_delete(role_id, endpoint_id):
client = get_client()
res = client.delete_endpoint_role(endpoint_id, role_id)
formatted_print(res, text_format=FORMAT_TEXT_RAW, response_key="message") | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement call identifier argument_list ide... | Executor for `globus endpoint role delete` |
def load_and_save_image(url, destination):
from urllib2 import Request, urlopen, URLError, HTTPError
req = Request(url)
try:
f = urlopen(req)
print "downloading " + url
local_file = open(destination, "wb")
local_file.write(f.read())
local_file.close()
file_typ... | module function_definition identifier parameters identifier identifier block import_from_statement dotted_name identifier dotted_name identifier dotted_name identifier dotted_name identifier dotted_name identifier expression_statement assignment identifier call identifier argument_list identifier try_statement block ex... | Download image from given url and saves it to destination. |
def screenshot(self, *args):
from mss import mss
if not os.path.exists("screenshots"):
os.makedirs("screenshots")
box = {
"top": self.winfo_y(),
"left": self.winfo_x(),
"width": self.winfo_width(),
"height": self.winfo_height()
... | module function_definition identifier parameters identifier list_splat_pattern identifier block import_from_statement dotted_name identifier dotted_name identifier if_statement not_operator call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end block expres... | Take a screenshot, crop and save |
def _get_gos_upper(self, ntpltgo1, max_upper, go2parentids):
goids_possible = ntpltgo1.gosubdag.go2obj.keys()
return self._get_gosrcs_upper(goids_possible, max_upper, go2parentids) | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list return_statement call attribute identifier identifier argument_list identifier identi... | Plot a GO DAG for the upper portion of a single Group of user GOs. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.