query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Stores the old gradient table for recalibration purposes. | def store_old_table(self):
for group in self.param_groups:
for p in group['params']:
gk = p.grad.data
param_state = self.state[p]
gktbl = param_state['gktbl']
gavg = param_state['gavg']
param_state['gktbl_old'] = gkt... | [
"def persist_gradient():\n p = tf.constant(3.0)\n with tf.GradientTape(persistent=True) as g:\n g.watch(p)\n q = p * p\n r = q * q\n dr_dp = g.gradient(r, p) # 108.0 (4*p^3 at p = 3)\n dq_dp = g.gradient(q, p) # 6.0\n del g # Drop the reference to the tape\n return (dr_dp, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a named plate type 96 or 384 according to num_wells | def create_plate(num_wells, name):
rows, cols = calc.rows_columns(int(num_wells))
new_plate = plate.Plate(rows, cols, name)
return new_plate | [
"def plate_well(well):\n\n return well['Meta']['Plate_Well']",
"def return_agar_plates(wells=6):\n if wells == 6:\n plates = {\"lb_miller_50ug_ml_kan\": \"ki17rs7j799zc2\",\n \"lb_miller_100ug_ml_amp\": \"ki17sbb845ssx9\",\n \"lb_miller_100ug_ml_specto\": \"ki17sbb9r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Cubic interpolation. Compute the coefficients of the polynomial interpolating the points (xi[i],yi[i]) for i = 0,1,2,3. Returns c, an array containing the coefficients of p(x) = c[0] + c[1]x + c[2]x2 + c[3]x3. | def cubic_interp(xi,yi):
# check inputs and print error message if not valid:
error_message = "xi and yi should have type numpy.ndarray"
assert (type(xi) is np.ndarray) and (type(yi) is np.ndarray), error_message
error_message = "xi and yi should have length 3"
assert len(xi)==4 and len(yi)==4, e... | [
"def cubic_interpol(X_P, Y_P):\r\n y_derivs = derivatives( X_P, Y_P ).flatten() # flatten as FB_sub returns 2d array\r\n \r\n for j in np.arange( X_P.shape[0] - 1 ): # for every x[i] and x[i+1] pair\r\n plot_points = np.linspace( X_P[j], X_P[j+1], 20) # points to plot in the interval\r\n para... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Score conversions and redirect as specified by url params Expects a 'continue' url parameter for the destination, and a 'conversion_name' url parameter for each conversion to score. | def get(self):
cont = self.request.get('continue', default_value='/')
# Check whether redirecting to an absolute or relative url
netloc = urlparse.urlsplit(cont).netloc
if netloc:
# Disallow absolute urls to prevent arbitrary open redirects
raise custom_exception... | [
"def process_conversion(queries, query, src, dst, val, currencies, wf):\n ####################################################################################################\n # Make the currency case insensitive\n ###########################################################################################... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fires on broadcast messages | def process_broadcast(data):
logger.info(f"Broadcast: {data}") | [
"def test_broadcast_message(self):\n\n typhoonae.websocket.broadcast_message('My broadcast message.')",
"def broadcastMessage(self, data):\n print('Broadcast message to all users(unrealized) ')\n # TODO: realise method which send 1 message to all users",
"def broadcast(self, broadcast):\n\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A function to get necessary labels for the waiting times of different thresholds | def get_plot_for_different_thresholds_labels(measurement_type):
if measurement_type == "w":
title = "Waiting times over different thresholds"
y_axis_label = "Waiting Time"
elif measurement_type == "b":
title = "Blocking times over different thresholds"
y_axis_label = "Blocking Ti... | [
"def get_bt_threshold(self):\r\n verbose(\"extracting bump times from \" + self.title + \" by threshold method\",3)\r\n \r\n bumptimes = []\r\n lastbumptime = -9999\r\n threshold = -1\r\n \r\n #Setting threshold :\r\n if (c.THRESHOLD_AUTOSET == \"maxlevel\"):\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the proportion waiting times within the target for a given trial of a threshold | def get_target_proportions_of_current_trial(individuals, target):
ambulance_waits, ambulance_target_waits = 0, 0
other_waits, other_target_waits = 0, 0
for individual in individuals:
ind_class = len(individual.data_records) - 1
rec = individual.data_records[-1]
if rec.node == 2 and i... | [
"def _probe_wait_time(self):\n r = self.probe_cycle_time / float(len(self.servers)) #self.probe_cycle_time=5\n r = max(.25, r) # Cap it at four per second\n return r",
"def precision_threshold(predictions, targets, threshold=0.7):\n number_of_examples_meeting_threshold = 0\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates the mean proportion of times that satisfy the target of all trials for the current threshold iteration Returns float, float, float The mean waiting times for ambulance patients, other patients and all patients for a given threshold | def get_mean_waits_of_current_threshold(
lambda_2,
lambda_1,
mu,
num_of_servers,
threshold,
seed_num,
num_of_trials,
runtime,
target,
):
current_ambulance_proportions = []
current_other_proportions = []
current_combined_proportions = []
if seed_num == None:
s... | [
"def get_target_proportions_of_current_trial(individuals, target):\n ambulance_waits, ambulance_target_waits = 0, 0\n other_waits, other_target_waits = 0, 0\n for individual in individuals:\n ind_class = len(individual.data_records) - 1\n rec = individual.data_records[-1]\n if rec.node... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Builds a plot that shows the proportion of individuals that satisfy the desired waiting time target. The plot shows the proportions of ambulance patients, other patients and the combined proportion of the two, that satisfy the target. | def make_plot_for_proportion_within_target(
lambda_2,
lambda_1,
mu,
num_of_servers,
num_of_trials,
seed_num,
target,
runtime=1440,
max_threshold=None,
):
ambulance_proportions = []
other_proportions = []
all_proportions = []
if max_threshold == None:
max_thres... | [
"def get_target_proportions_of_current_trial(individuals, target):\n ambulance_waits, ambulance_target_waits = 0, 0\n other_waits, other_target_waits = 0, 0\n for individual in individuals:\n ind_class = len(individual.data_records) - 1\n rec = individual.data_records[-1]\n if rec.node... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A function to get necessary labels for the two hospitals plot | def get_two_hospital_plot_labels(measurement_type):
if measurement_type == "w":
title = "Waiting times of two hospitals over different distribution of patients"
y_axis_label = "Waiting Time"
else:
title = (
"Blocking times of two hospitals over different distribution of patie... | [
"def label(graph, hi_thres, med_thres):\n\n extended_deg_size = hi_thres\n hi_pairs = get_hi_pairs(graph, hi_thres, extended_deg_size)\n sorted_hi_nodes = [x[0] for x in hi_pairs]\n med_pairs = get_med_pairs(graph, med_thres, hi_thres, sorted_hi_nodes)\n return (hi_pairs, med_pairs)",
"def get_labe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make a plot of the waiting/blocking time between two hospitals that have a joint arrival rate of ambulance patients. In other words plots the waiting / blocking times of patients based on how the ambulance patients are distributed among hospitals | def make_plot_two_hospitals_arrival_split(
lambda_2,
lambda_1_1,
lambda_1_2,
mu_1,
mu_2,
num_of_servers_1,
num_of_servers_2,
threshold_1,
threshold_2,
measurement_type="b",
seed_num_1=None,
seed_num_2=None,
warm_up_time=100,
trials=1,
accuracy=10,
runtime=... | [
"def compare(self, pulse1, pulse2):\n plt.title(\"pulse propagation after a given distance\")\n self.fig1= plt.subplot(221) #left top \n self.fig1.plot(pulse1.X,np.abs(pulse1.Y))\n self.fig1b=self.fig1.twinx()\n self.fig1b.plot(pulse1.X,pulse1.phase, 'r--')\n self.fig1.set_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Navigate and extract data about avalanche status | def navigate_and_extract_avalanche_data(self):
self.browser.get(self.url)
avalanche_status = {}
try:
avalanche_level = self.browser.find_element_by_xpath(
'//*[@id="law-master"]/div[1]/div[1]/span/span')
avalanche_status['avalanche_level'] = avalanche_leve... | [
"def get_avalanche_status():\n avalanche = AvalancheWarningScraper(\"http://lawiny.topr.pl/\")\n avalanche_status = avalanche.navigate_and_extract_avalanche_data()\n return avalanche_status",
"def _read_status(self):",
"def status_atual():\n return wiki.conteudo_pagina(\"status\")",
"def test_get_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function for getting a current avalanche status in Tatra Mountain | def get_avalanche_status():
avalanche = AvalancheWarningScraper("http://lawiny.topr.pl/")
avalanche_status = avalanche.navigate_and_extract_avalanche_data()
return avalanche_status | [
"def _getCurrentComponentStatus(self):\n resOverall = self.sysAdminClient.getOverallStatus()\n if not resOverall['OK']:\n return resOverall\n currentStatus = {'Down': set(), 'Run': set(), 'All': set()}\n informationDict = resOverall['Value']\n for systemsDict in informationDict.values():\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return disk usage statistics about the given path. | def disk_usage(path):
st = os.statvfs(path)
free = (st.f_bavail * st.f_frsize)/ 1024
total = st.f_blocks * st.f_frsize
used = (st.f_blocks - st.f_bfree) * st.f_frsize
return DiskUsage(total, used, free) | [
"def disk_usage(path):\n st = os.statvfs(path)\n free = st.f_bavail * st.f_frsize\n total = st.f_blocks * st.f_frsize\n used = (st.f_blocks - st.f_bfree) * st.f_frsize\n return _ntuple_diskusage(total, used, free)",
"def disk_usage(path):\n st = os.statvfs(path)\n total = (st.f_blocks * st.f_fr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Explain everything available for the given metric. | def explain(self,
disp: bool=True) -> Union[None, str]:
# Find intersecting methods/attributes between MetricTextExplainer and provided metric.
inter = set(dir(self)).intersection(set(dir(self.metric)))
# Ignore private and dunder methods
metric_methods = [getattr(self,... | [
"def describe(ctx):",
"def explainerdashboard_cli(ctx):",
"def fetch_metrics(self):\n\n self.explain_all_indices()",
"def help_explain(self):\n print(EXPLAIN)",
"def _print_metrics(self, *args, **kwargs):\n pass",
"def help_analyze(self):\n print(ANALYZE)",
"def describe(self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Populates `object` with `attributes` from a mapping. | def set_attributes(object, attributes):
for name, attribute in attributes.items():
setattr(object, name, attribute) | [
"def add_attributes_from_dict(self, dict):\n for key in dict:\n val = dict[key]\n if hasattr(self, key):\n setattr(self, key, val)",
"def set_attr_from_dict(self, dictionary):\n for key in dictionary:\n self.__setattr__(key, dictionary.get(key))",
"d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Populates `object` with attributes from `kwargs` as defined by the default mapping `defaults`. If an item is contained in `kwargs` that is not defined | def set_attributes_from_kwargs(object, kwargs, defaults):
set_attributes(
object,
dict((key, kwargs.pop(key, value)) for key, value in defaults.items())
)
if kwargs:
raise TypeError(
"set_attributes_from_kwargs() got an unexpected keyword argument "
"%r" % kwa... | [
"def initDefaults(self, kwargs):\n \n for k,v in self.defaults.iteritems():\n if k in kwargs: # use assigned values\n setattr(self, k, kwargs[k])\n else: # use default values\n setattr(self, k, v)\n \n for k,v in kwargs.iteritems():\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns ``list(object)`` or a list containing object. | def force_list(object):
try:
return list(object)
except TypeError:
return [object] | [
"def as_list(obj) -> list:\n\n if isinstance(obj, list):\n return obj\n return [obj]",
"def as_list(obj):\n\n if isinstance(obj, list):\n return obj\n else:\n return [obj]",
"def make_list(obj):\n\n if isinstance(obj, list):\n return obj\n\n return [obj]",
"def _g... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Splits the given length `n` into a larger and a smaller part using the golden ratio to determine a "perfect" split. | def golden_split(n):
large = n / GOLDEN_RATIO
small = n - large
large = int(round(large))
small = int(round(small))
return large, small | [
"def split(a, n):\n n = min(n, len(a))\n k, m = divmod(len(a), n)\n return [a[i * k + min(i, m) : (i + 1) * k + min(i + 1, m)] for i in range(n)]",
"def splitInBlocks (l, n):\n k = len(l) / n\n r = len(l) % n\n\n i = 0\n blocks = []\n while i < len(l):\n if len(blocks)<r:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Try loading the command dictionary. | def load(self, command_dict_filepath):
try:
with open(command_dict_filepath) as fobj:
logger.debug(f"Loading command dictionary at {command_dict_filepath}")
self.command_dict = yaml.safe_load(fobj.read())
if "commands" in self.command_dict.keys():
... | [
"def _get_command_lookup(self, command_dict):",
"def load_commands(self):\n\t\tcommands = {}\n\t\ttry:\n\t\t\tfile_ = open(\"commands\", 'r')\n\t\t\tfor line in file_.readlines():\n\t\t\t\tif line == \"\":\n\t\t\t\t\tcontinue\n\t\t\t\tcommands[line.split(\"::\")[0]] = line.split(\"::\")[1].strip()\n\t\texcept OSE... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Raises a CommandDictSanityError exception if the command dictionary is not considered "sane". | def assert_sanity(self):
# Maybe in the future: Check whether commands can be found in path
# For now, let the OS handle this
# Check whether command dictionary has a correct structure. Namely,
# that:
#
# 1. Toplevel children may only be called "commands" or "paths".
... | [
"def check_command_dict(self, command):\n\n if not isinstance(command, dict):\n self.fail(\"Command must be a dictionary\")\n\n # NOTE(pboldin): Here we check for the values not for presence of the\n # keys due to template-driven configuration generation that can leave\n # key... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns whether the given string matches any of the commands' names regex patterns. | def match(self, string):
matched = False
cmd = None
if string in self.commands.keys():
matched = True
cmd = string
else:
for command in self.commands.keys():
if "regex" in self.commands[command].keys() \
and re.match(... | [
"def match(self, command_str: str) -> bool:\n return re.match(self._PATTERN, command_str) is not None",
"def somePatternMatches(patterns, s):\n for each in patterns:\n if re.match(each, s):\n return True\n return False",
"def _is_regex_match(s, pat):\n\n pat = pat.rstrip()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the help string of the given command. | def get_help(self,command):
if "help" in self.commands[command]:
return self.commands[command]["help"]
else:
return "No help defined for this command." | [
"def help_for_command(command):\n help_text = pydoc.text.document(command)\n # remove backspaces\n return re.subn('.\\\\x08', '', help_text)[0]",
"def do_help(self, command: str) -> t.Union[str, FormattedText]:\n if not command:\n return self.help_string\n\n # Let's do more black... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return boolean of the "markdown_convert" option. | def get_opt_markdown_convert(self, command):
if "markdown_convert" in self.command_dict["commands"][command].keys():
return self.command_dict["commands"][command]["markdown_convert"]
else:
return CommandDict.DEFAULT_OPT_MARKDOWN_CONVERT | [
"def is_markdown(self):\n return self._tag == 'markdown'",
"def is_markdown():\n return has_source(r'.*\\.md$')",
"def is_markdown_cell(cell):\n return cell[\"cell_type\"] == \"markdown\"",
"def convert_to_markdown(self, text: str) -> str:",
"def can_markdown(repo, fname):\n if markdown is N... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return boolean of the "formatted" option. | def get_opt_formatted(self, command):
if "formatted" in self.command_dict["commands"][command].keys():
return self.command_dict["commands"][command]["formatted"]
else:
return CommandDict.DEFAULT_OPT_FORMATTED | [
"def is_formatted(setting_value):\n return len(FORMAT_STR.findall(setting_value)) != 0",
"def post_formatter(self, value):\n if isinstance(value, bool):\n return value and 'true' or None\n return value",
"def formatBoolCommand(value):\n # command does not accept argument when they... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the string defined in the "split" option, or None. | def get_opt_split(self, command):
if "split" in self.command_dict["commands"][command].keys():
return self.command_dict["commands"][command]["split"]
else:
return CommandDict.DEFAULT_OPT_SPLIT | [
"def safe_split_get(string: str, sep: str, index: int, default=None) -> str:\n if not isinstance(string, str):\n return default\n return safe_get_list(string.split(sep), index, default)",
"def get_list(self, section, option_key, split_char=','):\n option = self.get(section, option_key)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
pick actions given numeric agent outputs (np arrays) | def sample_actions(self, agent_outputs):
logits, state_values = agent_outputs
policy = np.exp(logits) / np.sum(np.exp(logits), axis=-1, keepdims=True)
return np.array([np.random.choice(len(p), p=p) for p in policy]) | [
"def sample_actions(self, agent_outputs):\r\n logits, state_values = agent_outputs\r\n probs = F.softmax(logits, dim=1)\r\n return torch.multinomial(probs, 1)[:, 0].data.numpy()",
"def sample_actions(self, agent_outputs):\n logits, state_value = agent_outputs\n policy = np.exp(l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a dictionary of files and folders for a given reference and path. Implemented using ``git lstree``. If an invalid reference and/or path None is returned. | def ls_tree(reference, path=None, directory=None):
# Try to track the reference as a branch
track_branches(reference, directory=directory)
cmd = 'git ls-tree ' + reference
if path is not None and path != '':
cmd += ':' + path
retcode, out, err = execute_command(cmd, autofail=False, silent_er... | [
"def create_tree_hash_dict(cls, current_dir, file_path, dirs, files, ref_table):\n\n # we sort just to ensure there are no arrangement issues that could affect the hash outcome\n file_hashs = sorted([ref_table['%s/%s' % (file_path, file)]['hash'] for file in files])\n dir_hashs = sorted([ref_ta... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Interface to the git show command. If path is a file that exists, a string will be returned which is the contents of that file. If the path is a directory that exists, then a dictionary is returned where the keys are items in the folder and the value is either the string 'file' or 'directory'. If the path does not exis... | def show(reference, path, directory=None):
# Check to see if this is a directory
dirs = ls_tree(reference, path, directory)
if dirs is not None:
return dirs
# Otherwise a file or does not exist, check for the file
cmd = 'git show {0}:{1}'.format(reference, path)
# Check to see if it is a... | [
"def git_show(ref, filepath, **kw):\n if ref == DIRTY and filepath == 'qwerty.sh':\n return sh('cat', os.environ.get('QWERTY_SH', filepath), **kw)\n return sh('git', 'show', '{ref}:{filepath}'.format(**locals()), **kw)",
"def gitInfo(path):\n\n\tcmd = [u'git', u'log', u'--format=\"Revision <a href=\\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the SHA1 commit hash for the given reference. | def get_commit_hash(reference, directory=None):
# Track remote branch
if branch_exists(reference, local_only=False, directory=directory):
if not branch_exists(reference, local_only=True, directory=directory):
track_branches(reference, directory)
cmd = 'git show-branch --sha1-name ' + ref... | [
"def get_hash(repo, ref='HEAD'):\n return subprocess.check_output(['git', 'rev-parse', '--verify', ref],\n cwd=repo).rstrip()",
"def cmd_get_sha(ref):\n return ['git', 'rev-parse', ref]",
"def git_sha1_commit():\n return local('git rev-parse --short HEAD', capture=True... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns True is the working branch has untracked files, False otherwise. | def has_untracked_files(directory=None):
out = check_output('git status', shell=True, cwd=directory)
if '# Untracked files:' in out:
return True
return False | [
"def is_dirty(self):\n return super().is_dirty() or len(self.untracked_files) != 0",
"def is_git_dirty():\n dirty_status = local('git diff --quiet || echo \"*\"', capture=True)\n if dirty_status == '*':\n return True\n\n untracked_count = int(local('git status --porcelain 2>/dev/null| grep ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns True if the given tag exists, False otherwise | def tag_exists(tag, directory=None):
return tag in get_tags(directory) | [
"def tag_exists(self, tag_name):\n raise NotImplementedError",
"def has_tag(self, tag):\n return tag in self.tags",
"def has(self, tag_name: str) -> bool:\n return hasattr(self, tag_name)",
"def verify_tag(tag):\n return Registration.exists(tag)",
"def check_tag(self, session, tag):\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Deletes a given remote tag. | def delete_remote_tag(tag, remote='origin', directory=None):
execute_command('git push {0} :{1}'.format(remote, tag), shell=True,
cwd=directory) | [
"def tags_delete(self, tag, **kwds):\n return self.request('tags/delete', tag=tag, **kwds)",
"def tag_remove(self, remote_path, corpus_id, tag, storage_id=None):\n client, remote_path = self._get_storage(remote_path, storage_id=storage_id)\n return client.tag_remove(corpus_id, tag)",
"def d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a list of tags in the git repository. | def get_tags(directory=None):
out = check_output('git tag -l', shell=True, cwd=directory)
return [l.strip() for l in out.splitlines()] | [
"def list_tags(self) -> List[str]:\n self._validate()\n\n cmd = \"git tag --list --sort v:refname\"\n cmd_params = cmd_exec.CommandParameters(cwd=self.get_source_directory())\n tag_output = cmd_exec.run_command(cmd, cmd_params)\n\n tag_list = [tag.strip() for tag in tag_output.split('\\n') if tag]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks that you are in the root of the git repository, else exit. | def ensure_git_root():
root = get_root()
if root is None:
error("Not in a git repository.", exit=True)
if os.getcwd() != root:
error("Must call from the top folder of the git repository",
exit=True) | [
"def navigate_to_git_root() -> bool:\n dir_climb_count = 0\n continue_dir_traverse = True\n while continue_dir_traverse:\n if not Utils.contains_dir('.git'):\n print(f\"Current dir {os.getcwd()} is not a Git repository.\")\n # Change directory up one lev... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tracks all specified branches. | def track_branches(branches=None, directory=None):
if type(branches) == str:
branches = [branches]
debug("track_branches(" + str(branches) + ", " + str(directory) + ")")
if branches == []:
return
# Save the current branch
current_branch = get_current_branch(directory)
try:
... | [
"def test_all_git_branches(self):\n pass",
"def _get_branches(self):\n logging.info('--- Get Branches ---')\n self.local_branches = set(self.find_branches())\n self.remote_branches = set(self.find_branches(remote=True))\n # Tags are remote branches that start with \"tags/\".\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the most recent, by date, tag in the given local git repository. | def get_last_tag_by_date(directory=None):
cmd = "git for-each-ref --sort='*authordate' " \
"--format='%(refname:short)' refs/tags/upstream"
output = check_output(cmd, shell=True, cwd=directory, stderr=PIPE)
output = output.splitlines()
if len(output) == 0:
return ''
return output[-... | [
"def latest_github_tag():\n release_tags_github_url = \"https://api.github.com/repos/rackerlabs/openstack-guest-agents-unix/tags\"\n release_tags_json = urllib2.urlopen(release_tags_github_url)\n release_tags_data = json.load(release_tags_json)\n return str(release_tags_data[0]['name'])[1:]",
"def get... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Delete specified scan ID in the OpenVAS server. | def delete_scan(self, scan_id):
self.__manager.delete_task(scan_id) | [
"def delete_scans(headers):\n for scan_name in scan_name_list:\n if scan_name in scan_id_dict:\n scan_id = scan_id_dict[scan_name]\n scan_name = '\"'.join([scan_name])\n try:\n url = f\"https://cloud.tenable.com/scans/{scan_id}\"\n response = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the results associated to the scan ID. | def get_results(self, scan_id):
if not isinstance(scan_id, basestring):
raise TypeError("Expected string, got %r instead" % type(scan_id))
m_response = None
try:
m_response = self.__manager.make_xml_request('<get_results task_id="%s"/>' % scan_id, xml_result=True)
... | [
"def results(self, checkid):\r\n return results.Results(self, checkid)",
"def get_results(self, task_id):\n\n\t\tif not isinstance(task_id, str):\n\t\t\traise TypeError(\"Expected string, got %r instead\" % type(task_id))\n\n\t\tif self.__manager.is_task_running(task_id):\n\t\t\traise VulnscanTaskNotFinish... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Transform the XML results of OpenVAS into GoLismero structures. | def transform(xml_results):
PORT = re.compile("([\w\d\s]*)\(([\d]+)/([\w\W\d]+)\)")
m_return = []
m_return_append = m_return.append
# All the results
for l_results in xml_results.findall(".//results"):
for l_results in l_results.findall("result"):
... | [
"def _parseData(self, obj):\n osmObj = osmData.OSM()\n \n root=ET.fromstring(obj)\n \n for node in root.iter(\"node\"):\n nodeObj = osmData.Node(node.attrib[\"id\"].encode('utf-8'), \n float(node.attrib[\"lat\"]), \n float(node.attrib[\"lon... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Lowlevel interface to send OMP XML to the manager. `xmldata` may be either a utf8 encoded string or an etree Element. If `xml_result` is true, the result is returned as an etree Element, otherwise a utf8 encoded string is returned. | def make_xml_request(self, xmldata, xml_result=False):
if xml_result:
return self._xml_command(xmldata)
else:
return self._text_command(xmldata) | [
"def _send(self, data):\n\n # Make sure the data is a string.\n if etree.iselement(data):\n data = etree.dump(data)\n if isinstance(data, unicode):\n data = data.encode('utf-8')\n\n # Synchronize access to the socket.\n with self.__socket_lock:\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Delete a target in OpenVAS server. | def delete_target(self, target_id):
request = """<delete_target target_id="%s" />""" % (target_id)
self.make_xml_request(request, xml_result=True) | [
"def DeleteTarget(self, target_instance_id):",
"def delete_target(\n self,\n ) -> Callable[[cloud_deploy.DeleteTargetRequest], operations_pb2.Operation]:\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserial... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get IDs of tasks of the server. If name param is provided, only get the ID associated to this name. | def get_tasks_ids(self, name=None):
m_return = {}
for x in self.get_tasks().findall("task"):
m_return[x.find("name").text] = x.get("id")
if name:
return {name : m_return[name]}
else:
return m_return | [
"def getTaskIdsFromName(tasks_name):\n ids = []\n for name in tasks_name:\n task_obj = Tafv2Task.objects.get(script=name)\n ids.append(task_obj.id)\n\n return ids",
"def getTasks(server, appId):\n JSONdata = urllib2.urlopen(server+\"/api/task?app_id=\"+str(appId))\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get IDs of tasks of the server depending of their status. | def get_tasks_ids_by_status(self, status="Done"):
if status not in ("Done", "Paused", "Running", "Stopped"):
raise ValueError("Requested status are not allowed")
m_task_ids = {}
for x in self.get_tasks().findall("task"):
if x.find("status").text == status:
... | [
"def getTasks(server, appId):\n JSONdata = urllib2.urlopen(server+\"/api/task?app_id=\"+str(appId))\n data = json.load(JSONdata)\n numberTasks = len(data)\n taskId = []\n for item in range(numberTasks):\n taskId.append(data[item]['id'])\n return taskId",
"def get_task_srv_tasklist():\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Send OMP data to the manager and read the result. `data` may be either an unicode string, an utf8 encoded string or an etree Element. The result is as an etree Element. | def _send(self, data):
# Make sure the data is a string.
if etree.iselement(data):
data = etree.dump(data)
if isinstance(data, unicode):
data = data.encode('utf-8')
# Synchronize access to the socket.
with self.__socket_lock:
# Send the data... | [
"def write(self, data):\n self._processor.process(data)",
"def process(self, data):\n if self.__head:\n self.__head.send(Element(\n stream_id=self.id,\n data=data))",
"def send_micropython_data(self, data):\n self.send_user_data_relay(XBeeLoc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make a request and get the text of the response in raw format. | def _text_command(self, request):
response = self._send(request)
self._check_response(response)
return response.text | [
"def text(self) -> str:\n return self._raw_response.text",
"def get_raw_resp(url):\n try:\n headers = {'User-Agent': random.choice(USER_AGENTS)}\n request = requests.get(url, headers=headers, proxies=get_proxies())\n return request.text.encode('utf-8') if PY2 else request.text\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make a request and get the response as xml tree format. | def _xml_command(self, request):
response = self._send(request)
self._check_response(response)
return response | [
"def xml_response(self, data):\n response = make_response(data)\n response.headers[\"Content-Type\"] = \"application/xml\"\n\n return response",
"def _api_call(url: str) -> ET.Element:\n result = requests.get(url)\n if result.status_code != 200:\n raise RequestException(f\"API st... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return all the measurements from the given candidate | def all_measurements(candidate, godata):
measurements = OrderedDict()
measurements.update(concept_measurements(candidate, godata))
measurements.update(evidence_measurements(candidate))
measurements.update(bias_measurements(candidate))
return measurements | [
"def extract_from(\n self, context: TuneContext, candidates: List[MeasureCandidate]\n ) -> List[NDArray]:\n raise NotImplementedError",
"def generate_measure_candidates(self) -> Optional[List[\"MeasureCandidate\"]]:\n if self.search_strategy is None:\n raise ValueError(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Seed the numpy prng and return a data frame w/ predictable test inputs so that the tests will have consistent results across builds. | def random_df(request):
old_state = np.random.get_state()
def fin():
# tear down: reset the prng after the test to the pre-test state
np.random.set_state(old_state)
request.addfinalizer(fin)
np.random.seed(1)
return pd.DataFrame(
{'some_count': np.random.randint(1, 8, 20)},... | [
"def prng():\n return np.random.RandomState(773889874)",
"def _make_test_dataset(self):\n # recovers the deterministic 2D function using zeros\n test_x, test_y = np.zeros(self._train_size), np.zeros(self._train_size)\n test_x = np.float32(test_x)\n test_y = np.float32(test_y)\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create Tab and fill with content of default_script_content | def create_new_tab(default_script_content=""):
pass | [
"def _create_tab(tabtype, name, *args, **kwargs):\n\ttab = tabtype(name, *args, **kwargs)\n\n\ttab.window = builder.get_new_output_window()\n\ttab.window.show_all()\n\n\tmgmt.set_font(tab.window.textview, mgmt.get_font())\n\n\tconnect_tab_callbacks(tab, (\"new_message\",\"new_name\",\n\t\t\"server_connected\",\"new... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the discriminator object that is wrapped. Subclasses may not need to implement this method but can chose to if they are wrapping an object capable of discrimination. | def discriminator(self) -> Any:
return None | [
"def MyDiscriminator(self):\n if self.force_auto_sync:\n self.get('MyDiscriminator')\n return self._MyDiscriminator",
"def discriminator(self) -> str:\n return self.__class__.__name__",
"def get_real_child_model(self, data):\n discriminator_value = data[self.discriminator]... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a discriminator from the configuration. | def from_config(cls, config: Dict[str, Any]) -> "BaseDiscriminator": | [
"def build_discriminator(input_shape):\n input_data = Input(shape=input_shape)\n\n cnn = Conv2D(filters=32, kernel_size=(3, 3), strides=(2, 2), padding='same')(input_data)\n cnn = LeakyReLU(alpha=0.2)(cnn)\n cnn = Dropout(0.4)(cnn)\n\n cnn = Conv2D(filters=64, kernel_size=(3, 3), strides=(1, 1), padd... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets a hash code for the current DateTime instance. | def __hash__(self):
return hash(self.date) ^ hash(self.time_of_day) | [
"def _hashDateTime(self):\r\n i = 0\r\n for tp in self._listTimePoints:\r\n self._dateTimeHash[tp.getDateTime()] = i\r\n i += 1",
"def hash_ts():\n ts_hash = sha1()\n ts_hash.update(str(time.time()).encode(\"utf-8\"))\n ts_hash.hexdigest()\n return ts_hash.hexdigest... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Finds out if two 'DateTime' instances are not equal. | def __ne__(self, Other):
return self.date != Other.date or self.time_of_day != Other.time_of_day | [
"def date_time_equal(dt1, dt2): # real signature unknown; restored from __doc__\n return False",
"def equal(self, dt1, dt2): # real signature unknown; restored from __doc__\n return False",
"def is_same_datetime(dt1: datetime.datetime, dt2: datetime.datetime) -> bool:\n\n assert isinstance(dt1, dat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets this timestamp's time of day. | def time_of_day(self):
return self.time_of_day_value | [
"def day_ts(self):\n return self.raw() // (60 * 24)",
"def time(self) -> dt:\n return dt.fromtimestamp(self.timestamp)",
"def datetime(self):\n\n time = self.time()\n if time is None or time < 0 or time >= 24:\n time = 0\n\n try:\n d = datetime(self.year... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets this timestamp's time of day. This accessor is private. | def time_of_day(self, value):
self.time_of_day_value = value | [
"def set_time(self, time):\n pass",
"def set_time(self, time):\n self._time = time",
"def set_system_time(self, dt):\n\n timeshift.set_system_time( dt )",
"def setTime(self, timeObj, day=None):\n\n # override day if it's None\n if not day:\n day = getDayFromNum(ti... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
出金流程第四步 Operation Check (1) WD Alloc Review | def test_step4_1(self):
self.login_csadmin('opr_test', 'aa1111')
# 点击出金管理
time.sleep(5)
self.page.chujinguanli_span.click()
# 点击 WD Alloc Review
time.sleep(3)
self.page.wd_alloc_review_a.click()
# 在搜索框输入用户名
time.sleep(3)
self.page... | [
"def NonNGFC_CustomerInformation_DB_Receipt_EmptyFields(self): #5\n\n tractor_fuel_type = 'Tractor fuel' # this is tractor fuel, because is the objective of this testcase\n def_type_no = 'No' # this is \"no\", because is the objective of this testcase\n card_to_use_NonNGFC = 'Debit' \n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Params ====== input_count = number of inputs node_count = number of nodes in the layer activations = activations for each node | def __init__(self, input_count, node_count, activations=[]):
self.input_count = input_count
self.node_count = node_count
# If no activations are passed, generate them randomly.
if (len(activations) == 0):
rand_activations = [random.randint(0, self.node_count) for i in range... | [
"def multiple_node_activation(self, inputvalues, layer):\n\n print \"\\n *********Entering multiple nodes activation *********** \\n\"\n\n # checking the number of nodes in a layer\n print layer\n\n print inputvalues\n\n for nodes in layer:\n if type(nodes) is not list:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Top level function to create Share or Batch instance depending on number of symbols given | def IexFinance(symbol, **kwargs):
if type(symbol) is str:
if not symbol:
raise ValueError("Please input a symbol or list of symbols")
else:
inst = Share(symbol, **kwargs)
elif type(symbol) is list:
if not symbol:
raise ValueError("Please input ... | [
"def __init__(self, symbols, short_window, long_window, command_execute):\n\n\t\t# Create a new Macs object for every stock\n\t\tself.data = {s: Macs(short_window, long_window) for s in symbols}\n\t\tself.command_execute = command_execute",
"def test_multiple_instanciation(num_resources=3):\n cfg = gc3libs.con... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Universal selector method to obtain custom endpoints from the data set. Will throw a IEXEndpointError if an invalid endpoint is specified and an IEXQueryError if the endpoint cannot be retrieved. | def get_select_endpoints(self, endpointList=[]):
if type(endpointList) is str:
endpointList = [endpointList]
result = {}
if not endpointList:
raise ValueError("Please provide a valid list of endpoints")
for endpoint in endpointList:
try:
... | [
"def get_endpoints(self, **kwargs):\n return self._database.lookup('endpoint', kwargs)",
"def get_endpoints(self, hostname=None, orchestrator_id=None,\n workload_id=None, endpoint_id=None):\n # First build the query string as specific as possible. Note, we want\n # the qu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Universal selector method to obtain custom datapoints from an individual endpoint. If an invalid endpoint is specified, throws an IEXEndpointError. If an invalid datapoint is specified, throws an IEXDatapointError. If there are issues with the query, throws an IEXQueryError. | def get_select_datapoints(self, endpoint, attrList= []):
if type(attrList) is str:
attrList = [attrList]
result = {}
if not attrList:
raise ValueError("Please give a valid attribute list")
try:
ep = self.data_set[endpoint]
except:
... | [
"def get_select_datapoints(self, endpoint, attrList= []):\r\n if type(attrList) is str:\r\n attrList = [attrList]\r\n result = {}\r\n if not attrList:\r\n raise ValueError(\"Please give a valid attribute list\")\r\n for symbol in self.symbolList:\r\n try:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Universal selector method to obtain custom datapoints from an individual endpoint. If an invalid endpoint is specified, throws an IEXEndpointError. If an invalid datapoint is specified, throws an IEXDatapointError. If there are issues with the query, throws an IEXQueryError. | def get_select_datapoints(self, endpoint, attrList= []):
if type(attrList) is str:
attrList = [attrList]
result = {}
if not attrList:
raise ValueError("Please give a valid attribute list")
for symbol in self.symbolList:
try:
ep... | [
"def get_select_datapoints(self, endpoint, attrList= []):\r\n if type(attrList) is str:\r\n attrList = [attrList]\r\n result = {}\r\n if not attrList:\r\n raise ValueError(\"Please give a valid attribute list\")\r\n try:\r\n ep = self.data_set[endpoint]\r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parses a comment body for amazon book urls, return all comentions | def get_comentions(body):
isbns = set(isbn for _, isbn in ISBN_REGEX.findall(body))
for isbn1, isbn2 in permutations(isbns, 2):
yield isbn1, isbn2 | [
"def get_book(url):\n \n text = requests.get(url).text\n start_comment = re.search('\\*\\*\\* START OF THIS PROJECT GUTENBERG EBOOK.*\\*\\*\\*',text)\n end_comment = re.search('\\*\\*\\* END OF THIS PROJECT GUTENBERG EBOOK.*\\*\\*\\*',text)\n text = text[start_comment.end():end_comment.start()]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
for each comment in the csv, count the number of comentions | def count_comentions_csv(csv_reader):
header = next(csv_reader)
index_of = {col: index for index, col in enumerate(header)}
comention_counter = Counter()
for line in csv_reader:
body = line[index_of['body']]
for isbn1, isbn2 in get_comentions(body):
comention_counter[(isbn1, ... | [
"def _count_comment_rows(vcf_path):\n vcf_lines_generator = lines_from_vcf(vcf_path)\n\n comment_lines_count = 0\n for line in vcf_lines_generator:\n if line.startswith('#'):\n comment_lines_count += 1\n else:\n vcf_lines_generator.close() # Don't leave the file handle ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reads in the all the comment csvs in `csv_directory` and builds a csv containing all the comention frequencies | def main():
csv_paths = sorted(glob(os.path.join('amazon', '*.csv')), key=lambda p: p.split('/'))
with open('comentions.csv', 'w+') as wf:
csv_writer = csv.writer(wf)
# counter for comentions across ALL the csvs
all_comentions_counter = Counter()
for csv_path in csv_paths:
... | [
"def count_comentions_csv(csv_reader):\n header = next(csv_reader)\n index_of = {col: index for index, col in enumerate(header)}\n comention_counter = Counter()\n for line in csv_reader:\n body = line[index_of['body']]\n for isbn1, isbn2 in get_comentions(body):\n comention_coun... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function accepts the column number for the features (X) and the target (y). It chunks the data up with a rolling window of Xt window to predict Xt. It returns two numpy arrays of X and y. | def get_window_data(symbol_signals_df, window_size, feature_col_number, target_col_number):
X = []
y = []
for i in range(len(symbol_signals_df) - window_size):
features = symbol_signals_df.iloc[i : (i + window_size), feature_col_number]
#print(features)
target =... | [
"def window_data(datax, datay, window_length, hop_size, sample_rate, test_size):\n sample_window_length = int(np.floor(window_length * sample_rate))\n sample_hop_size = int(np.floor(hop_size * sample_rate))\n\n X_train = np.empty((0, sample_window_length))\n X_test = np.empty((0, sample_window_length))\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Display individual listing details Form to edit details if needed | def view_and_edit_listing(request, listing_id):
categories = Category.objects.all()
listing = get_object_or_404(Listing, pk=listing_id)
if request.method == 'POST':
editform = AddListingForm(
request.POST,
request.FILES,
instance=listing)
if editform.is_v... | [
"def new_listing():\n\n return render_template(\"add_listing.html\")",
"def show_edit_form(self, obj_pk=None):\n obj = self.model.objects.get(pk=obj_pk)\n # if there is no edit permission then does not show the form\n if not self.has_view_permissions(obj): return\n\n\n # create the ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Allow user to delete his own listing from the database | def delete_listing(request, listing_id):
listing = get_object_or_404(Listing, pk=listing_id)
listing.delete()
messages.success(
request,
'Your listing has been removed from the database.')
return redirect(reverse('addlisting')) | [
"def delete(request, shoppinglist_id):\n Shoppinglist.objects.filter(pk=shoppinglist_id,\n pantry__owner=request.user).delete()\n return redirect('blackem.users.views.home')",
"def delete_meal():",
"def loan_remove(request, id):\n loan = User.objects.get(id=id)\n loan.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Shows on the stdout the progress bar for the given progress. | def bar(self, progress):
if not hasattr(self, "_limit") or not self._limit:
self._limit = self.terminal_size()
graph_progress = int(progress * self._limit)
self.stdout.write("\r", ending="")
progress_format = "[%-{}s] %d%%".format(self._limit)
self.stdout.write(
... | [
"def progress_bar(progress):\n import sys\n\n bar_length = 20\n if isinstance(progress, int):\n progress = float(progress)\n if not isinstance(progress, float):\n progress = 0\n if progress < 0:\n progress = 0\n if progress >= 1:\n progress = 1\n block = int(round(ba... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a tkinter widget, this will create a FigureCanvas as a root of that widget and pack it | def create_figure(root_window):
frame = ttk.Frame(root_window)
fig = Figure()
canvas = FigureCanvas(fig, frame)
toolbar = NavigationToolbar2TkAgg(canvas, frame)
frame.pack(expand=tk.YES, fill=tk.BOTH)
canvas.get_tk_widget().pack(expand=tk.YES, fill=tk.BOTH)
toolbar.update()
return fig | [
"def draw_canvas(self):\n\n self.canvas = Canvas(self)\n self.scrollbar = ttk.Scrollbar(self, orient= VERTICAL,\n command=self.canvas.yview) \n self.canvas.configure(yscrollcommand=self.scrollbar.set)\n \n # make sure to add scrollbar before adding the canvas\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Yields a generator of features for aligned sequences. | def get_alignment(sequenceA, sequenceB, featuresA, featuresB):
alignment = max(pairwise2.align.globalxx(sequenceA, sequenceB), key=operator.itemgetter(1))
alignedA, alignedB, _, __, ___ = alignment
featuresA = iter(featuresA)
featuresB = iter(featuresB)
for x,y in zip(alignedA, alignedB):
... | [
"def transform(self, sequences: Iterable[List[str]]) -> Iterable[torch.Tensor]:\n\n for seq in sequences:\n seq = self.preprocess(seq)\n if self.use_vocab:\n seq = [self.vocab[token] for token in seq]\n if self.bos:\n seq = [self.bos_index] + seq... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Joins feature_dict with the conservation features based on the sequence alignment. Features loaded are score, color, score confidence interval, color confidence interval and residue variety. | def join_conservation_data(sequence, features_dict, conservation_file):
with open(conservation_file, 'r') as ifile:
lines = [x.rstrip('\n') for x in ifile.readlines()]
lines = [x.split('\t') for x in lines]
lines = [x for x in lines if len(x) == 14]
features = features_dict.keys()
c... | [
"def add_features(record, feature_dict):\n \n # iterating through each annotation from the list\n for k,v in feature_dict.items():\n # first check if the sequence is present in the record\n name = k\n sequence = v\n\n if sequence_presence_check(record, sequence) == True:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create two Species and check that Ecosystem is correctly updated. | def test_speciesCreation():
sys = LVsystem.Ecosystem()
sys.addSpecies('rabbit')
sys.addSpecies('fox')
sys.setInteraction('rabbit', 'fox', -1)
sys.setInteraction('fox', 'rabbit', 1)
sys.setInitialCond('rabbit', 10)
sys.setInitialCond('fox', 5)
sys.setGrowthRate('rabbit', 1)
sys.... | [
"def testMakeNewSpecies(self):\n\n # adding 3 unique species:\n cerm = CoreEdgeReactionModel()\n\n spcs = [Species().fromSMILES('[OH]'), \n Species().fromSMILES('CC'),\n Species().fromSMILES('[CH3]')]\n\n for spc in spcs:\n cerm.makeNewSpecies(spc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create and destroy two species and check that at every step the Ecosystem is correctly updated. | def test_speciesDestruction():
sys = LVsystem.Ecosystem()
sys.addSpecies('rabbit')
sys.addSpecies('fox')
sys.addSpecies('wolf')
sys.removeSpecies('fox')
assert len(sys.species_list) == 2
assert not ('fox' in sys.species_list)
for key in sys.intMatrix:
assert not ('fox' ... | [
"def test_speciesCreation():\n \n sys = LVsystem.Ecosystem()\n sys.addSpecies('rabbit')\n sys.addSpecies('fox')\n sys.setInteraction('rabbit', 'fox', -1)\n sys.setInteraction('fox', 'rabbit', 1)\n sys.setInitialCond('rabbit', 10)\n sys.setInitialCond('fox', 5)\n sys.setGrowthRate('rabbit... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests if the method createData of the class Ecosystem returns correctly the data stored. | def test_createData():
sys = LVsystem.Ecosystem()
sys.addSpecies('rabbit')
sys.setInteraction('rabbit', 'hen', 0)
sys.setInteraction('rabbit', 'fox', -1)
sys.setInitialCond('rabbit', 30)
sys.setGrowthRate('rabbit', 0.09)
sys.setCarrCap('rabbit', 10000)
sys.setChangeRate('rabbit', 400)
... | [
"def test_factory_methods(self):\n\n DatumTest.create_data()",
"def test_create_device_data(self):\n pass",
"def test_creation(self):\n self.assertEqual(self.book_data, self.reader._books)\n self.assertEqual(1, self.reader._location)\n self.assertEqual([0, 0, 0, 0, 0, 0], self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Annotation used to log the HTTP headers of a request. Used for debugging. Headers will be logged as info. | def log_headers(f):
def wrapper(fself, *arguments, **keywords):
import logging
for header_key, header_value in fself.request.headers.items():
logging.info(header_key + ": " + header_value)
# Call the underlying function with the parameter added
return f(fself, *argument... | [
"def log_request_info():\n app.logger.debug('Headers: %s', request.headers)\n app.logger.debug('Body: %s', request.get_data())",
"def show_request_headers(response):\n return response.request.headers",
"def test_log_req_attrs_true(self, request, caplog):\n caplog.set_leve... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decorator that allows an endpoint to use pytracts messages for the request and response. | def endpoint(_wrapped_function=None, lenient=False, **kwargs):
if len(kwargs) > 1:
raise IndexError("Cannot have more than one mapping for request body")
if len(kwargs) == 1:
body_param_name = list(kwargs.keys())[0]
body_param_type = list(kwargs.values())[0]
if not isinstance(... | [
"def endpoint(request):\n try:\n if request.method == \"GET\":\n return message_GET(request)\n elif request.method == \"POST\":\n return message_POST(request)\n elif request.method == \"PUT\":\n return message_PUT(request)\n else:\n return H... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
given the argument PATTERN from the argument parser, this function decides if it's a single pattern or a file. If it's a file, each line is a search pattern. | def extract_pattern(self, patterns):
# if we have more patterns or
# a single one which is not a file:
if len(patterns) > 1 or (
len(patterns) == 1 and not os.path.isfile(patterns[0])):
return patterns
else:
pattern = patterns[0]
pat_list ... | [
"def matching(pattern: str, kind: Optional[str] = None,\n dirpath: Optional[Union[str, Path]] = None, **options\n) -> List[Tuple[Path, Path]]:\n\n if dirpath or kind == 'askdirectory':\n\n # dialog for dir if none given\n dirpath = standard(kind, **options) if not dirpath else Path(dirp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
remove the empty string from the patterns if no patterns are left, stops the programme and warns the user. No need to validate the TEXT parameter as an empty string cannot contain any other pattern | def validate_data(self):
for pattern in self.patterns:
if pattern == "":
self.patterns.remove("")
if not self.patterns:
print("WARNING! Missing pattern or empty string!")
sys.exit() | [
"def cleaning_filter(text):\n try:# A REFAIRE\n if \"This article has been retracted\" in text:\n text =\"retracted\"\n return False\n if \"Cette article\" in text:\n text =\"retracted\"\n return False\n if len(text) < 20:\n return False... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This functions prints (or saves in JSON) the output from the matcher based on some parameters (es. self.recursive, type of input). It prints additional informations such as the TEXT string or the name of the file and the calls the function self.results to format the rest of the output. | def output(self, argument):
if not self.json:
if not self.first_print:
print()
self.first_print = False
if isinstance(argument, tuple):
filepath, filename = argument
if not self.json:
# if -r, print the path AND the name of t... | [
"def getResults(self):\n\n\t\t# Basically: self.output = self.formatResultsAs{{self.outputFormat}}\n\t\tif self.outputFormat == 'text':\n\t\t\tself.output = self.formatResultsAsText()\n\t\telif self.outputFormat == 'csv':\n\t\t\tself.output = self.formatResultsAsCsv()\n\n\t\tif self.outputLocation == 'stdout':\n\t\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
the 'main' function of the class, given the type of input it calls the appropriate function to process it | def run(self):
# FILE INPUT
if self.text_type == "file":
self.process_files()
# STRING INPUT
else:
self.process_strings()
if self.json:
self.save_json()
if self.errors:
print("\nThe following file(s) could not be opened:"... | [
"def main():\n\targuments_sent = sys.argv\n\tif len(arguments_sent) > 1:\n\t\tfile_path = arguments_sent[1]\n\t\tprocess_based_on_type(file_path)",
"def processInputs(self):",
"def process_inputs(self, inputs):",
"def process(self, input, output):\n pass",
"def main():\n parser = argparse.Argument... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verify that volumes pagination works right and back. | def test_volumes_pagination(self, volumes_steps, create_volumes,
update_settings):
volume_names = list(generate_ids('volume', count=3))
create_volumes(volume_names)
update_settings(items_per_page=1)
tab_volumes = volumes_steps.tab_volumes()
tab_v... | [
"def test_pagination(self):\n artist = Artist.objects.create(name='Artist', normname='artist')\n album = Album.objects.create(artist=artist, name='Album', normname='album')\n songs = {}\n for num in range(120):\n songs[num] = Song.objects.create(filename='file%03d.mp3' % (num+... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verify that user can view volume info. | def test_view_volume(self, volume, volumes_steps):
volumes_steps.view_volume(volume.name) | [
"def verify_volume_displayed(self, volume_name):\n self._webnative_volumes_users.verify_volume_displayed(volume_name)",
"def verify_user_volume_displayed(self, username, volume_name):\n self._webnative_volumes_users.verify_user_volume_displayed(username, volume_name)",
"def is_volume_displayed(sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verify that user can change volume type. | def test_change_volume_type(self, create_volume, volumes_steps):
volume_name = generate_ids('volume').next()
create_volume(volume_name, volume_type=None)
volumes_steps.change_volume_type(volume_name) | [
"def test_retype_setup_fail_volume_is_available(self, mock_notify):\n elevated = context.get_admin_context()\n project_id = self.context.project_id\n\n db.volume_type_create(elevated, {'name': 'old', 'extra_specs': {}})\n old_vol_type = db.volume_type_get_by_name(elevated, 'old')\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verify that user can upload volume to image. | def test_upload_volume_to_image(self, volume, images_steps, volumes_steps):
image_name = next(generate_ids('image', length=20))
volumes_steps.upload_volume_to_image(volume.name, image_name)
images_steps.page_images().table_images.row(
name=image_name).wait_for_presence(30)
i... | [
"def is_upload(self) -> bool:",
"def _verify_volume_creation(self, volume):\n # validate disk type\n self._get_disk_type(volume)\n\n # validate storage profile\n profile_name = self._get_storage_profile(volume)\n if profile_name:\n self.ds_sel.get_profile_id(profile_n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verify that admin can launch volume as instance. | def test_launch_volume_as_instance(self, volume, instances_steps,
volumes_steps):
instance_name = next(generate_ids('instance'))
volumes_steps.launch_volume_as_instance(
volume.name, instance_name, network_name=INTERNAL_NETWORK_NAME)
instances_... | [
"def test_launch_instance_with_creating_blank_volume(self):\n device_name = '/dev/vdb'\n instance_type = CONF.aws.instance_type\n (resp, data,) = self.ec2_client.RunInstances(ImageId=CONF.aws.image_id, InstanceTypeId=instance_type, \\\n\t\t\t\t\tInstanceCount=1, SubnetId=self.subnet_id, \n\t\t\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verify that admin can change volume status. | def test_change_volume_status(self, volume, volumes_steps):
volumes_steps.change_volume_status(volume.name, 'Error')
volumes_steps.change_volume_status(volume.name, 'Available') | [
"def CheckAdmin():\n if ( os.geteuid() != 0 ):\n sys.stderr.write(\"Root privileges are required for low-level disk \")\n sys.stderr.write(\"access.\\nPlease restart this script as root \")\n sys.stderr.write(\"(sudo) to continue.\\n\")\n sys.exit(1)",
"def test_mute_possibility(sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verify that admin can manage volume attachments. | def test_manage_volume_attachments(self, volume, instance, volumes_steps):
volumes_steps.attach_instance(volume.name, instance.name)
volumes_steps.detach_instance(volume.name, instance.name) | [
"def test_attachment_deletion_allowed_volume_no_attachments(self):\n volume = tests_utils.create_volume(self.context)\n self.volume_api.attachment_deletion_allowed(self.context, None, volume)",
"def attachment_check():\n async def predicate(ctx):\n return ctx.guild is not None and ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verify that volume can be transfered between users. | def test_transfer_volume(self, volume, auth_steps, volumes_steps):
transfer_name = next(generate_ids('transfer'))
transfer_id, transfer_key = volumes_steps.create_transfer(
volume.name, transfer_name)
auth_steps.logout()
auth_steps.login(USER_NAME, USER_PASSWD)
volume... | [
"def is_volume_available(tenant_id, auth_token, volume_id):\n content = volume_details(tenant_id, auth_token, volume_id)\n while content[\"volume\"][\"status\"] == \"creating\" or \\\n content[\"volume\"][\"status\"] == \"downloading\" or \\\n content[\"volume\"][\"status\"] == \"restoring-backu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Assigns networks to specified interface. | def assign_networks(cls, instance, networks):
instance.assigned_networks_list = networks
db().flush() | [
"def network_interfaces(self, network_interfaces):\n\n self._network_interfaces = network_interfaces",
"def attach_interface_to_namespace(node, namespace, interface):\n cmd = f\"ip link set {interface} netns {namespace}\"\n\n ret_code, _, stderr = exec_cmd(node, cmd, timeout=5, sudo=True)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks availability of DPDK for given interface. DPDK availability of the interface depends on presence of DPDK drivers and libraries for particular NIC. It may vary for different OpenStack releases. So, dpdk_drivers vary for different releases and it can be not empty only for node that is assigned to cluster currently... | def dpdk_available(cls, instance, dpdk_drivers):
return (cls.get_dpdk_driver(instance, dpdk_drivers) is not None and
instance.node.cluster.network_config.segmentation_type ==
consts.NEUTRON_SEGMENT_TYPES.vlan) | [
"def setup_dpdk(self):\n pci_drv_map = dict()\n if self.eth_if:\n eth_if = self.eth_if\n else:\n print(\"Mandatory Argument Eth If is missing\\n\")\n\n if self.bind:\n bind = self.bind\n\n #all_drv_path = '/sys/bus/pci/drivers/'\n\n if self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update information about offloading modes for the interface. | def update_offloading_modes(cls, instance, new_modes, keep_states=False):
def set_old_states(modes):
"""Set old state for offloading modes
:param modes: List of offloading modes
"""
for mode in modes:
if mode['name'] in old_modes_states:
... | [
"def update_mode(self):\n pass",
"def update_modes(self, initial=False):\n if self._v1_modes:\n # Work around slow arlo connections.\n if initial and self._arlo.cfg.synchronous_mode:\n time.sleep(5)\n resp = self._arlo.be.notify(\n base=... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Query networks to interfaces mapping on all nodes in cluster. Returns combined results for NICs and bonds for every node. Names are returned for node and interface (NIC or bond), IDs are returned for networks. Results are sorted by node name then interface name. | def get_networks_to_interfaces_mapping_on_all_nodes(cls, cluster):
nodes_nics_networks = db().query(
models.Node.hostname,
models.NodeNICInterface.name,
models.NetworkGroup.id,
).join(
models.Node.nic_interfaces,
models.NodeNICInterface.assigne... | [
"def _compile_networks(self):\n\n _header_ = self._header_ + '_compile_networks(): '\n\n if self.verbose:\n print(_header_ + 'Compiling all networks ...')\n\n networks = []\n\n all_nidx = set(self.nidx2lidx.keys())\n\n while all_nidx:\n\n nidx0 = [all_nidx.po... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get interface with specified network assigned to it. This method first checks for a NodeNICInterface with the specified network assigned. If that fails it will look for a NodeBondInterface with that network assigned. | def get_interface_by_net_name(cls, node_id, netname):
iface = db().query(models.NodeNICInterface).join(
(models.NetworkGroup,
models.NodeNICInterface.assigned_networks_list)
).filter(
models.NetworkGroup.name == netname
).filter(
models.NodeNICInt... | [
"def getlinknetif(self, network):\n for interface in self.netifs():\n if hasattr(interface, \"othernet\") and interface.othernet == network:\n return interface\n\n return None",
"def getInterface(self, host, network):\n\t\tinterface = None\n\t\tfor interface, in self.db.sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find all interfaces with MAC address not in mac_addresses. | def get_interfaces_not_in_mac_list(cls, node_id, mac_addresses):
return db().query(models.NodeNICInterface).filter(
models.NodeNICInterface.node_id == node_id
).filter(
not_(models.NodeNICInterface.mac.in_(mac_addresses))
) | [
"def possible_mac_addresses(interface):\n\n mac_addrs = []\n\n # In case of VLANs, just grab the parent interface\n if interface.interface_type == 'vlan':\n interface = interface.parent\n\n # Bonding/bridge: append the MACs of the physical interfaces\n # TODO: drop the public/bootable check on... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes a hypothesis (string) and a list of rules (list of IF objects), returning an AND/OR tree representing the backchain of possible statements we may need to test to determine if this hypothesis is reachable or not. This method should return an AND/OR tree, that is, an AND or OR object, whose constituents are the sub... | def backchain_to_goal_tree(rules, hypothesis):
goal_tree = []
for rule in rules:
var = match(rule.consequent(),hypothesis)
if var:
sub_hypothesis = populate(rule.antecedent(), var)
if isinstance(rule.antecedent(), OR):
sub_tree = [backchain_to_goal_tree(r... | [
"def parse(rule: str):\n\n rule = rule.strip()\n if len(rule):\n\n # Handle cases where there is a nested rule first\n if rule.startswith('('):\n split_rule = re.split(after_paren, rule, maxsplit=1)\n split_rule = list(map(lambda x: x.strip(), split_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds calibration point fields to the import window. | def add_calibration_entry(self):
self.calibration_points=True
self.begin_ind_calibration = tkinter.Label(self.rightmostframe, text='Calibration Point 1 Row', bg='white')
self.begin_ind_calibration.pack(pady=4)
self.begin_ind_calibration_entry = tkinter.Entry(self.rightmostframe)
... | [
"def add_points(self, points):\n feat = QgsFeature()\n self.output_layer.startEditing()\n prov = self.output_layer.dataProvider()\n point_nr = 0\n for point in points:\n point_nr += 1\n point_name = '{}_{}'.format(self.dlg.lineEditFeatureName.text().strip(), ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds filter field to import window. Allows user to specify another column in the data to filter the data by. | def add_filter_entry(self, filter_column=None, filter_entry=None):
new_filter_label = tkinter.Label(self.rightmostframe, text='Custom Column Filter:')
new_filter_label.pack(pady=4)
my_str = tkinter.StringVar()
new_filter_columns = tkinter.OptionMenu(self.rightmostframe, my_str, *self.c... | [
"def addFilter(self):\n\n df = self.table.model.df\n fb = FilterBar(self, self.fbar, list(df.columns))\n fb.pack(side=TOP, fill=BOTH, expand=1, padx=2, pady=2)\n self.filters.append(fb)\n return",
"def import_data_filter_options(data_url, column_filter, authorization_token):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Opens up save window to save the current import | def save_import(self, out_dict):
self.attributes('-topmost', 'false')
options = self.create_options(saving=True)
options['spreadsheet_path'] = self.spreadsheet_path
self.wait_window(SavePage(self, options))
self.attributes('-topmost', 'true') | [
"def save_dialog(self, *args):\n if not self.sprite.image:\n return\n content = SaveDialog(save=self.save_check, cancel=self.dismiss_popup,\n file_types=['*.bounds'])\n content.ids.filechooser.path = self.last_dir\n content.text_input.text = (self.s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handles saving of the import with the specified name Includes error checking for invalid characters, empty name, and file already existing | def save(self, file_name):
invalid_characters = ['#','%','&','{','}','\\','<','>','*','?','/','^','$','!','\'','\"',':','@','+',"`",'|','=','~']
if len(file_name) == 0:
message = "The import name cannot be empty"
SaveError(self, message)
elif any(invalid_char in file_name... | [
"def saveFile (self, fieldname, fullNamePath) :\n self.riseError ()",
"def test_custom_valid_name_callable_upload_to(self):\n obj = Storage()\n obj.custom_valid_name.save(\"random_file\", ContentFile(\"random content\"))\n # CustomValidNameStorage.get_valid_name() appends '_valid' to t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |