query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
None < apbsWriteSolvationEnergy(fp)\n Writes APBS Solvation Energy Parameters into fp\n | def apbsWriteSolvationEnergy(self, fp):
fp.write('READ\n')
fp.write('\tmol pqr %s\n'%(self.molecule1Path))
fp.write('END\n\n')
fp.write('ELEC\n')
fp.write('\tmg-auto\n')
fp.write('\tmol 1\n')
file_name, ext = os.path.splitext(self.molecule1Path)
mol_name =... | [
"def apbsWriteElectrostaticPotential(self, fp):\n fp.write('READ\\n')\n fp.write('\\tmol pqr %s\\n'%(self.molecule1Path))\n fp.write('END\\n\\n')\n fp.write('ELEC\\n')\n fp.write('\\tmg-auto\\n')\n fp.write('\\tmol 1\\n')\n file_name, ext = os.path.splitext(self.mole... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
None < apbsWriteBindingEnergy(fp)\n Writes APBS Binding Energy Parameters into fp\n | def apbsWriteBindingEnergy(self, fp):
fp.write('READ\n')
fp.write('\tmol pqr %s\n'%(self.molecule1Path))
fp.write('\tmol pqr %s\n'%(self.molecule2Path))
fp.write('\tmol pqr %s\n'%(self.complexPath))
fp.write('END\n\n')
fp.write('ELEC\n')
fp.write('\tmg-auto\n')
... | [
"def SaveAPBSInput(self, filename):\n fp = open(filename, 'wb+')\n if(self.calculationType=='Solvation energy'):\n self.apbsWriteSolvationEnergy(fp)\n elif(self.calculationType=='Binding energy'):\n self.apbsWriteBindingEnergy(fp)\n else: self.apbsWriteElectrostatic... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
None < apbsWriteElectrostaticPotential(fp)\n Writes APBS Electrostatic Potential Parameters into fp\n | def apbsWriteElectrostaticPotential(self, fp):
fp.write('READ\n')
fp.write('\tmol pqr %s\n'%(self.molecule1Path))
fp.write('END\n\n')
fp.write('ELEC\n')
fp.write('\tmg-auto\n')
fp.write('\tmol 1\n')
file_name, ext = os.path.splitext(self.molecule1Path)
mol... | [
"def apbsWritePhysicsParams(self, fp):\n #fp.write('\\tgamma %.3f\\n'%(self.GAMMA)) # NOTE: CONSTANT\n fp.write('\\ttemp %.3f\\n'%(self.systemTemperature))\n fp.write('\\tsrad %.3f\\n'%(self.solventRadius))\n fp.write('\\tsdie %.3f\\n'%(self.solventDielectric))\n fp.write('\\tpdie... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
None < apbsWriteElectrostaticPotential(filename)\n Saves APBS Input Parameters in a file named filename \n | def SaveAPBSInput(self, filename):
fp = open(filename, 'wb+')
if(self.calculationType=='Solvation energy'):
self.apbsWriteSolvationEnergy(fp)
elif(self.calculationType=='Binding energy'):
self.apbsWriteBindingEnergy(fp)
else: self.apbsWriteElectrostaticPotential(f... | [
"def apbsWriteElectrostaticPotential(self, fp):\n fp.write('READ\\n')\n fp.write('\\tmol pqr %s\\n'%(self.molecule1Path))\n fp.write('END\\n\\n')\n fp.write('ELEC\\n')\n fp.write('\\tmg-auto\\n')\n fp.write('\\tmol 1\\n')\n file_name, ext = os.path.splitext(self.mole... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Delete a step by name. | def delete(self, name):
if name in self.steps:
self.steps.pop(name)
else:
self.log('{} not in steps dict'.format(name), level='warn')
if name in self.order:
ind = self.order.index(name)
self.order = self.order[:ind] + self.order[ind + 1:]
e... | [
"def delete(self, name):\n LOG.info(\"Delete workflow [name=%s]\" % name)\n\n db_api.delete_workflow_definition(name)",
"def deleteName(self, name):\n if not isinstance(name, str):\n return False\n if len(name) > 15:\n return False\n\n conn = Connection(sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Run a specific step by name. If 'current' run the most recent 'Not run' or 'failed' step. | def run(self, step='current'):
self._get_current()
if step == 'current':
cur = None
if not self.order:
self.log('No steps added yet, not running', level='warn')
return
for step in self:
if not step.done:
... | [
"def run_step(self, step_config):\n assert isinstance(step_config, self.StepConfig)\n return self._engine.run_step(step_config)",
"def _run(self, name, cmd, step_test_data=None):\n return self.m.step(\n name, [self._client] + list(cmd),\n step_test_data=step_test_data,\n infra_step=T... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Run all steps in order if not already complete. | def run_all(self, skip_pre_donecheck=False, force=False):
self._get_current()
self.save()
for step in self:
# Get done state
done = step.done
if not skip_pre_donecheck and not force:
if step.donetest:
done = step.run_done_te... | [
"def step_all(self):\n for agent in self.agents:\n agent.step()",
"def run(self):\n while not self.finished():\n self.runStep()",
"def run(self) -> None:\n for step, val in self.directions:\n step(val)",
"def step(self):\n \tif not self.is_done():\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Run job_list (tuple of step names) in parallel. Runs all jobs in job_list (a tuple or list) in parallel. It is HIGHLY recommended that the dependency lists for all jobs are populated before running this. Jobs will not run until their dependencies are satisfied. It is possible to have jobs autoresubmit on failure, up to... | def run_parallel(self, job_list, auto_resubmit=False, tries=5, delay=60,
raise_on_error=False):
pass # TODO | [
"def run_in_parallel(task_list, maximum_jobs):\n if maximum_jobs == 0:\n executor = concurrent.SynchronousExecutor()\n else:\n executor = concurrent.ProcessPoolExecutor(max_workers=maximum_jobs)\n\n result_list = []\n with executor:\n try:\n # Submit initial tasks.\n not_done = {executor.subm... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set self.current to most recent 'Not run' or 'Failed' step. | def _get_current(self):
if self.order:
for step in self:
if not step.done or step.failed:
self.current = step.name
return
self.current = None | [
"def _handleLastStep(self) -> None:\n if self._graphical:\n self.unit.moveTo(self.destinationTile.center)\n self.isPerformed = True\n self._unitsLocation[self.unit] = self.destinationTile.identifier",
"def test_previous_run(self):\n conn = self.reporter.conn\n\n test_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Overwrite with parent's save. | def save(self):
if hasattr(self.parent, 'parent'):
self.parent.parent.save()
elif hasattr(self.parent, 'save'):
self.parent.save()
else:
raise self.StepError('Cannot save without a parent') | [
"def save(self):\n self.parent.save()",
"def update_parent(self, old_parent, new_parent):\n\n bpy.ops.object.mode_set(mode='EDIT')\n edit_bones = self.obj.data.edit_bones\n\n for child in edit_bones[old_parent].children:\n child.parent = edit_bones[new_parent]",
"def paren... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Run a test function. Will evalucate to success if test function returns True or 0, failure on any other return. Any exceptions raised during the handling will cause failure. If raise_on_fail is True, a FailedTest Exception or the function's own Exception will be raised. Otherwise they will not. | def run_test(self, test, raise_on_fail=True):
self.log('Running test ' + str(test), level=0)
self._test_test(test)
# Run the function
out = False
if isinstance(test, tuple):
out = run_function(*test)
else:
out = run_function(test)
# Test t... | [
"def test_case(test_fn):\n from functools import wraps\n\n @wraps(test_fn)\n def wrapper(*args, **kwargs):\n try:\n result, msg = test_fn(*args, **kwargs)\n except (ResponseError, ValidationError) as exc:\n if args[0].verbosity > 1:\n traceback.print_exc()... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write a comment to self.comment. Will fail if comment alread exists and overwrite/append not True | def add_comment(self, comment, overwrite=False, append=False):
if self.comment and not overwrite and not append:
self.log('Comment already exists, specify overwrite=True,' +
'or append=True to save this comment.', 'error')
return False
if self.comment and app... | [
"def _write_comment(self, comment):\n\n # Write the comment into the log\n self._file.write(comment + \"\\n\")\n\n # If appropriate, print the comment into the screen\n if not self._silent:\n print(comment)\n\n # Flush the file\n self._file.flush()",
"def write... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return detailed information about all substeps if it exists. | def get_steps(self, include_outputs=True):
if not self.file_list:
return 'No substeps in {}'.format(self)
if not self.steps:
self._create_substeps()
output = ''
for step in self.steps:
output = output + '\n\n' + str(step)
if include_outputs... | [
"def sub_workflow_info(self):\n return self._sub_workflow_info",
"def getExtractionSubgraphs(self):\n return self.extractionSubgraphs",
"def get_subway_data():\n # Call the routes endpoint, filtering on route types 0 and 1\n # (light rail and heavy rail)\n data = call_mbta_api('routes', '... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a formatted string containing self.out and self.err. | def get_outputs(self):
output = ''
if self.out:
output = output + "\nOutput:\n{}".format(self.out)
if self.err:
output = output + "\nSTDERR:\n{}".format(self.err)
return output | [
"def _construct_msg(self) -> str:\n return '\\n'.join([\n self._formatted_filename(), self._err_description()])",
"def __str__(self):\n header = \"Traceback\"\n if self.COLORIZE:\n header = Colorize.apply(header, 'traceback-header')\n header = \"{}{} (most recent ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Use self.file_list to add sub_steps to self. | def _create_substeps(self):
if not self.file_list:
raise self.StepError('Cannot add substeps without a file list')
if not self.steps:
self.steps = [] # Make sure steps is a list
for file in self.file_list:
file = str(file)
# If args exist, replace... | [
"def _add_steps(self, steps):\n for step in steps:\n self._add_step(step)",
"def sub_file_entries(self):",
"def add_files(path, file_list, mana, step_len, snr):\n for the_file in file_list:\n mana.read_data(path + the_file, step_len=step_len, snr=snr, norm=True)",
"def add_child_fi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test a single test instance to make sure it is usable. If args contain REGEX ('<StepError'), then return False, if not and all other tests pass return True. | def _test_test(self, test):
if test is None:
return None # This is a crude way to distinguish fail from None
if isinstance(test, tuple):
if len(test) != 2:
raise self.StepError('Test must have only two values:' +
'the function... | [
"def __validate_if_runnable(self):\n if not self.step_impl or not self.step_impl_match:\n raise RadishError(\n \"Unable to run Step '{} {}' because it has \"\n \"no Step Implementation assigned to it\".format(self.keyword, self.text)\n )\n\n if self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Actually execute the function and return a dictionary of values. | def _execute(self, kind=''):
return_dict = {'start_time': time.time()}
args = (self.command, self.args) if self.args else (self.command,)
try:
return_dict['out'] = run_function(*args)
except Exception as e:
return_dict['failed'] = True
return_dict['EXC... | [
"def _execute(self, kind=''):\n return_dict = {}\n # Set kind from storage option\n if not kind:\n kind = 'get' if self.store else 'check'\n\n # Make a string from the command as we run with shell=True\n if self.args:\n if isinstance(self.args, (list, tuple))... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Actually execute the command and return a dictionary of values. | def _execute(self, kind=''):
return_dict = {}
# Set kind from storage option
if not kind:
kind = 'get' if self.store else 'check'
# Make a string from the command as we run with shell=True
if self.args:
if isinstance(self.args, (list, tuple)):
... | [
"def _execute(self, kind=''):\n return_dict = {'start_time': time.time()}\n args = (self.command, self.args) if self.args else (self.command,)\n try:\n return_dict['out'] = run_function(*args)\n except Exception as e:\n return_dict['failed'] = True\n retu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Overwrite with parent's save. | def save(self):
self.parent.save() | [
"def save(self):\n if hasattr(self.parent, 'parent'):\n self.parent.parent.save()\n elif hasattr(self.parent, 'save'):\n self.parent.save()\n else:\n raise self.StepError('Cannot save without a parent')",
"def update_parent(self, old_parent, new_parent):\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return an AlleleSeqPipeline object restored from the pickle_file. prot can be used to change the default protocol | def restore_pipeline(pickle_file=DEFAULT_FILE):
with open(pickle_file, 'rb') as fin:
return pickle.load(fin) | [
"def get_pipeline(pickle_file=DEFAULT_FILE, root='.', prot=DEFAULT_PROT):\n if os.path.isfile(pickle_file):\n return restore_pipeline(pickle_file)\n else:\n pipeline = Pipeline(pickle_file=os.path.abspath(str(pickle_file)),\n root=os.path.abspath(str(root)),\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create or restore a pipeline at pickle_file. If pickle file exists, restore it, else make a new session and save it. Return AlleleSeqPipeline object | def get_pipeline(pickle_file=DEFAULT_FILE, root='.', prot=DEFAULT_PROT):
if os.path.isfile(pickle_file):
return restore_pipeline(pickle_file)
else:
pipeline = Pipeline(pickle_file=os.path.abspath(str(pickle_file)),
root=os.path.abspath(str(root)),
... | [
"def restore_pipeline(pickle_file=DEFAULT_FILE):\n with open(pickle_file, 'rb') as fin:\n return pickle.load(fin)",
"def load_pipeline(name):\r\n pipeline = _load(name, get_pipelines_paths())\r\n if pipeline is None:\r\n raise ValueError(\"Unknown pipeline: {}\".format(name))\r\n\r\n ret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Run command and return status, output, stderr. cmd is run with shell, so must be a string. | def run_cmd(cmd):
pp = Popen(str(cmd), shell=True, universal_newlines=True,
stdout=PIPE, stderr=PIPE)
out, err = pp.communicate()
code = pp.returncode
if out[-1:] == '\n':
out = out[:-1]
if err[-1:] == '\n':
err = err[:-1]
return code, out, err | [
"def Run(cmd):\n proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n out = proc.stdout.read()\n err = proc.stderr.read()\n code = proc.wait()\n return int(code), out.decode('UTF-8'), err.decode('UTF-8')",
"def execute_cmd(cmd):\n\tp = Popen(cm... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Use `which` to get the path of an executable. Raises PathError on failure | def get_path(executable, log=None):
code, out, err = run_cmd('which {}'.format(executable))
if code != 0 or err == '{} not found'.format(executable):
raise PathError('{} is not in your path'.format(executable), log)
else:
return os.path.abspath(out) | [
"def which(executable_name, env_var='PATH'):\n exec_fp = None\n\n if env_var in os.environ:\n paths = os.environ[env_var]\n\n for path in paths.split(os.pathsep):\n curr_exec_fp = os.path.join(path, executable_name)\n\n if os.access(curr_exec_fp, os.X_OK):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Build a file list from an r'' regex expression. | def build_file_list(file_regex, root='.'):
file_list = []
# Check depth of regex search
parts = tuple(file_regex.split('/'))
# Build a list of all possible files
if len(parts) == 1:
files = os.listdir(root)
elif len(parts) == 2:
directories = [i for i in os.listdir(root) if re.ma... | [
"def reglob(path, regex):\n return [file for file in os.listdir(path) if re.match(regex, file)]",
"def _regex_matches(self, file_list: [str]):\n return [m for m in [self.regex.match(f) for f in file_list] if m]",
"def __init__(self, filename):\n f = open(filename)\n self.relist = list()\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Substitute all instances of args_regex in args. Works if args is a str, list, tuple, or dict. All values replaced with re.sub. If args is dict, only the values, not the keys, are replaced. | def sub_args(args, args_regex, sub):
step_regex = re.compile(args_regex)
if isinstance(args, str):
return step_regex.sub(sub, args)
elif isinstance(args, (tuple, list)):
step_args = []
for arg in args:
step_args.append(step_regex.sub(sub, arg))
return tuple(step_a... | [
"def replace(self, *args, **kwargs):\n\n params = {\n k: v for k, v in zip((\"lower\", \"upper\", \"lower_inc\", \"upper_inc\"), args)\n }\n params.update(kwargs)\n\n has_lower = \"lower\" in params\n has_lower_inc = \"lower_inc\" in params\n if not has_lower_inc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate the total amount of votes depending on the candidate's name inputted to the function | def votes(CandidateName):
total = 0
for row in candidate:
if row == CandidateName:
total += 1
return total | [
"def add_votes(self, candidate, votes):\n if not candidate in self.candidates.keys():\n raise ValueError\n else:\n self.candidates[candidate][\"votes\"] += votes\n self.total_votes += votes",
"def candidate_votes():\n for name in votedCandidates: \n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Unique list of Candidates with votes | def voted_candidate():
for row in candidate:
if row not in votedCandidates:
votedCandidates.append(row)
return votedCandidates | [
"def candidate_votes():\n for name in votedCandidates: \n candidateVotes.append(votes(name))\n return candidateVotes",
"def sort_candidates(self):\n self.candidates.sort(key=lambda x:x.get_votes(), reverse=True)",
"def fetch_candidates(self):\n return (\n Versio... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
List of the vote percent for each candidate with a 3 decimal format | def vote_percent():
for vote_amount in candidateVotes:
votePercent = '{:.3f}'.format(float(vote_amount/TotalVotes)*100)
candidateVotesPercent.append(votePercent)
return candidateVotesPercent | [
"def get_percentage_summary(self):\n summary = {}\n for candidate in self.candidates:\n summary[candidate] = self.__safeCalculateVotePercentage(self.candidates[candidate][\"votes\"], self.total_votes)\n return summary",
"def vote_percentage(results):\n yes = results.count('yes')... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
List of the total votes for each candidate | def candidate_votes():
for name in votedCandidates:
candidateVotes.append(votes(name))
return candidateVotes | [
"def votes(CandidateName):\n total = 0 \n for row in candidate:\n if row == CandidateName:\n total += 1\n return total",
"def get_total_votes(self):\n return self.total_votes",
"def get_votes(self, candidate):\n if not candidate in self.candidates.key... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates new pagerank based on corpus and old pagerank, returns the new pagerank | def pagerank_calc(corpus, old_pagerank, damping_factor):
new_pagerank = {}
pages = list(corpus.keys())
pagerank_base_prob = (1-damping_factor)/len(pages)
for page in pages:
# Set of tuples of all the links that link to the current page
# (page_name, num_links_on_the_page)
links ... | [
"def sample_pagerank(corpus, damping_factor, n):\n page_rank = {}\n #Initialize rank of each page in the corpus to 0.0\n for page in corpus:\n page_rank[page] = 0\n sample = random.choice(list(corpus))\n page_rank[sample] += 1/n\n for i in range(1, n + 1):\n model = transition_model(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the predictor for the current configuration (either provided to the function or read from file). Contains a prediction model and metainfo, such as the model name. Loads config, model etc. from file on the first invocation, and stores the result. Future invocations will return the predictor that was created on the f... | def get_predictor(configuration: Dict = None) -> Predictor:
global _predictor
if not _predictor:
if configuration:
_predictor = _load_predictor(configuration)
else:
with open("config.json") as json_file:
_predictor = _load_predictor(json.load(json_file))
... | [
"def predictor(self) -> \"torch.nn.Module\": # type: ignore\n if self._predictor is None:\n self._predictor = torch.jit.load(self.path).eval()\n return self._predictor",
"def create_predictor(model_config, model_weights, threshold):\n cfg = get_cfg()\n cfg.merge_from_file(model_con... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Logs messages with debug log level. | def debug(self, *messages):
self.log(LOGLEVELS["debug"], "\n[Debug]", *messages) | [
"def debug(self, msg, *args, **kwargs):\n self.write(msg, level='DEBUG', *args, **kwargs)",
"def debug(self,msg):\n self.logger.debug(msg)",
"def debug(msg):\n if DEBUG:\n log.debug(msg)",
"def cmd_debug(self):\r\n self.log.setLevel(logging.DEBUG)\r\n self.log.debug('Swit... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Logs messages with info log level. | def info(self, *messages):
self.log(LOGLEVELS["info"], "\n[Info]", *messages) | [
"def info(self, msg, *args, **kwargs):\n self.write(msg, level='INFO', *args, **kwargs)",
"def info(self,msg):\n self.logger.info(msg)",
"def cmd_info(self):\r\n self.log.setLevel(logging.INFO)\r\n self.log.info('Switching to INFO threshold')",
"def info(self, message: str, **extra... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Logs messages with important log level. | def important(self, *messages):
self.log(LOGLEVELS["important"], "\n[Important]", *messages) | [
"def important(self, msg, *args, **kwargs):\n self.print(40, msg, *args, **kwargs)",
"def logg(msg):\n logging_log(LOGGING_LEVELS['NORMAL']['level'], msg)",
"def important(msg, *args, **kwargs):\n if len(print_root.handlers) == 0:\n basicConfig()\n print_root.important(msg, args, kwargs)"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Logs messages with warn log level. | def warn(self, *messages):
self.log(LOGLEVELS["warn"], "\n[Warn]", *messages) | [
"def cmd_warning(self):\r\n self.log.setLevel(logging.WARNING)\r\n self.log.warning('Switching to WARNING threshold')",
"def warning(msg):\n _syslog(syslog.LOG_WARN, msg)",
"def cmd_warning(self):\n self.log.setLevel(logging.WARNING)\n self.log.warning('Switching to WARNING thresh... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get_module_version Retrieves version of specified module | def get_module_version(module=None):
# check if module type is valid
assert not (module is None) and isinstance(
module, types.ModuleType
), "[VidGear CORE:ERROR] :: Invalid module!"
# get version from attribute
version = getattr(module, "__version__", None)
# retry if failed
... | [
"def module_version(product='mangadap'):\n try:\n modules = os.environ['LOADEDMODULES']\n except:\n# print_frame('Exception')\n# modules = None\n return None\n # TODO: Re-raise the exception?\n \n # Parse the loaded version(s) of product\n versions = [module.split('/')[1]... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
import_core_dependency Imports specified core dependency. By default(`error = raise`), if a dependency is missing, an ImportError with a meaningful message will be raised. Also, If a dependency is present, but version is different than specified, an error is raised. | def import_core_dependency(
name, pkg_name=None, custom_message=None, version=None, mode="gte"
):
# check specified parameters
assert name and isinstance(
name, str
), "[VidGear CORE:ERROR] :: Kindly provide name of the dependency."
# extract name in case of relative import
sub... | [
"def handleImportError(self, exception):\n first = exception.args[0]\n if first.find('No module named ') < 0:\n raise\n module = first[len('No module named '):]\n module = module.split('.')[0]\n\n if module in self._deps.keys():\n dep = self._deps[module]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Figure out which chunk is going to be read next. It should be the one with the least number of records read by the moment. | def _next_chunk_id(property_chunks: Mapping[int, PropertyChunk]) -> Optional[int]:
non_exhausted_chunks = {
# We skip chunks that have already attempted a sync before and do not have a next page
chunk_id: property_chunk.record_counter
for chunk_id, property_chunk in property_... | [
"def get_block(self, size=1024):\n # read in some more data\n data = self._stream_handle.read(size)\n if data:\n self._chunker.add_chunk(data, self._timestamp)\n return len(data)\n else: # EOF\n raise EOFError",
"def _GetFirstUnconsumedRecord(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the latest state by comparing the cursor value in the latest record with the stream's most recent state object and returning an updated state object. Check if latest record is IN stream slice interval => ignore if not | def get_updated_state(self, current_stream_state: MutableMapping[str, Any], latest_record: Mapping[str, Any]) -> Mapping[str, Any]:
latest_record_value: pendulum.DateTime = pendulum.parse(latest_record[self.cursor_field])
slice_max_value: pendulum.DateTime = pendulum.parse(self._slice.get("end_date"))
... | [
"def get_updated_state(self, current_stream_state: MutableMapping[str, Any], latest_record: Mapping[str, Any]):\n slice_value = getter(latest_record, self.record_slice_key)\n updated_state = self.convert_cursor_value(latest_record[self.cursor_field])\n stream_state_value = current_stream_state.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Yield describe response of SObjects defined in catalog as streams only. | def read_records(self, **kwargs) -> Iterable[Mapping[str, Any]]:
for sobject in self.sobjects_to_describe:
yield self.sf_api.describe(sobject=sobject) | [
"def test_get_streams(self, proxy):\n\n xpath = \"/restconf-state/streams\"\n streams = proxy(IetfRestconfMonitoringYang).get(xpath)\n for stream in streams.stream:\n assert len(stream.access) == 4\n\n # Confd supports NETCONF and uagent_notification streams currently\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This program creates a function that takes in a list as input and then swaps the first and last elements of given elements in the list. | def swap_last_item(list):
list[0], list[-1] = list[-1], list[0] # indexes of list getting swapped
return list # returns the new list with indexes swapped | [
"def Myfunc(myList):\n myList[0], myList[-1] = myList[-1], myList[0]\n return myList",
"def _swap(list_, a, b):\n list_[a], list_[b] = list_[b], list_[a]",
"def swap(nums: List[int], i: int, j: int) -> None:\n nums[i], nums[j] = nums[j], nums[i]",
"def swap(list, old, new):\n index = li... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determines if it is possible to finish all courses. | def can_finish(num_courses: int, prerequisites: List[List[int]]) -> bool:
def DFS(start, my_dict, course_state):
course_state[start] = 1
for pre_course in my_dict[start]:
if course_state[pre_course] == 1:
return True
if course_state[pre_course] == 0:
... | [
"def game_is_finished():\n for room in ALLROOMS.values():\n if not room.needs_complete(): # any room is incomplete, not done\n return False\n return True # all rooms complete, game is finished",
"def could_take_course(self,course):\r\n #if course.count() >= course.max_size: return... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initializes a state, given the bin, list of objects, and next object. | def __init__(self, bin, objects, next_object):
self.bin = bin
self.objects = objects
self.next_object = next_object | [
"def __init__(self, state=0, neighbours=[], age=0):\n\t\tself.state=state\n\t\tself.neighbours=[]\n\t\tself.age=age",
"def __init__(self, value=None, next=None):\n self.value = value\n self.next = next",
"def __init__(self, state: 'SoState'):\n this = _coin.new_SoNormalCache(state)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates and returns a copy of this state. The bin and next_object are replicated, but the list of objects is a shallow copy (a new list, but the same objects). Returns State A copy of this instance of State | def copy(self):
bin_copy = self.bin.copy()
obj_copy = [o for o in self.objects]
next_obj_copy = self.next_object.copy()
# new_state = State(self.bin, self.objects, self.next_object)
new_state = State(bin_copy, obj_copy, next_obj_copy)
return new_state | [
"def Clone(self):\n st = GoState(self.size)\n st.board=copy.deepcopy(self.board [:])\n st.playerJustMoved = self.playerJustMoved\n st.points1=self.points1\n st.points2=self.points2\n st.size=self.size\n st.lastpass=self.lastpass\n st.komove=self.komove\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initializes an action, given the transform and next object. | def __init__(self, transform, next_object):
self.transform = transform
self.rotation = transform[:2,:2]
self.translation = transform[:2,2]
self.next_object = next_object | [
"def __init__(self, action, init_pages=[], limit=float('inf'), verbosity=0):\n if limit is None:\n limit = float('inf')\n\n if type(init_pages == str):\n init_pages = [init_pages]\n\n if not callable(action):\n raise TypeError(\"'action' must be callable\")\n\n self._action = action\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update a notebook by ID | def update(user, id, name, color):
notebook = Notebook.query.filter_by(id=id, user_id=user.id).first()
if not notebook:
raise UnprocessableEntity(description="NOTEBOOK_NOT_FOUND")
notebook.name = name
notebook.color = color
notebook.updated_at = int(time.time())
... | [
"def save_notebook(self, notebook_id, data, name=None, format=u'json'):\n if format != 'json':\n raise Exception('Only supporting JSON in Django backed notebook')\n n = Notebook.objects.get(id=notebook_id)\n if n.archive == True:\n raise Exception('Cannot update archived copy')\n # update copy... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The purpose of the cursor is for the race condition which results if new messages arrive while subscriber is receiving messages and requests a new subscription. The subscriber sends back the cursor of the last message it received. callback must be wrapped in a tornado async_callback | def subscribe(self, cursor=None, callback=None, channel_name=None):
if callback is None:
callback = self.async_callback(self._subscribe_callback)
if channel_name is None:
self._required_attr_check()
channel_name = self.CHANNEL_NAME
chan_data = BaseChannel._c... | [
"def consume_data(cur: cursor):\n consumer = KafkaConsumer(\n bootstrap_servers=\"localhost:9094\",\n auto_offset_reset=\"earliest\",\n group_id=\"log_group\",\n enable_auto_commit=True,\n consumer_timeout_ms=100000,\n value_deserializer=lambda x: loads(x.decode(\"utf-8\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a JsonTranslator test subject. | def subject() -> JsonTranslator:
return JsonTranslator() | [
"def test_get_subject(self):\n pass",
"def test_get_subjects(self):\n pass",
"def get() -> Subject:\n return self._subject",
"def get_subject(index, subject, user=None):\n client = load_search_client(user)\n try:\n idata = get_index(index)\n if version.parse(gl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a minimal JsonProtocol with the given elements, to use as test input. | def _make_v6_json_protocol(
*,
pipettes: Dict[str, Pipette] = {
"pipette-id-1": Pipette(name="p10_single"),
},
labware_definitions: Dict[str, LabwareDefinition] = {
"example/plate/1": _load_labware_definition_data(),
"example/trash/1": _load_labware_definition_data(),
},
... | [
"def _make_v7_json_protocol(\n *,\n labware_definitions: Dict[str, LabwareDefinition] = {\n \"example/plate/1\": _load_labware_definition_data(),\n \"example/trash/1\": _load_labware_definition_data(),\n },\n commands: List[protocol_schema_v7.Command] = [],\n liquids: Dict[str, Liquid] ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a minimal JsonProtocol with the given elements, to use as test input. | def _make_v7_json_protocol(
*,
labware_definitions: Dict[str, LabwareDefinition] = {
"example/plate/1": _load_labware_definition_data(),
"example/trash/1": _load_labware_definition_data(),
},
commands: List[protocol_schema_v7.Command] = [],
liquids: Dict[str, Liquid] = {
"liq... | [
"def _make_v6_json_protocol(\n *,\n pipettes: Dict[str, Pipette] = {\n \"pipette-id-1\": Pipette(name=\"p10_single\"),\n },\n labware_definitions: Dict[str, LabwareDefinition] = {\n \"example/plate/1\": _load_labware_definition_data(),\n \"example/trash/1\": _load_labware_definition... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test translating v6 commands to protocol engine commands. | def test_load_command(
subject: JsonTranslator,
test_v6_input: protocol_schema_v6.Command,
test_v7_input: protocol_schema_v7.Command,
expected_output: pe_commands.CommandCreate,
) -> None:
v6_output = subject.translate_commands(
_make_v6_json_protocol(commands=[test_v6_input])
)
v7_o... | [
"def test_pi18_fullcommand_PEH(self):\n protocol = pi()\n result = protocol.get_full_command(\"PEH\")\n expected = b\"^S006PEH\\r\"\n # print(result)\n self.assertEqual(result, expected)",
"def test_pi18_fullcommand_VFW(self):\n protocol = pi()\n result = protocol.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test Rule IDs are Unique | def test_rule_ids_unique(self):
existing_rules = []
for rule in self.rules:
self.assertFalse(rule.id in existing_rules)
existing_rules.append(rule.id) | [
"def test_unique_based_on_id(self):\n unique = misc.unique_based_on_id\n self.assertSequenceEqual(unique([]), [])\n self.assertSequenceEqual(unique([1, 2, 3]), [1, 2, 3])\n self.assertSequenceEqual(unique([1, 1, 3]), [1, 3])\n self.assertSequenceEqual(unique([[], [], 3]), [[], [],... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test Rule IDs are property formmated | def test_rule_ids_are_formatted_correctly(self):
for rule in self.rules:
self.assertIn(rule.id[0], ['W', 'I', 'E'])
self.assertEqual(len(rule.id), 5)
self.assertTrue(isinstance(int(rule.id[1:]), int)) | [
"def test_id(self):\n\n self.assertEqual(self.r1.id, 1)\n self.assertEqual(self.r2.id, 2)\n self.assertEqual(self.r3.id, 3)\n self.assertEqual(self.r4.id, 9)",
"def match_rule_id(self, rule_id, match):\n pass",
"def test_penaltyshootouts_id_get(self):\n pass",
"def te... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns True if synset2 is a hypernym of synset1, or if they are the same synset. Returns False otherwise. | def hypernymOf(synset1, synset2):
if synset1 == synset2:
return True
for hypernym in synset1.hypernyms():
if synset2 == hypernym:
return True
if hypernymOf(hypernym, synset2):
return True | [
"def _can_be_object(self, synsets: Sequence[Synset]) -> bool:\n for synset in synsets:\n for lch in synset.lowest_common_hypernyms(self.wn_organism_synset):\n # logger.debug(f\"synset: {synset.name()}, lowest common hypernym: {lch.name()}\")\n if lch.name() != self.wn... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns an example JSON string for testing, with metadata included | def fixture_example_json_with_metadata():
return json.dumps(_example_dict(with_metadata=True)) | [
"def generate_example_json(config):\n return generate_example(config, ext=\"JSON\")",
"def test_recipe_to_json():\n recipe = Recipe(\"Tuna pasta\", ingreds)\n data = recipe.to_json()\n assert data[\"name\"] == recipe.name\n assert data[\"ingredients\"] == recipe.ingreds",
"def testDataInJson(self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that RabbitMessage.from_json() can load a JSON string and deserialise it into dataclasses | def test_rabbit_json_load(example_json):
deserialized = RabbitMessage.from_json(example_json)
assert deserialized.event_type == "compute.instance.create.end"
assert deserialized.project_name == "project_name"
assert deserialized.project_id == "project_id"
assert deserialized.user_name == "user_name"... | [
"def from_json(cls, json_str: str) -> Sender:\n return cls.from_dict(json.loads(json_str))",
"def from_json(self, json_str):",
"def from_json(s):\n d = json.loads(s)\n return MsgFwd.from_json_dict(d)",
"def protobuf_from_json(json_str, message_type, *args, **kwargs):\n value = json.loads(json_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
dispatch a list of that result in the routing of msgcause. uses either localnode.sender or the 'processing' visitor if the message is for an app above this node. | def dispatch_one(self, msgcause, destinations):
if destinations != None and len(destinations)>0:
for next_hop, message in destinations:
message.sign("@%s: %i destinations"%(
self.__local_node.partition_id,len(destinations)))
if(next_hop !=... | [
"def eventDispatcher(self):\n event = self.nextEvent()\n if event < 0:\n return\n else:\n log.msg(\"processing event: %s\" % event)\n fields = event.split(separator)\n try:\n sequence = int(fields[0])\n except:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns True iff self and other are functionally the same posts. | def __eq__(self, other: 'Post') -> bool:
return (type(self) == type(other) and self.comments == other.comments
and self.author == other.author and self.link == other.link
and self.timestamp == other.timestamp
and self.price == other.price and self.content == other... | [
"def is_same(self, other):\n return self.self_traits == other.self_traits",
"def __eq__(self, other: Transform) -> bool:\n if len(self.transforms) != len(other.transforms):\n return False\n else:\n return all([a == b for a, b in zip(self.transforms, other.transforms)])",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns True iff the content of the post is likely a seller. All product posts are sellers. | def is_seller(self) -> bool:
keywords = ['budget']
for word in keywords:
if word in self.content.lower():
return False
return True | [
"def is_seller_search(self) -> bool:\n assert self._is_seller_search is not None, \"is_seller_search not set!\"\n return self._is_seller_search",
"def is_sell(self) -> bool:\n return self.side == TradeSide.SELL",
"def is_bestseller(self, book) -> bool:\n\n product = WebDriverWait(sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns True iff the content of the post is likely a sublet. | def is_sublet(self) -> bool:
keywords = ['sublet', 'sublease']
for word in keywords:
if word in self.content.lower():
return True
return False | [
"def _is_subword(self, token):\n token = self._tokenizer.convert_tokens_to_string(token)\n return True",
"def is_body(part):\n if get_content_type(part) == 'text/plain':\n if not is_attachment(part):\n return True\n return False",
"def should_process_post(post: PostSummary,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns True iff the price of the post is between the lower and upper bounds, inclusive. | def in_price_range(self, upper: int, lower: int=0) -> bool:
return lower <= self.price <= upper | [
"def interval_check(self, lower, upper):\n return self.function(lower) * self.function(upper) < 0",
"def in_range(self, value):\n return ((self.lower_bound is None or value >= self.lower_bound) and\n (self.upper_bound is None or value <= self.upper_bound))",
"def __is_between(self, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a list of prices found in a body of text. Prices must be preceded by a dollar sign. >>> text = 'It is $1,000.50/month total; the bedroom is $500.' >>> extract_prices(text) [1000, 500] | def extract_prices(body: str) -> List[int]:
prices = []
price = ''
i = 0
while i < len(body):
if body[i] == '$':
price += body[i]
elif len(price) > 0 and body[i].isnumeric():
price += body[i]
elif len(price) > 0 and body[i] != ',':
prices.appen... | [
"def scrape_prices(self) -> list:\r\n cars = self.__cars\r\n prices = []\r\n for car in cars:\r\n try:\r\n price = (\r\n car.find(\"div\", attrs={\"class\": \"announcement-pricing-info\"})\r\n .text.strip()\r\n .... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the lowest price in prices, as long it surpasses LOW_PRICE. Returns None if there are no suitable prices. >>> lowest_price([2000, 1000, 1500]) 1000 >>> lowest_price([10, 25, 1000]) 1000 >>> print(lowest_price([10])) None | def lowest_price(prices: List[int]) -> Union[int, None]:
new_prices = [x for x in prices if x > Post.LOW_PRICE]
if new_prices != []:
return min(new_prices)
return None | [
"def low_price(stock_prices):\n\n lowest = (stock_prices[0], 0)\n\n for i, price in enumerate(stock_prices):\n if price < lowest[0]:\n lowest = (price, i)\n\n return lowest[1]",
"def _getLowestPrice( self, node ):\n\n\t\tprice = -1\n\t\tif etree.tostring(node).find( \"<LowestNewPrice>\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
convert fasta to vcf dataframe Input Fasta file, _ref is recognized as ref and _alt is used as alt, these are two keywords Output | def fasta2vcf(f):
my_dict = {}
for r in SeqIO.parse(f, "fasta"):
my_dict[r.id] = str(r.seq).upper()
print (my_dict)
vcf = pd.DataFrame()
index_list = []
chr_list = []
pos_list = []
ref_list = []
alt_list = []
seq_list = []
for k in my_dict:
if not "_ref" in k:
continue
name = k.replac... | [
"def vcf_annot(args):\n \n headers=['chrom','pos','id','ref','alt','type','depth','alt_reads','alt_reads_percentage','ref_reads_percentage',\\\n 'allele_freq','symbol','major_consequence','gene_id_ens']\n \n #Initiate dataframe\n annot_df=pd.DataFrame(columns=headers)\n \n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
given the target_fa we extracted from target_pos, we get sub fasta | def sub_fasta_single(target_fa,target_pos, abs_start,abs_end):
N = int(len(target_fa)/2)
start = N-(target_pos-abs_start)
end = abs_end - abs_start + start
seq = target_fa[start:end]
if len(target_fa)<1000:
## user input fasta:
seq = target_fa[abs_start:abs_end]
return seq | [
"def extract_sub_alignment_read_seq(aln, ref_start, ref_end):\n # TODO TODO TODO implement this!",
"def fastaextract(inputfile, fastafile):\n subsequences = {}\n\n if os.path.isfile(inputfile):\n file = open(inputfile, \"r\") \n for line in file:\n if line.startswith(\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
RNA fold python binding | def call_RNAplfold(seq,scaffold_length):
# scaffold - RTT - PBS
# we only care about RTT+PBS (3' extension) pairs with scaffold
data = []
fc = RNA.fold_compound(seq, md, RNA.OPTION_WINDOW)
fc.probs_window(ulength, RNA.PROBS_WINDOW_BPP | RNA.PROBS_WINDOW_UP, pf_window_callback2, data)
# parse output
d... | [
"def R_caller(working_dir, fold_input_path, fold_output_path, train_val_file,\n test_file, isRef, isSaveTrain):\n r = ro.r\n r.source(os.path.join(working_dir, 'run_ComBat.R'))\n _ = r['ComBatHarm'](working_dir, fold_input_path, fold_output_path,\n train_val_file, test_fi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Grab score from web server input gRNA list should include PAM sequence, PAM is NGG | def get_DeepSpCas9_score(gRNA_list):
url="http://deepcrispr.info/DeepSpCas9/"
br = mechanize.Browser()
br.set_handle_robots(False) # ignore robots
br.open(url)
br.select_form(nr=0)
br["ENTER_FASTA"] = list_to_fasta(gRNA_list)
res = br.submit()
output = res.read()
res = parse_webpage(output)
flag = F... | [
"def get_score(play):\n scores = []\n away_score_str = \"\"\n home_score_str = \"\"\n raw_score = play.split('class=\"combined-score\">')[1]\n count = 0\n home_away_flag = 0\n while True:\n if raw_score[count] == \"<\":\n break\n elif raw_score[count] in [\" \", \"-\"]:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handle stuff when the dock is closed | def dockCloseEventTriggered(self):
self.close()
self.deleteLater() | [
"def OnCloseWindow(self):\n pass",
"def onClosePlugin(self):\n #on clean les combobox\n self.dockwidget.list_exu.clear()\n self.dockwidget.list_bv.clear()\n\n #print \"** CLOSING DrawJoinFeature\"\n\n # disconnects\n self.dockwidget.closingPlugin.disconnect(self.on... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
creates links to all class of the passed in application for which get_listview_url() methods have been registered | def nav_menu(app=None):
if app:
models = ContentType.objects.filter(app_label=app)
result = []
for x in models:
modelname = x.name
modelname = modelname.replace(" ", "").lower()
try:
fetched_model = ContentType.objects.get(
... | [
"def gen_app_urls(user_app_name):\n\n doc = gen_docstring(open_string=True)\n\n doc += '''URL map for %s app.\n\"\"\"\n\n# import application specific handlers\n''' % user_app_name\n\n doc += '''\nURLS = [] # Fill up app specific urlmap\n\n__all__ = ['URLS']\n\n\nif __name__ == '__main__':\n pass\n'''\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fetches the Libras Movement dataset Returns X, Y | def libras_movement():
dataset = csv.reader(open('data/movement_libras.data', 'r'))
X = []
Y = []
for element in dataset:
X.append(element[:-1])
Y.append(element[-1])
return np.array(X).astype('float'), np.array(Y).astype('float') | [
"def get_sensor_laser_data(self, sensor):\n direction = sensor.direction\n current_pos = pygame.math.Vector2(sensor.x, sensor.y)\n\n for _ in range(max(self.width, self.height)):\n current_pos += direction\n find_flag = False\n for sprite in self.group_walls:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates the actual shellcode payload | def gen_shellcode(ret_address):
if len(SHELLCODE) > BUFFER_LEN:
print("Error: Shellcode is too big for the buffer!\n")
exit()
# Space to fill with nop instruction
padding_len = BUFFER_LEN - len(SHELLCODE)
padding_str = (NOP * padding_len)
output = padding_str
output += SHE... | [
"def generate_powershell_shellcode(\n self, posh_code, arch=\"both\", dot_net_version=\"net40\"\n ):\n if arch == \"x86\":\n arch_type = 1\n elif arch == \"x64\":\n arch_type = 2\n elif arch == \"both\":\n arch_type = 3\n\n directory = self.gene... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Devolve se a dada posicao se encontra livre. | def eh_posicao_livre(tab, pos):
# eh_posicao_livre: tabuleiro x posicao -> booleano
if not (eh_tabuleiro(tab) and eh_posicao(pos)):
raise ValueError('eh_posicao_livre: algum dos argumentos e invalido')
return obter_valor_posicao(tab,pos) == 0 | [
"def elementsPosCechk(self):\n\t\teps = 0.0000001\n\t\t#---------move LI_S16B:FCT00 and LI_S16B:SCT00 to LI_MEBT2\n\t\tseq0 = None\n\t\tseq1 = None\n\t\tfor acc_seq_da in self.acc_seqs_da:\n\t\t\tif(acc_seq_da.stringValue(\"name\") == \"LI_S16B\"):\n\t\t\t\tseq0 = acc_seq_da\n\t\t\tif(acc_seq_da.stringValue(\"name\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Devolve o tuplo ordenado com todas as posicoes livres do tabuleiro dado. | def obter_posicoes_livres(tab):
# obter_posicoes_livres: tabuleiro -> tuplo
if not eh_tabuleiro(tab):
raise ValueError('obter_posicoes_livres: o argumento e invalido')
vect = ()
for n in range(1,10):
if eh_posicao_livre(tab,n):
vect += (n,)
return vect | [
"def llenarTablero(self):\n y=0 \n for miniterminos in self.renglonesHoja:\n for mini in miniterminos.miniterminosSimpli:\n x=self.indices[mini]\n self.columnas[y][x]=1\n y=y+1",
"def obter_linhas_colunas_diagonais(tab, pos):\n # obter_linhas_c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Devolve um tuplo com os tuplos correspondentes a todas as linhas, colunas e diagonais a que essa posicao pertence. | def obter_linhas_colunas_diagonais(tab, pos):
# obter_linhas_colunas_diagonais: tabuleiro x posicao -> tuplo
if not (eh_tabuleiro(tab) and eh_posicao(pos)):
raise ValueError('obter_linhas_colunas_diagonais: algum dos argumentos e invalido')
lcds = ()
linha = ((pos-1)//3)+1
lcds += (obter_... | [
"def marcar_linha(vect, j, pos):\n # marcar_linha: tuplo x inteiro x posicao -> tuplo\n\n new_linha = ()\n for n in range(3):\n if n == (pos-1)%3:\n new_linha += (j,)\n else:\n new_linha += (vect[n], )\n\n return new_linha",
"def s_minus_cells(self):\n k = se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Devolve um tabuleiro com a marca do jogador na posicao dada. | def marcar_posicao(tab, j, pos):
# marcar_posicao: tabuleiro x inteiro x posicao -> tabuleiro
if not (
eh_tabuleiro(tab) and
type(j) == int and j in (-1, 1) and
eh_posicao(pos) and eh_posicao_livre(tab,pos)
):
raise ValueError('marcar_posicao: algum dos argumentos e invalido... | [
"def deshacer_jugada(self, jugada):\n self.tablero[jugada[0]][jugada[1]] = 0",
"def llenarTablero(self):\n y=0 \n for miniterminos in self.renglonesHoja:\n for mini in miniterminos.miniterminosSimpli:\n x=self.indices[mini]\n self.columnas[y][x]=1\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Devolve um tuplo representante de uma linha com a marca do jogador na posicao dada. | def marcar_linha(vect, j, pos):
# marcar_linha: tuplo x inteiro x posicao -> tuplo
new_linha = ()
for n in range(3):
if n == (pos-1)%3:
new_linha += (j,)
else:
new_linha += (vect[n], )
return new_linha | [
"def marcar_posicao(tab, j, pos):\n # marcar_posicao: tabuleiro x inteiro x posicao -> tabuleiro\n\n if not (\n eh_tabuleiro(tab) and\n type(j) == int and j in (-1, 1) and\n eh_posicao(pos) and eh_posicao_livre(tab,pos)\n ):\n raise ValueError('marcar_posicao: algum dos argument... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Esta funcao realiza a leitura de uma posicao introduzida manualmente por um jogador e devolve esta posicao escolhida. | def escolher_posicao_manual(tab):
# escolher_posicao_manual: tabuleiro -> posicao
if not eh_tabuleiro(tab):
raise ValueError('escolher_posicao_manual: o argumento e invalido')
pos = int(input('Turno do jogador. Escolha uma posicao livre: '))
if not (eh_posicao(pos) and eh_posicao_livre(tab, p... | [
"def crear_todo_el_mapa(self):\n for i in range(0,self.cantidad_de_paredes_no_rompibles): # Defino paredes no rompibles\n self.pos_de_paredes_no_rompibles_en_x += self.distancia_entre_paredes_no_rompibles * (i != 0)\n for g in range(0,self.cantidad_de_paredes_no_rompibles):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Se o jogador tiver uma posicao de bifurcacao devolve essa posicao. | def bifurcacao(tab, j):
# bifurcacao: tabuleiro x inteiro -> posicao
for pos in obter_posicoes_livres(tab):
if eh_intersecao(tab, pos, j):
return pos
return None | [
"def bloqueio_bifurcacoes(intersecoes, tab, j):\n # bloqueio_bifurcacoes: tuplo x tabuleiro x inteiro -> posicao\n\n posicoes_livres = obter_posicoes_livres(tab)\n\n possibilidades = ()\n for pos in posicoes_livres:\n if pos not in intersecoes:\n\n # Forca o oponente a jogar numa posic... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verifica se a posicao se encontra em duas ou mais linhas, colunas ou diagonais com pecas do jogador. | def eh_intersecao(tab,pos,j):
# eh_intersecao: tabuleiro x posicao x inteiro -> booleano
total = 0
for lcd in obter_linhas_colunas_diagonais(tab, pos):
if lcd.count(0) == 2:
total += lcd.count(j)
return total >= 2 | [
"def testaInterseccao(self, linha:Linha) -> bool:\n return Interseccao.valida(self.p1, self.p2, linha.p1, linha.p2) or \\\n Interseccao.valida(self.p2, self.p3, linha.p1, linha.p2) or \\\n Interseccao.valida(self.p3, self.p4, linha.p1, linha.p2) or \\\n Interseccao.valida(sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Devolve a posicao que impede a criacao de uma bifurcacao quando existem mais do que uma posicao que a crie. | def bloqueio_bifurcacoes(intersecoes, tab, j):
# bloqueio_bifurcacoes: tuplo x tabuleiro x inteiro -> posicao
posicoes_livres = obter_posicoes_livres(tab)
possibilidades = ()
for pos in posicoes_livres:
if pos not in intersecoes:
# Forca o oponente a jogar numa posicao que nao sej... | [
"def crear_bomba(self):\n if len(self.bombas) != self.cant_bombas and self.existe_bomba == False:\n self.existe_bomba = True \n self.posicion_de_nueva_bomba = self.bomberman.set_id_casilla()\n self.bombas.append(bomba.Bomba(self.posicion_de_nueva_bomba,self))",
"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Devolve o primeiro canto que e uma posicao livre caso exista. | def canto_vazio(tab, _):
# canto_vazio: tabuleiro -> posicao
for pos in (1,3,7,9):
if eh_posicao_livre(tab, pos):
return pos
return None | [
"def continente_pais ( self , pais ) :\n\n for i1iIIIiI1I in self . continentes :\n if 70 - 70: Oo0Ooo % Oo0Ooo . IiII % OoO0O00 * o0oOOo0O0Ooo % oO0o\n if pais in self.continentes[i1iIIIiI1I] :\n return i1iIIIiI1I\n if 23 - 23: i11iIiiIii + I1IiiI",
"def minCostToMoveChips(self, position: List[int]) -... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Devolve a primeira lateral que e uma posicao livre caso exista. | def lateral_vazio(tab, _):
# lateral_vazio: tabuleiro -> posicao
for pos in (2,4,6,8):
if eh_posicao_livre(tab, pos):
return pos
return None | [
"def _swap_on_miss(partition_result):\n before, item, after = partition_result\n return (before, item, after) if item else (after, item, before)",
"def remove_from_front(self):\n if len(self.orders) > 0:\n return self.orders.pop(0)\n else:\n return None",
"def get_next_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Esta funcao corresponde a funcao principal que permite jogar um jogo completo de Jogo do Galo de uma jogador contra o computador. | def jogo_do_galo(j, strat):
# jogo_do_galo: cad. caracteres x cad. caracteres -> cad. caracteres
if not (j in ('X','O') and strat in ('basico','normal','perfeito')):
raise ValueError('jogo_do_galo: algum dos argumentos e invalido')
print('Bem-vindo ao JOGO DO GALO.')
print('O jogador joga com ... | [
"def juiz(jogador1, jogador2):\r\n\treturn 'Casa'",
"def joke():\n return",
"def ganador(cubo, turno_player):\n cubo_ganador = (1, 1, 1)\n if cubo == cubo_ganador:\n return turno_player #Si hemos llegado a 1,1,1 devolvemos el turno del ganador\n else:\n return -1 # Si no -1",
"def ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a temporary request token that can be used to validate a TMDb user login. | def _create_request_token(self):
response = self._request_obj(self._urls["create_request_token"])
self.expires_at = response.expires_at
return response.request_token | [
"def get_jwt_token():\n return make_jwt(user=frappe.session.user)",
"def generate_token(request: HttpRequest):\n if request.method == \"POST\":\n user = user_helper.get_user(request)\n # Get user token\n try:\n token = Token.objects.get(\n user=user\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
You can use this method to create a fully valid session ID once a user has validated the request token. | def _create_session(self):
response = self._request_obj(
self._urls["create_session"],
method="POST",
json={"request_token": self.request_token}
)
self.session_id = response.session_id | [
"def generate_session_id() -> str:\n return generate_unique_id()",
"def _new_session_id(self):\n return os.urandom(32).encode('hex')",
"def generate_session_id():\n return str(secrets.randbits(32))",
"def create_session(self, user_id: str = None) -> str:\n if user_id is None:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This method allows an application to validate a request token by entering a username and password. | def _authorise_request_token_with_login(self):
self._request_obj(
self._urls["validate_with_login"],
method="POST",
json={
"username": self.username,
"password": self.password,
"request_token": self.request_token,
}
... | [
"def check_authorization(self):\n self.token",
"def test_get_token_with_valid_username_and_password(self):\n token_result = self.client.post('/api/v1/users/get-token/', data={\n 'username': self.lennon.username,\n 'password': self.john_password,\n })\n\n self.asse... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If you would like to delete (or "logout") from a session, call this method with a valid session ID. | def delete_session(self):
if self.has_session:
self._request_obj(
self._urls["delete_session"],
method="DELETE",
json={"session_id": self.session_id}
)
self.session_id = "" | [
"def delete_session(request):\n session_id = request.POST.getlist('del_sid')[0]\n destroy_session_obj = Pipeline()\n destroy_session_obj.destroy_session(int(session_id))\n return redirect(reverse('webui:dashboard'))",
"def logout_session():\n del session[CURR_USER]",
"def remove(self, session):\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the children nodes of this one | def set_children(self, children) :
self.__children = children | [
"def set_children(self, children: List[DOMElement]) -> 'DOMLayout':\n for element in self._children:\n element.remove_global_observer(self._on_child_event)\n for i, element in enumerate(children):\n element._set_parent(self, i)\n element.add_global_observer(self._on_ch... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the content of a node. The content must be a dict | def set_content(self,content) :
if isinstance(content,dict) :
self.__content = content
else :
raise Exception("SNode2.set_content must receive a dict") | [
"def setContent(self, data):\n self._content = data",
"def setContent(self, content: 'ScXMLContentElt') -> \"void\":\n return _coin.ScXMLInvokeElt_setContent(self, content)",
"def setContent(self, content):\n # later will add content modified check here\n self.text.ChangeValue(conten... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the root node of the tree | def set_root(self,node) :
if not node is None:
node.parent = None
self.__root = node | [
"def setRootNode(self, root: 'SoNode') -> \"void\":\n return _coin.SoProtoInstance_setRootNode(self, root)",
"def _setRoot(self, newRoot: HuffNode) -> None:\n if not isinstance(newRoot, HuffNode):\n raise TypeError('not an instance of HuffNode')\n\n self._root = newRoot",
"def se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check whether a node is the root node Returns | def is_root(self,node) :
if node.parent is None:
return True
else :
return False | [
"def is_root(self):\n return self.node_type() == 0",
"def is_root(self) -> bool:\n return self._is_root",
"def is_root(self,p):\n return (self.root() == p)",
"def is_leaf(self,node) :\n if len(node.children) == 0 :\n return True\n else :\n return False... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check whether a node is a leaf node, i.e., a node without children Returns | def is_leaf(self,node) :
if len(node.children) == 0 :
return True
else :
return False | [
"def is_leaf(vertex):\n return list(LinkedBST.children(vertex)) == []",
"def isLeaf(self, *args) -> \"SbBool\":\n return _coin.SoNodekitCatalog_isLeaf(self, *args)",
"def isLeaf(self):\n raise NotImplementedError",
"def is_leaf(self,p):\n return (self.num_children(p) == 0)",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add a node to the tree under a specific parent node | def add_node_with_parent(self,node,parent) :
node.parent = parent
if not parent is None:
parent.add_child(node) | [
"def addParent(self, node):\n self.parent = node",
"def add_to_tree(self, node):\n # print(node.state)\n # if(node.parent_node is not None):\n # print(\"parent:\", node.parent_node.state)\n # print()\n self.tree.append(node)\n return",
"def insert_node(cls, parent_id):\n try:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove a node from the tree | def remove_node(self,node) :
node.parent.remove_child(node)
self._deep_remove(node) | [
"def remove_node(self, node):\n self.children.remove(node)\n node.parent = None",
"def remove_node(self, node):\n self.nodes.remove(node)\n if len(self.nodes) == 0:\n self.nodes = None",
"def _remove_tree_node(data, path):\n if not path or not data:\n return\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Obtain a list of all nodes int the tree Returns | def get_nodes(self) :
n = []
self._gather_nodes(self.root,n)
return n | [
"def get_all_node(self) -> list:\n if self.is_empty():\n return [self]\n elif self.is_leaf():\n return [self]\n else:\n temp = [self]\n for subtree in self.subtrees:\n temp += subtree.get_all_node()\n return temp",
"def get... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a node with a specific name in a the subtree rooted at fake_root. The name is always an integer | def get_node_in_subtree(self,index,fake_root) :
return self._find_node(fake_root,index) | [
"def findNodeFromName(self, name):\n path = name.split('|')\n for root in self.roots:\n if root.name==path[0]:\n newName = name[len(path[0])+1:]\n if len(newName):\n n = root.findChildByName(root, newName)\n if n: return n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sweet breadthfirst/stack iteration to replace the recursive call. Traverses the tree until it finds the node you are looking for. | def _find_node(self,node,index) :
stack = [];
stack.append(node)
while(len(stack) != 0) :
for child in stack :
if child.index == index :
return child
else :
stack.remove(child)
for cchild in... | [
"def _find_node(self,node,index) :\n stack = []; \n stack.append(node)\n while(len(stack) != 0) :\n for child in stack :\n if child.get_index() == index :\n return child\n else :\n stack.remove(child)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the degree of a given node. The degree is defined as the number of leaf nodes in the subtree rooted at this node. | def degree_of_node(self,node) :
sub_tree = self.get_sub_tree(node)
st_nodes = sub_tree.get_nodes()
leafs = 0
for n in st_nodes :
if sub_tree.is_leaf(n) :
leafs = leafs +1
return leafs | [
"def degree_out(self, node: Node) -> int:\n return len(self.edges_from(node))",
"def getDegree(self, node):\n return self.degree[node]",
"def degree(self):\n return self.defining_polynomial().degree()",
"def degree(self,u):\n return len(self.get_node(u))",
"def get_level(self, node... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the order of a given node. The order or centrifugal order is defined as 0 for the root and increased with any bifurcation. Hence, a node with 2 branch points on the shortest path between that node and the root has order 2. | def order_of_node(self,node) :
ptr = self.path_to_root(node)
order = 0
for n in ptr :
if len(n.children) > 1 :
order = order+1
# order is on [0,max_order] thus subtract 1 from this calculation
return order-1 | [
"def get_bond_order(self, atom):\n order = 0.\n for a1, a2, info in self._graph_edges(data=True, node=atom):\n order += info['bond'].get_order()\n return order",
"def get_ordering(dag):\n g = nx.DiGraph(dag)\n order = list(nx.topological_sort(g))\n return order",
"def ge... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find the path between two nodes. The from_node needs to be of higher \ order than the to_node. In case there is no path between the nodes, \ the path from the from_node to the soma is given. | def path_between_nodes(self,from_node,to_node) :
n = []
self._go_up_from_until(from_node,to_node,n)
return n | [
"def find_spanning_tree_path(self, from_node, to_node):\r\n # Follow the tree's links back from to_node to from_node.\r\n path_nodes = []\r\n path_links = []\r\n current_node = to_node\r\n while current_node != from_node:\r\n # Add this node to the path.\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |