query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Deploy the stack using CloudFormation
def deploy_stack(session, secrets): with open('scripts/cf_stack.yml') as template: template_data = template.read() try: cloudformation = session.client('cloudformation') stack = cloudformation.update_stack( StackName=STACK_NAME, TemplateBody=te...
[ "def deploy(cloud_formation_script, stack_name, cf_resource):\n with open(cloud_formation_script) as setup_file:\n setup_template = setup_file.read()\n print(f\"Creating {stack_name}.\")\n stack = cf_resource.create_stack(\n StackName=stack_name,\n TemplateBody=setup_template,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get_artifacts retrieves a list of artifacts from the selected date range that are listed in artifact_names
def get_artifacts(token, artifact_names, start, end): artifacts = [] page = 1 retry_limit = 3 while True: req = Request(URL + f"&page={page}") req.add_header("Accept", "application/vnd.github.v3+json") req.add_header("Authorization", f"token {token}") with urlopen(req) a...
[ "async def artifacts_get(self) -> List[Artifact]:\n return await self.get(f\"/artifacts\")", "def test_get_artifact_list(self):\n pass", "async def generate_artifacts(self):\n artifacts = []\n while True:\n (artifact, status) = await self._queue.get()\n if statu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
run_curl downloads an artifact file It returns True if the response was a 200 If there was an exception is returns False and the error, as well as printing it to stderr
def run_curl(token, url, filename): with open(filename, "wb") as f: c = pycurl.Curl() headers = [ "Accept: application/vnd.github.v3+json", f"Authorization: token {token}", ] options = { pycurl.FOLLOWLOCATION: 1, pycurl.MAXREDIRS: ...
[ "def download(FILE,URL):\n CMD = ['curl','-o',FILE,URL]\n call(CMD)", "def download_artifacts(artifacts, artifact_name, download_loc):\n for artifact in artifacts:\n if os.path.basename(artifact[\"path\"]) == artifact_name:\n proc = subprocess.Popen([\"wget\", \"-P\", download_loc, artifact[\"url\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
download_artifacts downloads the artifacts as uniquely named files If there is a problem downloading an artifact it is skipped and not added to the returned list. It returns a list of tuples containing the artifact name, the artifact name with the updated date appended (eg. logsrhel820220401), and the filename of the z...
def download_artifacts(token, artifacts): zipfiles = [] for a in artifacts: updated_at = datetime.fromisoformat(a["updated_at"][:-1]) datename = a["name"]+updated_at.strftime("-%Y-%m-%d") filename = datename + ".zip" if os.path.exists(filename): zipfiles.append((a["na...
[ "def download_artifacts(artifacts, artifact_name, download_loc):\n for artifact in artifacts:\n if os.path.basename(artifact[\"path\"]) == artifact_name:\n proc = subprocess.Popen([\"wget\", \"-P\", download_loc, artifact[\"url\"]])\n stdout, stderr = proc.communicate()\n if stdout is not None:\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
extract_logs unzips the archive into a temporary directory This directory is deleted when the object goes out of scope
def extract_logs(f): tdir = tempfile.TemporaryDirectory(prefix="kstest-log-", dir="/var/tmp/") with zipfile.ZipFile(f) as zf: zf.extractall(tdir.name) # Return the object so that the temporary directory isn't deleted yet return tdir
[ "def archive_logs():\n logging.info('Archive start...')\n\n for log_dir in filter(dir_filter, os.listdir('logs')):\n path = 'logs/{}'.format(log_dir)\n archive_files = filter(lambda x: '.log.' in x, os.listdir(path))\n zip_file_name = '{}/{}.zip'.format(\n path,\n st...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build kstestlist if it is missing This is a list of the expected tests, and it is used to help detect when tests are totally missing from the results.
def generate_test_list(tdir): # Skip this if it already exists if os.path.exists(os.path.join(tdir.name, "kstest-list")): return kstest_log = os.path.join(tdir.name, "kstest.log") with open(kstest_log) as f: for line in f.readlines(): if not line.startswith("Running tests: ...
[ "def _build_tests_list_helper(self, suite):\n tests = list(iterate_tests(suite))\n return tests", "def missing_tests(session):\n print('The following samples do not have tests:')\n for sample in set(ALL_SAMPLE_DIRECTORIES) - set(ALL_TESTED_SAMPLES):\n print('* {}'.format(sample))", "d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
rebuild_logs recreates kstest.log with timestamps It does this by appending all the individual kstest.log files, which do contain timestamps, into a new kstest.log
def rebuild_logs(tdir): # Remove the old log with no timestamps kstest_log = os.path.join(tdir.name, "kstest.log") os.unlink(kstest_log) # Find all the test's kstest.log files and append them to kstest.log with open(kstest_log, "w") as ksf: for log in glob(os.path.join(tdir.name, "*", "kste...
[ "def archive_test_logs(days, archive_path, all_logs):\n for day in days.keys():\n daydir = datetime.strptime(day, \"%Y%m%d\").strftime(\"%m-%d-%Y\")\n for scenario in days[day].keys():\n # temporary log directories are stored by scenario + date\n datename = scenario + \"-\" + ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check the tests for success, failing, missing, or flakes success after first failing
def check_tests(tests): success = [] missing = [] failed = {} flakes = {} # The goal is to sort the tests into good/failed and record the ones # that passed after first failing in flakes for t in tests: name = t["name"] if t["success"]: # Tests should never have ...
[ "def test_case_01(self):\n if True:\n self.fail()", "def _check(self):\n if self.action_on_failure not in self.ACTION_ON_FAILURE:\n raise type_utils.TestListError(\n 'action_on_failure must be one of \"NEXT\", \"PARENT\", \"STOP\"')\n\n if self.parallel:\n if not self.su...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the directory of the logs for the test The logfile path should start with /var/tmp/kstest but this finds the kstest no matter what the leading path elements are.
def kstest_logdir(tmpdir, test): logfile = test["logfile"] for e in logfile.split(os.path.sep): if e.startswith("kstest-"): return os.path.join(tmpdir, e) raise RuntimeError(f"No kstest-* directory found in {logfile}")
[ "def get_log_dir():\n base_dir = os.path.realpath(cfg.CONF.ruiner.log_dir.rstrip('/'))\n return os.path.join(base_dir, test_start_time_tag())", "def find_logs():\n dirname = os.path.normpath('./logs')\n d = 1\n\n while d < 5:\n if os.path.exists(dirname):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Store the logs from the failed/flaky tests for archiving
def archive_test_logs(days, archive_path, all_logs): for day in days.keys(): daydir = datetime.strptime(day, "%Y%m%d").strftime("%m-%d-%Y") for scenario in days[day].keys(): # temporary log directories are stored by scenario + date datename = scenario + "-" + datetime.strptim...
[ "def test_logs(self):\n # Purge all logs\n log_dir = self.test_config['LOG_DIR']\n pattern = re.compile('^nginx-access-ui.log-(?P<day_of_log>\\d{8})(\\.gz)?$')\n logs = [f for f in os.listdir(log_dir) if re.search(pattern, f)]\n map(os.remove, logs)\n\n # Try to make report...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Process the logfiles into a data structure
def process_logs(logs): all_data = {} for log in logs: with open(log) as f: data = json.load(f) scenario = data[0].get("scenario", None) if scenario is None: # No scenario name, no way to organize the data continue # Use th...
[ "def process_logfile(self):\n with open(self.log_file, 'r') as f:\n for line in f:\n if line.strip() != '':\n data = [x.strip() for x in line.split(':')]\n self.log_data.update({ data[0] : data[1] })", "def parse(self):\n with open(self.log, 'r', errors='ignore') as f:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the weekly summary on a single directory Instead of pulling artifacts from github use a single directory with kstest.log.json and the log directories.
def test_summary(args, path): log = os.path.join(path, "kstest.log.json") with open(log) as f: data = json.load(f) scenario = data[0].get("scenario", None) if not scenario: raise RuntimeError("No scenario found in %s" % log) # The json log filename needs to be in the form of <sc...
[ "def archive_test_logs(days, archive_path, all_logs):\n for day in days.keys():\n daydir = datetime.strptime(day, \"%Y%m%d\").strftime(\"%m-%d-%Y\")\n for scenario in days[day].keys():\n # temporary log directories are stored by scenario + date\n datename = scenario + \"-\" + ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gather inputs, requires mvip, user, password, called in connect_cluster
def get_inputs(): parser = argparse.ArgumentParser() parser.add_argument('-m', type=str, required=True, metavar='mvip', help='MVIP name or IP') parser.add_argument('-u', type=str, required=True, ...
[ "def __init__(self, user, password, contentType):\n ip_list = []\n user_list = []\n pass_list = []\n\n print('Netscaler IP and credentials ready!')", "def GetCreds():\n\n _username = input(\"Router username: \")\n _password = getpass(\"Password for {}: \".format(_username))\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gather the networking information for virtual networks Looks at the subnet and determines the block size for use in find_block
def find_net_info(sfe): print("-" * 20 + " find_net_info started") virt_net = sfe.list_virtual_networks() json_virt_net = virt_net.to_json() #pprint(json_virt_net) virt_mask = json_virt_net['virtualNetworks'][0]['netmask'] svip = json_virt_net['virtualNetworks'][0]['svip'] # Break the netma...
[ "def _get_network_subnets(self):\n LOG.info(\"Extracting network subnets\")\n network_subnets = {}\n for net_type in self.data['network']['vlan_network_data']:\n # One of the type is ingress and we don't want that here\n if (net_type != 'ingress'):\n network...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returnError Helper function to format & return error messages & codes
def returnError(msg, errcode): logger.warning("[FLASKWEB] Returning error code %d, `%s`" % (errcode, msg)) if request.headers['Accept'] == 'application/json': return msg, errcode else: return render_template("error.html", message=msg, code=errcode)
[ "def get_error(self, code):\n\t\tif code == 200:\n\t\t\treturn \"200 | Success\"\n\t\tif code == 204:\n\t\t\treturn \"204 | No Content\"\n\t\tif code == 400:\n\t\t\treturn \"400 | Bad Request\"\n\t\tif code == 401:\n\t\t\treturn \"401 | Unauthorized\"\n\t\tif code == 402:\n\t\t\treturn \"402 | Payment required.\"\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
/trace Debugging response. Returns the client's HTTP request data in json
def trace(): logger.debug('[FLASKWEB /trace] Trace debug request') output = {} output['args'] = request.args output['form'] = request.form output['method'] = request.method output['url'] = request.url output['client_ip'] = request.remote_addr output['headers'] = {k: str(v) for k,v in request.headers.i...
[ "def debug_print(self, response):\n \n print('REQUEST:')\n method = response.request.method\n url = response.request.url\n body = json.dumps(json.loads(response.request.body), indent=4)\n print('{method} {url}'.format(method, url))\n print(body)\n\n print('RES...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Redirect to uploadApp (/apps)
def uploadAppRedir(): logger.debug('[FLASKWEB /app] Redirect to /apps') return uploadApp()
[ "def uploadApp():\n if request.method == 'POST':\n logger.debug(\"[FLASKWEB /apps] POST request to upload new application\")\n file = request.files['file']\n if file:\n name = secure_filename(file.filename)\n path = os.path.join(webapp.config['UPLOADED_APPS_DEST'], name)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
/apps, /app Application Level interface POST Upload new application
def uploadApp(): if request.method == 'POST': logger.debug("[FLASKWEB /apps] POST request to upload new application") file = request.files['file'] if file: name = secure_filename(file.filename) path = os.path.join(webapp.config['UPLOADED_APPS_DEST'], name) if not os.pa...
[ "def uploadAppRedir():\n logger.debug('[FLASKWEB /app] Redirect to /apps')\n return uploadApp()", "def post(self, request, app_id):\n context = self.get_context_data(app_id)\n app = context.pop('application', None)\n\n if (app is not None):\n data = request.POST\n app...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
/apps/ Specific Application Level interface GET Display all versions for given application
def getApp(appName): logger.debug('[FLASKWEB /apps/<appName>] GET request for app, `%s`' % appName) applist = [a['name'] for a in db.getAllApps()] if appName in applist: versionList = db.getVersions(appName) if request.headers['Accept'] == 'application/json': return jsonify(dict(name=appName, versi...
[ "def versions(app):\r\n print '\\n'.join(_versions(app))", "def cli_list(ctx):\n try:\n r = api.apps_get()\n pprint(r)\n except ApiException as e:\n print(\"Exception when calling AppsApi->apps_get: %s\\n\", e)", "def _get_apps(self):\n return self.api.get('/v2/apps')", "def ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
/apps// Specific Application Level interface POST (Upload archive data (C++, Source, etc....)
def archiveApp(appName, appUID): logger.debug('[FLASKWEB /app/<appName>/<appUID>] %s Request for App Archive `%s`, UID=`%s`' % (request.method, appName, appUID)) applist = [a['name'] for a in db.getAllApps()] uname = AppID.getAppId(appName, appUID) # if appName not in applist: # logger.warning("Archive re...
[ "def upload():\n storeapps = APP.config[\"storage\"]\n binary = request.data\n\n # Add compatibility with POST requests\n if 'file' in request.files:\n binary = request.files['file'].read()\n\n logging.debug(\"Received file with size: %i\", len(binary))\n\n try:\n app = nativeapps.ap...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
/delete/app/ POST Deletes an app from the web server
def deleteApp(appName): logger.debug('[FLASKWEB /delete/app/<appName>] Request to delete App `%s`', appName) applist = [a['name'] for a in db.getAllApps()] if appName not in applist: return returnError("Application %s does not exist" % appName, 404) logger.info("[FLASKWEB] DELETING all versions of app, `...
[ "def test_05d_get_nonexistant_app_delete(self):\r\n self.register()\r\n # GET\r\n res = self.app.get('/app/noapp/delete', follow_redirects=True)\r\n assert res.status == '404 NOT FOUND', res.data\r\n # POST\r\n res = self.delete_application(short_name=\"noapp\")\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Redirect createJob using the latest uploaded application version
def createJobLatest(appName): logger.debug('[FLASKWEB /jobs/<appName>] Redirect to current version of /jobs/%s' % appName) app = db.getApp(appName) if app: return createJob(appName, app['uid']) else: return returnError("Application %s does not exist" % appName, 404)
[ "def redirect_version():\n return redirect(url_for(\"base_blueprint.version\"), code=301)", "def replayJob(appName, jobId):\n global dispatcher\n joblist = db.getJobs(jobId=jobId)\n oldjob = None if len(joblist) == 0 else joblist[0]\n if oldjob:\n logger.info(\"[FLASKWEB] REPLAYING %s\" % jobId),\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
/jobs/ /jobs//<appUID Launch a new K3 Job POST Create new K3 Job
def createJob(appName, appUID): logger.debug('[FLASKWEB /jobs/<appName>/<appUID>] Job Request for %s' % appName) global dispatcher applist = [a['name'] for a in db.getAllApps()] if appName in applist: if request.method == 'POST': logger.debug("POST Request for a new job") # TODO: Get user ...
[ "def create_job():\n data = request.json\n job = {\n \"repository_url\": data.pop(\"repo_url\", None),\n \"commit_hash\": data.pop(\"commit_hash\", None),\n \"branch\": data.pop(\"branch\", None),\n \"keep_data\": data.pop(\"keep_data\", False),\n \"attributes\": data\n }...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
/jobs//<appUID/replay Replay a previous K3 Job POST Create new K3 Job
def replayJob(appName, jobId): global dispatcher joblist = db.getJobs(jobId=jobId) oldjob = None if len(joblist) == 0 else joblist[0] if oldjob: logger.info("[FLASKWEB] REPLAYING %s" % jobId), # Post new job request, get job ID & submit time thisjob = dict(appName=oldjob['appName'], ...
[ "def createJob(appName, appUID):\n logger.debug('[FLASKWEB /jobs/<appName>/<appUID>] Job Request for %s' % appName)\n global dispatcher\n applist = [a['name'] for a in db.getAllApps()]\n if appName in applist:\n if request.method == 'POST':\n logger.debug(\"POST Request for a new job\")\n # TO...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
/jobs///archive Endpoint to receive & archive files GET returns curl command POST Accept files for archiving here
def archiveJob(appName, jobId): job_id = str(jobId).encode('utf8', 'ignore') if job_id.find('.') > 0: job_id = job_id.split('.')[0] jobs = db.getJobs(jobId=job_id) job = None if len(jobs) == 0 else jobs[0] if job == None: return returnError ("Job ID, %s, does not exist" % job_id, 404) ...
[ "async def archive(request):\n guid = request.match_info[\"guid\"]\n future = pigeon_jobs.submit(pigeon.run, pigeon.archive(guid))\n future.add_done_callback(handle_exception)\n future.add_done_callback(archive_task_done)\n return web.json_response({guid: future._state})", "def get_archives(name, b...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
/delete/jobs POST Deletes list of K3 jobs
def deleteJobs(): deleteList = request.form.getlist("delete_job") for jobId in deleteList: job = db.getJobs(jobId=jobId)[0] path = os.path.join(webapp.config['UPLOADED_JOBS_DEST'], job['appName'], jobId) shutil.rmtree(path, ignore_errors=True) db.deleteJob(jobId) return redirect(url_for('listJobs'...
[ "def delete(job_id):\n\t_jobs.delete(jobs.get_or_404(job_id))\n\treturn None, 204", "def deleteJobs(self):\n\t\tfor item in self.ui.jobs_listWidget.selectedItems():\n\t\t\tself.j.deleteJob(item.text())\n\t\t\tself.ui.jobs_listWidget.takeItem(self.ui.jobs_listWidget.row(item))", "def rm(job_ids: List[int], tags:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
/compileservice/up POST Starts compile service
def compServiceUp(): global compileService if request.method == 'POST' and compileService.isDown(): settings = dict(webaddr=webapp.config['ADDR']) settings['branch'] = request.form.get('branch', 'development') gitpull = request.form.get('gitpull', True) settings['gitpull'] = gitpull if isinstance(g...
[ "def compServiceDown():\n global compileService\n compileService.goDownGracefully()\n\n if request.headers['Accept'] == 'application/json':\n return jsonify(compileService.getItems()), 200\n else:\n return render_template(\"compile.html\", status=compileService.state.name, hostlist=compileService.getAllNo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
/compileservice/stop GET Stop compile service Immediately
def compServiceStop(): global compileService compileService.goDown() if request.headers['Accept'] == 'application/json': return jsonify(compileService.getItems()), 200 else: return render_template("compile.html", status=compileService.state.name, hostlist=compileService.getAllNodes())
[ "def iscsi_service_stop(self):\n return self.request( \"iscsi-service-stop\", {\n }, {\n } )", "def nmt_service_stop(self):\n self._node.nmt.send_command(0x2)", "def net_service_stop(self):\n\t\treturn Job(SDK.PrlSrv_NetServiceStop(self.handle)[0])", "def pcap_service_stop(askadmin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
/compileservice/down GET Shuts down compile service gracefully
def compServiceDown(): global compileService compileService.goDownGracefully() if request.headers['Accept'] == 'application/json': return jsonify(compileService.getItems()), 200 else: return render_template("compile.html", status=compileService.state.name, hostlist=compileService.getAllNodes())
[ "def compServiceStop():\n global compileService\n compileService.goDown()\n\n if request.headers['Accept'] == 'application/json':\n return jsonify(compileService.getItems()), 200\n else:\n return render_template(\"compile.html\", status=compileService.state.name, hostlist=compileService.getAllNodes())", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves the compiler output from local file
def getCompilerOutput(uname): fname = os.path.join(webapp.config['UPLOADED_BUILD_DEST'], uname, 'output').encode('utf8') if os.path.exists(fname): stdout_file = open(fname, 'r') output = unicode(stdout_file.read(), 'utf-8') stdout_file.close() return output else: return returnE...
[ "def compile_file(in_path: pathlib.Path) -> dict[str, Any]:\n file = ContentFile(in_path)\n file.read_input()\n compile(file)\n file.write_output()\n return file.options", "def compile(c_file: File) -> File:\n os.system(\"gcc -c {c_file}\".format(c_file=c_file.path))\n return File(c_file.path...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
/compilestatus Short list of active jobs & current statuses
def getCompileStatus(): logger.debug("[FLASKWEB] Retrieving current active compilation status") jobs = compileService.getActiveState() title = "Active Compiling Tasks" if jobs else "NO Active Compiling Jobs" if request.headers['Accept'] == 'application/json': return jsonify(jobs), 200 else: return r...
[ "def do_status(self, args):\n status = self._leet.job_status\n\n for job in self.finished_jobs:\n status.append({\"id\" : job.id,\n \"hostname\" : job.machine.hostname,\n \"plugin\": job.plugin_instance.LEET_PG_NAME,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
/compilelog Connects User to compile log websocket
def getCompileLog(): if webapp.config['COMPILE_OFF']: return returnError("Compilation Features are not available", 400) logger.debug("[FLASKWEB] Connecting user to Compile Log WebSocket") with open(webapp.config['COMPILELOG'], 'r') as logfile: output = logfile.read().split('<<<<< Compiler Service Initia...
[ "def logtool(ctx):", "def pulllog():\n\tpass", "def compile_log(mesg):\n if 'kivy.logging' not in sys.modules.keys():\n logging.debug(mesg)\n else:\n Logger.debug('Compiler: ' + mesg)", "def start_logging(self):\n self.zmqLog = self.context.socket(zmq.PUSH)\n self.zmqLog.conn...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
/compile//kill GET Kills an active compiling tasks (or removes an orphaned one from DB)
def killCompile(uid): if webapp.config['COMPILE_OFF']: return returnError("Compilation Features are not available", 400) complist = db.getCompiles(uid=uid) if len(complist) == 0: complist = db.getCompiles(uid=AppID.getUID(uid)) if len(complist) == 0: return returnError("Not currently tracking the...
[ "def killJobs(self, blTaskName, rng):\n return self._genericCommand('kill', blTaskName, rng)", "def kill(self):\n self.running = False\n\n if self.pool is not None:\n self.pool.close()\n# self.pool.terminate()\n# self.pool.join()\n self.pool = None\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
/delete/compiles POST Deletes list of inactive compile jobs
def deleteCompiles(): if webapp.config['COMPILE_OFF']: return returnError("Compilation Features are not available", 400) deleteList = request.form.getlist("delete_compile") for uid in deleteList: logger.info("[FLASKWEB /delete/compiles] DELETING compile job uid=" + uid) job = db.getCompiles(uid=uid)...
[ "def deleteJobs():\n deleteList = request.form.getlist(\"delete_job\")\n for jobId in deleteList:\n job = db.getJobs(jobId=jobId)[0]\n path = os.path.join(webapp.config['UPLOADED_JOBS_DEST'], job['appName'], jobId)\n shutil.rmtree(path, ignore_errors=True)\n db.deleteJob(jobId)\n return redirect(url_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load the data from the specified json file. When merge=True the data will be added to the current data (used for merging sheets) Duplicates will be overwritten by the last load file
def load_json(self,sample_sheet_location,merge=False): with open(sample_sheet_location) as f: if merge: for k,v in json.load(f).items(): if k not in self.data: self.data[k] = v else: self.data[k]....
[ "def set_data_from_json(self, filename):\n with open(filename, 'r') as f:\n self.data = json.load(f, object_pairs_hook=OrderedDict)", "def load_json(self):\n if os.path.exists(self.json_path):\n data = read_json(self.json_path)\n # everything else\n for ff...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the well to index mapping for the supplied layout
def layout_well2index(self, layout_name): return {k:tuple(v) for k,v in self['well2coord'][self['layout_format'][layout_name]].items()}
[ "def get_index_from_well(self, well):\n pass", "def layout_method_mapper(self):\n return {\n \"kamada_kawai_layout\": kamada_kawai_layout,\n \"fruchterman_reingold_layout\": fruchterman_reingold_layout,\n \"spectral_layout\": spectral_layout,\n }", "def get_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove all libraries with the given mark
def drop_mark(self, mark): if type(mark) is list: for m in mark: self.drop_mark(m) return to_prune = [] for sample, _mark in self['marks'].items(): if mark==_mark: to_prune.append(sample) self.drop_library(to_prune)
[ "def remove_packages(self, packages):", "def remove(self, *packages):\n raise NotImplementedError", "def remove_libraries(self, libs, root, xml_path):\n for lib in libs:\n rm_tree(Path(root) / lib)\n\n process_file(\n xml_path,\n lambda lines: [line for line in ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Merchant Benchmark This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response.
def postmerchant_benchmark_with_http_info(self, merchant_benchmarkpost_payload, **kwargs): all_params = ['merchant_benchmarkpost_payload'] all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_...
[ "def test_merchant_get_1(self):\n admin.set_wallet_amount(balance=bl(0.000012), currency='BTC', merch_lid=user1.merchant1.lid)\n admin.set_wallet_amount(balance=bl(5.55), currency='UAH', merch_lid=user1.merchant1.lid)\n merch = admin.get_model(model='merchant', _filter='lid', value=int(user1.me...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Connects to the Harmony and sets current activity.
def set_current_activity(client, activity_label): id = activities_by_name[activity_label] func = client.start_activity(id) status = run_in_loop_now('start_activity', func) return status
[ "async def set_activity(activity):\n\tkind, name = activity.split(\" \", maxsplit=1)\n\tkinds = {\n\t\t\"playing\" : ActivityType.playing,\n\t\t\"watching\" : ActivityType.watching,\n\t\t\"listening-to\" : ActivityType.listening,\n\t}\n\tawait Me.change_presence(activity=Activity(name=name, type=kinds[kind]))\n\tre...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Take a one input and return True if the passed input is either the number or string 2, False otherwise.
def is_two(x): if x == 2 or (str(x)).lower()== 'two': return True else: return False
[ "def check_two_digits():\n if tokenize_user_input[1].isdigit and tokenize_user_input[2].isdigit:\n return True\n else:\n print(\"Please try with two digits number.\")", "def check_one_digit():\n if tokenize_user_input[1].isdigit:\n return True\n else:\n print(\"Please try w...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return True if the passed string is a consonant, False otherwise. Use you is_vowel function to accomplish this.
def is_consonant(x): if is_vowel(x) == True: return False elif len(x) > 1 or type(x) == int: return False
[ "def is_consonant(string):\n # this is to check the type of the input to make sure it's a string\n if type(string) != str:\n return None\n # if the length is more than 1 char long, will not work\n if len(string) != 1:\n return None\n # use previous function is_vowel to check reverse\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Accept a string that is a number that contains commas in it as input, and return as number as output. 1. if want to check that input is string type, if false print "Please enter a string" return boolean False value 2. else reassign x to a copy with replace method to change commas to underscores. This will allow python ...
def handle_commas(x): if type(x) != str: print ("Please enter a string") return False else: x = float(x.replace(",","")) return x
[ "def handle_commas(string):\n # check to make sure input is a string in order to continue\n if type(string) != str: # <---this check is weak it doesnt check to see if the input has numbers in it\n return None\n # remove any commas and cast input as an int\n return int(string.replace(',', ''))", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Concatenate train set and test set, So our filling data won't overfit on the train set.
def ConcatDF(train_set, test_set): return pd.concat([train_set, test_set], sort=True).reset_index(drop=True)
[ "def concatenateData(self):\n self.data = pd.concat([tr.data for tr in self.getTestRuns()])", "def ConcatDF(train_set, test_set):\n df_all = pd.concat([train_set, test_set], sort=True).reset_index(drop=True)\n df_all.trn_len = train_set.shape[0]\n return df_all", "def setup_data(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets all binary entries for a given Keepass database entry.
def get_binaries(kdb,entry): xml = objectify.fromstring(entry.dump_xml()) binaries = list(xml.xpath('./Binary')) for binary in binaries: yield (binary.Key.text, Binary(kdb,binary))
[ "def get_binaries(name_only=False):\n\n bins = list()\n\n dtf_db = sqlite3.connect(DTF_DB)\n cur = dtf_db.cursor()\n\n # This just returns the name\n if name_only:\n\n sql = ('SELECT name '\n 'FROM binaries ')\n\n for binary in cur.execute(sql):\n bins.append(bi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extracts, decodes and decompresses the binary data for this block. Returns the data as bytes.
def content(self): if self._content is not None: return self._content binaries = self._kdb.kdb.obj_root.Meta.Binaries xpath = './Binary[@ID="{}"]'.format(self.ref) binary = binaries.xpath(xpath)[0] result = b64decode(binary.text) if (binary.attrib['Compresse...
[ "def read_binary(self):\n length = self.read_uint32()\n bytes = self.data[:length]\n self.data = self.data[length:]\n return bytes", "def _decode_binary_block(self, block, dtype):\r\n # The fixed length block is defined by IEEE 488.2 and consists of `#'' (ASCII), one numeric (AS...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves the SSH entry's passphrase (from the Keepass password field) >>> entry = KP_DB.find_entries_by_path('embedded_keys/id_rsa')[0] >>> ssh_entry = SshEntry(KP_DB,entry) >>> ssh_entry.passphrase.decode() == entry.password True
def passphrase(self): password = self.entry.password if password: return self.entry.password.encode('UTF-8') else: return None
[ "def passphrase(self):\n if self._passphrase:\n return self._passphrase\n\n #passphrase must be provided; it can't be calculated.\n raise AttributeError()", "def api_key_passphrase(self):\n password = self.attributes.get(\n \"{}.API Key Passphrase\".format(self._c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parses the KeeAgent settings for the provided entry. >>> entry = KP_DB.find_entries_by_path('embedded_keys/id_rsa')[0] >>> ssh_entry = SshEntry(KP_DB,entry) >>> ssh_entry.settings
def settings(self): if self._settings is not None: return self._settings settings = self.binaries['KeeAgent.settings'].content self._settings = objectify.fromstring(settings) return self._settings
[ "def read_enc_settings():\n print(\"Decrypting {}\".format(ENC_SETTINGS))\n try:\n output = subprocess.check_output(['gpg', '-d', ENC_SETTINGS])\n except subprocess.SubprocessError:\n print(\"Decryption failed, ignoring\")\n return\n config = ConfigParser()\n config.read_string(o...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the serialized variant of the stored private key for this entry. SSH keys can both be stored as attachments or references to keyfiles on disk. This property supports both and will automatically read the data from the right place. Returns the respective private key file as bytes. >>> entry = KP_DB.find_entries_b...
def serialized_private_key(self): if self._serialized_private_key is not None: return self._serialized_private_key location = self.settings.Location if location.AttachmentName: self._serialized_private_key = self.binaries[location.AttachmentName.text].content ...
[ "def get_private_key_in_der(self):\n serialized_private = self.private_key_obj.private_bytes(\n encoding=serialization.Encoding.DER,\n format=serialization.PrivateFormat.TraditionalOpenSSL,\n encryption_algorithm=serialization.NoEncryption()\n )\n return seriali...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the path for the private key file associated with the SSH entry. If the private key file is stored as an attachment in the Keepass database,
def private_key_path(self): if self._private_key_path is not None: return self._private_key_path location = self.settings.Location if location.AttachmentName: self._private_key_path = 'kdbx-attachment:///{}/{}'.format( self.entry.path, location.Attachment...
[ "def _get_path_to_key_file():\n\n if 'private_key_path' not in ctx.node.properties:\n raise NonRecoverableError(\n 'Unable to get key file path, private_key_path not set.')\n\n return os.path.expanduser(ctx.node.properties['private_key_path'])", "def PRIVATE_RSA_KEYFILE_PATH() :\n retur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Attempts to wrap a Keepass entry with the `SshEntry` class. Returns the `SshEntry` instance if successful and `None` otherwise.
def try_parse_ssh_entry(kdb,entry): try: return SshEntry(kdb,entry) except: return None
[ "def get_entry(self, *args, **kwargs):\n return LDAPEntry(self, *args, **kwargs)", "def ensure_entry(self, entry):\n try:\n t = entry['AltSpliceVariant']\n return entry\n except (TypeError, AttributeError, IndexError):\n if isinstance(entry, (int, numpy.number...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Iterates over all entries in a Keepass database and filters out the entries containing KeeAgent settings. >>> get_ssh_entries(KP_DB) [, ...]
def get_ssh_entries(kdb): entries = kdb.entries entries = [try_parse_ssh_entry(kdb,e) for e in entries] entries = [e for e in entries if e] return entries
[ "def get_entries_all(self):\n if self.database is None:\n raise DatabaseNotOpened('No KeePass Database Opened.')\n else:\n return self.database.find_entries_by_title('.*', \n regex=True)", "def GetSSHKeys():\n keydict = {...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Inits message queue by a user choice, zmq (Default) or rabbitmq
def __init__(self, mq_choice="zmq"): self.mq = mq_choice func = getattr(self, "_init_{}".format(self.mq)) func()
[ "def init_mq():\n channel = get_mq().channel()\n\n channel.queue_delete('celery')\n channel.exchange_delete('celery')\n\n channel.exchange_declare(\n exchange='celery',\n exchange_type='direct',\n durable=True)\n request_queue = channel.queue_declare(\n queue='celery',\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update ESGF slcs token.
def generate_esgf_slcs_token(self): client = ESGFSLCSClient(self.request) if client.get_token(): try: client.refresh_token() except Exception as err: self.session.flash('Could not refresh token: {}'.format(escape(err.message)), queue="danger") ...
[ "def _update_token(token):\n session.token = token", "def _update_session_token(self, callback, attempts=0, bypass_lock=False):\r\n if self.provider.security_token == PENDING_SESSION_TOKEN_UPDATE and not bypass_lock:\r\n return\r\n self.provider.security_token = PENDING_SESSION_TOKEN_UPDATE # invali...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Forget ESGF slcs token.
def forget_esgf_slcs_token(self): client = ESGFSLCSClient(self.request) client.delete_token() self.session.flash("ESGF token removed.", queue='info') return HTTPFound(location=self.request.route_path('profile', userid=self.userid, tab='esgf_slcs'))
[ "def clearToken(self):\n\n self.token = ''", "def unlink(self):\n self.token = None", "def revoke_token(token):\n token.delete_instance()", "def refresh_token(self):\n self._token = None\n self._keystone_client = None\n return self.get_token()", "def refresh_token(self)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
print message if package not found in repository
def pkg_not_found_mess(pkgname: str, reponame: str) -> None: meta = MainData() print(('{0}Package {1}{2} {0}not found in \'{3}\' ' 'repository.{4}').format(meta.clrs['red'], meta.clrs['lcyan'], pkgname, ...
[ "def __init__(self, package_name, msg=None):\n if msg is None:\n msg = 'Package: {fp} could not be found.'.format(fp=package_name)\n\n super(PackageNotFoundError, self).__init__(msg)", "def _print_missing(packages, verbose):\n if not packages:\n print(\"## No Rez packages were f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return list of packages in the current directory
def get_packages_in_current_dir() -> list: from os import listdir pkgs = [] ext = ('.tgz', '.txz') for file_in_current_dir in sorted(listdir()): if file_in_current_dir.endswith(ext): pkgs.append(file_in_current_dir) return pkgs
[ "def get_all_packages():\n return search_all_packages()", "def list_packages():\n\n shelf_dir = settings.shelf_dir\n\n package_list = os.listdir(shelf_dir)\n\n package_list.sort()\n\n return package_list", "def get_packages(package):\n return [str(path.parent) for path in Path(package).glob(\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the size of the remote file
def get_remote_file_size(url: str = '', httpresponse: object = False) -> int: need_to_close = False if not httpresponse: httpresponse = url_is_alive(url) if not httpresponse: error_open_mess(url) return 0 need_to_close = True content_length = httpresponse.get...
[ "def get_remote_file_size(url):\n headers = requests.head(url).headers\n return int(headers['content-length'])", "def get_file_size(self, remote_path, connection=None):\n\n if connection:\n size = connection.file(remote_path, \"r\")._get_size()\n else:\n with self.create_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get md5sum of remote or local file
def get_md5_hash(file_path: str) -> str: from hashlib import md5 # local file if file_path.startswith('/'): return md5(open(file_path, 'rb').read()).hexdigest() # remote file httpresponse = url_is_alive(file_path) if not httpresponse: error_open_mess(file_path) return '...
[ "def _get_remote_md5(self):\n E = action_element_maker()\n top = E.top(\n E.FileSystem(\n E.Files(\n E.File(\n E.SrcName(self.src),\n E.Operations(\n E.md5sum()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
check md5sum of two files
def check_md5sum(file1: str, file2: str) -> bool: return get_md5_hash(file1) == get_md5_hash(file2)
[ "def equal_file_sum(file1_paht, file2_paht):\n md5_sum1 = generate_sum(file1_path)\n md5_sum2 = generate_sum(file2_path)\n return (md5_sum1 == md5_sum2)", "def checkMD5(self,orig,new):\n\n errMsg = \"comparing md5sum for \\\"\"+new+\"\\\" against \\\"\"+orig+\"\\\"\"\n logging.debug(errMsg)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper function to extract ground truth communities from LFR Benchmar
def detect_ground_truth_communities(self, G): print("Detecting Ground - Truth communities") gt_communities = {frozenset(G.nodes[v]['community']) for v in G} return [list(fs) for fs in gt_communities]
[ "def get_ground_truth():\n\n true_ps, obs_xs = util.io.load(os.path.join(get_root(), 'observed_data'))\n return true_ps, obs_xs", "def comparePrintUeGnBLogResults(msg_count, ue_field_name_pat_arr, gn_field_name_pat_arr, ue_field_var, gn_field_var, flag_connected_state_found, flag_1st_pdcch_harq_after_rach_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the concentration of the input pollutant at point (x, y).
def concentration(rFile, eFile, x, y, pollutant): sheets = pd.read_excel(eFile, sheet_name = None) if pollutant in ['NO2', 'PM10', 'PM25', 'EC']: c_traffic = traffic_concentration(rFile, sheets, x, y, pollutant) if c_traffic == 'e1': print("The calculation point is more than 60 ...
[ "def __calc_concentration(self, diam, data, dmin, dmax):\n\n dp = np.log10(diam*1e-9)\n conc = data # smoothed\n dmin = np.max((np.log10(dmin),dp[0]))\n dmax = np.min((np.log10(dmax),dp[-1]))\n dpi = np.arange(dmin,dmax,0.001)\n conci = np.sum(interp1d(dp,conc,kind='nearest...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a point p, find the nearest road that p belongs to. Return the road type and the distance from p to this road.
def nearest_road(p, file): with fiona.open(roadFile, 'r') as roads: nearestRoad = roads[0] minDis = p.distance(shape(roads[0]['geometry'])) for road in roads: dis = p.distance(shape(road['geometry'])) if dis < minDis: nearestRoad = road ...
[ "def nearest_point(self, p: Vec) -> Vec:\n # We could just do points in range for the entire tree, but that wouldnt be all that efficient\n # 1. Find the closest point within the leaf\n # 2. Set up a rectangle area round this point based on the distance to the closest within the leaf\n #...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the background concentration value at point (x, y) from the template file.
def background_concentration(sheets, x, y, pollutant): i, j = coor2idx(x, y) # get bc from excel. The year is hard coded to 2015 f = sheets["Backgroundconc"] idx = f[f['XiYI'] == str(i) + "-" + str(j)].index if len(idx) == 0: print("BCError: No location found. 0 returned.") ...
[ "def min_background_concentration(self) -> _VectorisedFloat:\n return self.CO2_atmosphere_concentration", "def GetBackgroundValue(self) -> \"short\":\n return _itkBinaryContourImageFilterPython.itkBinaryContourImageFilterISS3ISS3_GetBackgroundValue(self)", "def GetBackgroundValue(self) -> \"short\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get wind speed at point (x, y) from excel.
def wind_speed(sheets, x, y): i, j = coor2idx(x, y) # get ws from excel. The year is hard coded to 2012 f = sheets["Meteo CAR-VL3.0"] idx = f[f['Search key'] == int(str(i) + str(j) + "2012")].index if len(idx) == 0: print("WSError: No location found.") return 0 ...
[ "def get_wind_speed(self) -> float | None:\n if self.has_anemometer:\n ws = self.query(WeatherCommand.GET_WINDSPEED)\n ws *= 0.84\n # The manual says to add 3 km/h to the reading but that seems off.\n # ws += 3 * u.km / u.hour\n return ws\n else:\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Translate coordinates into indices (as being used in CAR VL3.0). In fact, I dont know in which CRS the coordinates are. I just followed what has been done in excel.
def coor2idx(x, y): a = round(x/4000,0)*4000 b = (round_down(y/4000,0)+0.5)*4000 i = int((a - 24000)/4000) + 1 j = int((b - 22000)/4000) + 1 return i, j
[ "def Indexes(self, latitudes, longitudes):\n res = self._transform.TransformPoints(\n np.column_stack((longitudes, latitudes)))\n res = list(zip(*res))\n x, y = np.array(res[0]), np.array(res[1])\n idx_col = self._inv_txf[0] + self._inv_txf[1] * x + self._inv_txf[2] * y\n idx_row = self._inv_t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Round a number to n decimal places (same as 'rounddown' in excel).
def round_down(n, decimals=0): multiplier = 10 ** decimals return int(n * multiplier) / multiplier
[ "def myround(number, ndigits=None):\n pass", "def round_to(n, precision):\n correction = 0.5 if n >= 0 else -0.5\n return int(n / precision + correction) * precision", "def float_round(num, n):\n num = float(num)\n num = round(num, n)\n return num", "def round_to_n(x, n=8):\n n = 1 + n - ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Small utility returning a record reader that can read gzip'ed files.
def _gzip_reader_fn(): return tf.TFRecordReader( options=tf.python_io.TFRecordOptions( compression_type=tf.python_io.TFRecordCompressionType.GZIP))
[ "def _gzip_reader_fn(filenames):\n return tf.data.TFRecordDataset(\n filenames,\n compression_type='GZIP')", "def _gzip_reader_fn(filenames):\n return tf.data.TFRecordDataset(filenames, compression_type=\"GZIP\")", "def open_gz(filename, mode):\n return gzip.open(filename, mode)", "def _ini...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a modified whirl plot for an arbitrary polygon. Traditionally whirl plots are limited to ngons, to plot for an arbtirary polygon we express the construction of the whirl as subsequent connections between points while solving the miceproblem.
def whirl_plot(polygons, iterations, step, fpath, **kwargs): for polygon in polygons: for _ in range(iterations): # pylint: disable=invalid-name xy = np.vstack([polygon, polygon[0]]) plt.plot(*np.hsplit(xy, 2), **kwargs) diff = polygon - np.roll(polygon, 1, a...
[ "def test_simple_polygonisation(n_points=20):\n # generate random sample points.\n sample_points = np.random.random_sample((n_points,2))*10\n # generate simple polygon\n seq = simple_polygonisation(sample_points)\n # plot polygon\n plt.figure()\n plt.plot(seq[:,0], seq[:,1], color=\"blue\", mar...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Trims white space border of a numpy image.
def _trim_border(img): for i in range(img.shape[0]): if np.any(img[i, :, :] != 255): img = img[i:, :, :] break for i in range(img.shape[0] - 1, 0, -1): if np.any(img[i, :, :] != 255): img = img[: i + 1, :, :] break for i in range(img.shape[1]...
[ "def reduce_whitespace(self, border: int = 5) -> None:\n if self.img is None:\n raise FileExistsError(\"Load an image first with from_url.\")\n\n pix = np.asarray(self.img)\n\n pix = pix[:, :, 0:3] # Drop the alpha channel\n idx = np.where(pix - 255)[0:2] # Drop the color wh...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Route permettant d'afficher la page Bibliographie en retournant une template via l'objet Flask render_template(), où est défini le chemin vers le document html où le retour de la fonction sera affiché.
def bibliographie(): return render_template("pages/bibliographie.html")
[ "def cover_page_route():\n return render_template(\"/cover_page_creation.html\")", "def main_page():\n return render_template(\"main_page.html\")", "def main_page():\n return render_template(\"index.html\")", "def rocketlab_page():\n return render_template('rocketlab.html')", "def process_book()...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Route permettant d'afficher la page de présentation du corpus des actes ducaux en retournant une template via l'objet Flask render_template(), où est défini le chemin vers le document html où le retour de la fonction sera affiché. La variable Actes_total contient le résultat d'une requête sur l'ensemble de la classe Ac...
def corpus(): Actes_total = Acts.query.all() return render_template("pages/corpus.html", document=Actes_total)
[ "def news(id):\n news_args = get_articles(id)\n highlight_args = 'Route Working!!'\n # name = f'{results_list}'\n return render_template('news.html',highlight_param=highlight_args,news=news_args)", "def predict_page():\n return render_template(template_name_or_list=\"predict.html\")", "def render...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Route permettant d'afficher la page de contact en retournant une template via l'objet Flask render_template(), où est défini le chemin vers le document html où le retour de la fonction sera affiché.
def contact(): return render_template("pages/contact.html")
[ "def contact():\n return render_template(\"contact.html\")", "def contact_us():\n return render_template('home/contact-us.html')", "def contact_us():\n return render_template(\"contact_us.html\")", "def landing_page():\n return render_template(\"landing.html\")", "def processContactRequest(self)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Route permettant d'afficher la page recherche. (1) Des listes vides sont définies. (2) Des requêtes sont effectuées en boucle sur la classe Acts et les éléments trouvés sont ajoutés à la liste correspondante. Dans le libellé des dépôts d'archives départemenaux et municipaux, la méthode sub() de la librairie re permet, ...
def recherche(): list_year = [] list_AN = [] list_bib = [] list_AD = [] list_AM = [] list_deperdita = [] list_state = [] list_type = [] list_city = [] for item in Acts.query.all(): year = item.date year = re.search('[0-9]{4}',year) list_year.append(int(year.group())) list_year = set(list_year) for ins...
[ "def recherche():\n # On préfèrera l'utilisation de .get() ici\n # qui nous permet d'éviter un if long (if \"clef\" in dictionnaire and dictonnaire[\"clef\"])\n motclef = request.args.get(\"keyword\", None)\n page = request.args.get(\"page\", 1)\n\n if isinstance(page, str) and page.isdigit():\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a set of unique field values from a list of DICOM files
def get_unique_field_values(dcm_file_list, field_name): field_values = set() for dcm in dcm_file_list: field_values.add(str(DicomFile(dcm).get_attributes(field_name))) return field_values
[ "def multi_field_list(fields, indicators):\n values = []\n for f in fields:\n for i in indicators:\n values.extend(subfield_list(f, i))\n return set(values)", "def arcpy_get_unique_field_values(self, arg_field_name):\r\n\t\t# next line uses python 'set comprehension'... basically an inl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a list of the dicom files within root_path
def find_all_dicom_files(root_path): dicoms = set() try: for fpath in get_all_files(root_path): if is_dicom_file(fpath): dicoms.add(fpath) except IOError as ioe: raise IOError('Error reading file {0}.'.format(fpath)) from ioe return dicoms
[ "def get_files(self, path):\n # get directory contents, fully-qualified filenames, remove non-files\n filenames = os.listdir(path)\n filenames = [os.path.join(path, filename) for filename in filenames]\n filenames = [filename for filename in filenames if os.path.isfile(filename)]\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tries to read the file using dicom.read_file, if the file exists and dicom.read_file does not raise and Exception returns True. False otherwise.
def is_dicom_file(filepath): if not os.path.exists(filepath): raise IOError('File {} not found.'.format(filepath)) filename = os.path.basename(filepath) if filename == 'DICOMDIR': return False try: _ = dicom.read_file(filepath) except Exception as exc: log.debug('Ch...
[ "def test_read(self):\n logger.info(\"Read\")\n try:\n _file = read(file_path)\n self.assertIsNotNone(_file)\n passed = True\n except Exception as e:\n passed = 'No such file' in str(e)\n self.assertEqual(passed, True)", "def is_dicom_file(pa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Group in a dictionary all the DICOM files in dicom_paths separated by the given `hdr_field` tag value.
def group_dicom_files(dicom_paths, hdr_field='PatientID'): dicom_groups = defaultdict(list) try: for dcm in dicom_paths: hdr = dicom.read_file(dcm) group_key = getattr(hdr, hdr_field) dicom_groups[group_key].append(dcm) except KeyError as ke: raise KeyErro...
[ "def enumerate_data_files(dicom_dir, contour_dir):\n\n dicom_files = {}\n contour_files = {}\n\n for dicom_name in os.listdir(dicom_dir):\n match = re.match(r'^(\\d+).dcm$', dicom_name)\n if match:\n dicom_id = match.group(1)\n dicom_files[dicom_id] = os.path.join(dicom_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decompress all .dcm files recursively found in DICOM_DIR. This uses 'gdcmconv raw'. It works when 'dcm2nii' shows the `Unsupported Transfer Syntax` error. This error is usually caused by lack of JPEG2000 support in dcm2nii compilation.
def decompress(input_dir, dcm_pattern='*.dcm'): dcmfiles = sorted(recursive_glob(input_dir, dcm_pattern)) for dcm in dcmfiles: cmd = 'gdcmconv --raw -i "{0}" -o "{0}"'.format(dcm) log.debug('Calling {}.'.format(cmd)) subprocess.check_call(cmd, shell=True)
[ "def convert_all_dicoms(directory, dicom2niix_path=\"dcm2niix\", convert=True):\n directory = os.path.join(directory)\n print(\"[INFO] Starting to convert ...\")\n # if os.path.isfile(f\"{directory}/DICOMDIR\"):\n\n\n # ds = dcmread(f\"{directory}/DICOMDIR\")\n\n\n # warnings.filterwarnings(\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function retrieve articles by article indexes and return found articles.
def retrieve_articles(article_indexes): articles = [] for index in article_indexes: filename, position = index.split('@') with open(filename, 'r', encoding='utf-8') as articles_file: articles_file.seek(int(position)) line = articles_file.readline() article = l...
[ "def articles(self, **kwargs):\n for title in self.index(**kwargs):\n yield self.search(title, **kwargs)", "def get_articles_by_aid(aids):\n\n return Article.objects.in_bulk(aids)", "def index_news_articles(self):\n # Get the RSS feed\n print('Fetching the RSS feed')\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method realizes searching by more than 1 keyword and you can search articles that include all keywords or at least one keyword.
def search_by_keywords(self, keywords, operator='or'): if operator == 'or' and self.indexes: articles_indexes = [] for keyword in keywords: if keyword in self.indexes.keys(): articles_indexes += self.indexes[keyword] articles_indexes = list...
[ "def test_user_can_search_for_articles_by_keywords(self):\n username = self.user.username\n title = self.article.title\n description = self.article.description\n body = self.article.body\n response = self.client.get(f\"{self.url}?search={username}\")\n self.assertEqual(resp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse command line arguments and liftoff configuration.
def parse_options() -> Namespace: opt_parser = OptionParser( "liftoff", [ "script", "config_path", "procs_no", "gpus", "per_gpu", "no_detach", "verbose", "copy_to_clipboard", "time_limit", #...
[ "def parse_configuration_and_cli(self, argv=None):\n # type: (Union[NoneType, List[str]]) -> NoneType\n if self.options is None and self.args is None:\n self.options, self.args = aggregator.aggregate_options(\n self.option_manager, self.config_finder, argv\n )\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the command for a pid if that process exists.
def get_command_for_pid(pid: int) -> str: try: result = subprocess.run( f"ps -p {pid:d} -o cmd h", stdout=subprocess.PIPE, shell=True ) return result.stdout.decode("utf-8").strip() except subprocess.CalledProcessError as _e: return ""
[ "def _search_for_process(cls):\n # Check existing pidfile\n pid = cls.get_pid_from_file()\n if pid:\n proc = psutil.Process(pid)\n if proc.cmdline() == cls.cmd:\n return proc\n\n # Look for the process\n for proc in psutil.process_iter():\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if a subprocess is still active.
def still_active(pid: int, cmd: str) -> bool: os_cmd = get_command_for_pid(pid) return cmd in os_cmd
[ "def _proc_is_alive(self):\n if self._proc is None:\n return False\n\n return self._proc.poll() is None", "def daemon_check(proc: subprocess.Popen):\n if proc is None:\n return True\n else:\n is_alive = proc.poll() is None\n return is_alive", "def proc_alive(p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function gets the previous list of running processes, the resources, and return the new list of pids. The resources are modified if some processes ended.
def refresh_pids(active_pids, resources): still_active_pids = [] no_change = True for info in active_pids: pid, gpu, title, cmd, lock_path = info if still_active(pid, cmd): still_active_pids.append(info) else: print(f"[{time.strftime(time.ctime())}] {title} se...
[ "def find_rogue_pids(self) -> List[ProcessID]:", "def list_active_processes():\n return psutil.process_iter()", "def get_all_running_processes():\n thispid = os.getpid()\n rpids = set()\n for pid in psutil.pids():\n try:\n if psutil.Process(pid).status() == 'running' or psutil.Proc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes a generator and returns a shuffled generator.
def shuffle(some_generator): seq = list(some_generator) random.shuffle(seq) for x in seq: yield x
[ "def _shuffle_generator(generator, shuffle_buffer_size):\n\n # TODO(matejb): Consider using random.shuffle when the buffer is first filled.\n\n shuffle_buffer = []\n for data in generator:\n shuffle_buffer.append(data)\n if len(shuffle_buffer) == shuffle_buffer_size:\n random_index = random.randint(0,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Basic HTTP auth decorator
def basic_http_auth(f): def wrap(request, *args, **kwargs): if request.META.get('HTTP_AUTHORIZATION', False): authtype, auth = request.META['HTTP_AUTHORIZATION'].split(' ') auth = base64.b64decode(auth) username, password = auth.split(':') user = authenticate(...
[ "def http_basic_auth(func):\r\n\t@wraps(func)\r\n\tdef _decorator(request, *args, **kwargs):\r\n\r\n\t\tif request.META.has_key('HTTP_AUTHORIZATION'):\r\n\t\t\ttry:\r\n\t\t\t\tauthmeth, auth = request.META['HTTP_AUTHORIZATION'].split(' ', 1)\r\n\t\t\t\tif authmeth.lower() == 'basic':\r\n\t\t\t\t\tauth = auth.strip(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Service an update request in the form of /update?ipv6=&ipv4=&domain=
def update(request): from pprint import pformat if 'ipv4' not in request.GET and 'ipv6' not in request.GET: return HttpResponse("Must specify one or both of ipv4/ipv6 address\nParams:%s" % pformat(request.GET.dict()), status=400) if not u'domain' in request.GET: return HttpResponse("Must spe...
[ "def send_update(host=\"\",domain=\"\",password=\"\",namecheap_url = \"\", ipv4=\"\",old_ipv4=[]):\r\n if old_ipv4:\r\n print(\"A difference was found for domain {}.{}. Old IPs were {} and the new found IP is {}. \".format(host,domain,' '.join(old_ipv4),ipv4))\r\n request_params = {\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Init a Paddle ASR Connection Handler instance
def __init__(self, asr_engine): super().__init__() logger.debug( "create an paddle asr connection handler to process the websocket connection" ) self.config = asr_engine.config # server config self.model_config = asr_engine.executor.config self.asr_engine = a...
[ "def __init__(self, tts_engine):\n super().__init__()\n logger.debug(\n \"Create PaddleTTSConnectionHandler to process the tts request\")\n\n self.tts_engine = tts_engine\n self.executor = self.tts_engine.executor\n self.config = self.tts_engine.config\n self.fro...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
when in continous decoding, reset for next utterance.
def reset_continuous_decoding(self): self.global_frame_offset = self.num_frames self.model_reset()
[ "def reset(self):\r\n self._parser_state = self.PARSERSTATE_IDLE\r\n self._current_bytes = []\r\n self._current_byte_counter = 0\r\n self._has_response_flag = False", "def _reset(self):\r\n Stream._reset(self)", "def reset(self):\n log.debug('Reseting decoder.')\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decorate a function or method to have its first positional argument be treated as an (x, y, z) tuple which must fit inside chunk boundaries of 16, CHUNK_HEIGHT, and 16, respectively. A warning will be raised if the bounds check fails.
def check_bounds(f): @wraps(f) def deco(chunk, coords, *args, **kwargs): x, y, z = coords # Coordinates were out-of-bounds; warn and run away. if not (0 <= x < 16 and 0 <= z < 16 and 0 <= y < CHUNK_HEIGHT): warn("Coordinates %s are OOB in %s() of %s, ignoring call" ...
[ "def _check_bounds(self, *args):\n if not all(\n (-0x7fff - 1) <= number <= 0x7fff\n for number in args):\n raise ValueError(args)\n else:\n return tuple(int(p) for p in args)", "def check_cutout(method):\n\n @wraps(method)\n def new_method(s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set up glow tables. These tables provide glow maps for illuminated points.
def make_glows(): glow = [None] * 16 for i in range(16): dim = 2 * i + 1 glow[i] = array("b", [0] * (dim**3)) for x, y, z in product(xrange(dim), repeat=3): distance = abs(x - i) + abs(y - i) + abs(z - i) glow[i][(x * dim + y) * dim + z] = i + 1 - distance ...
[ "def initialize_default_palette(self):\n print(\"Using default colors\")\n self.simple_catchment_and_flowmap_colors = ['blue','peru','white','black']\n self.create_colormap_colors = ['blue','peru','yellow','white','gray','red','black',\n 'indigo','deepskybl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Composite a light source onto a lightmap. The exact operation is not quite unlike an add.
def composite_glow(target, strength, x, y, z): ambient = glow[strength] xbound, zbound, ybound = 16, CHUNK_HEIGHT, 16 sx = x - strength sy = y - strength sz = z - strength ex = x + strength ey = y + strength ez = z + strength si, sj, sk = 0, 0, 0 ei, ej, ek = strength * 2, s...
[ "def copy(self) -> 'LightSource':\n\n new_obj = LightSource(self.position.copy(), self.intensity)\n\n return new_obj", "def merge_light_catalogue():\n output_filename = os.path.join(constants.DESTINATION,\n 'concatenated',\n 'iph...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the amount of light that should be shone on a block. ``glow`` is the brighest neighboring light. ``block`` is the slot of the block being illuminated. The return value is always a valid light value.
def neighboring_light(glow, block): return clamp(glow - blocks[block].dim, 0, 15)
[ "def getBlockLight(self, x: int, y: int, z: int) -> int:\n\t\treturn self.getSubChunk(y >> 4).getBlockLight(x, y & 0x0f, z)", "def block_colour(self, block):\n return config.BlockColour[block.block_type.value]", "def getBlockSkyLight(self, x: int, y: int, z: int) -> int:\n\t\treturn self.getSubChunk(y >>...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Regenerate the height map array. The height map is merely the position of the tallest block in any xzcolumn.
def regenerate_heightmap(self): for x in range(16): for z in range(16): column = x * 16 + z for y in range(255, -1, -1): if self.get_block((x, y, z)): break self.heightmap[column] = y
[ "def recalculateHeightMap(self):\n\t\tfor z in range(16):\n\t\t\tfor x in range(16):\n\t\t\t\tself.setHeightMap(x, z, self.getHighestBlockAt(x, z, False))", "def getHeightMap(self, x: int, z: int) -> int:\n\t\treturn self.heightMap[(z << 4) | x]", "def setHeightMap(self, x: int, z: int, value: int):\n\t\tself.h...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Regenerate the ambient light map. Each block's individual light comes from two sources. The ambient light comes from the sky. The height map must be valid for this method to produce valid results.
def regenerate_skylight(self): # Create an array of skylights, and a mask of dimming blocks. lights = [0xf] * (16 * 16) mask = [0x0] * (16 * 16) # For each y-level, we're going to update the mask, apply it to the # lights, apply the lights to the section, and then blur the ligh...
[ "def populateSkyLight(self):\n\t\t# TODO: rewrite this, use block light filters and diffusion, actual proper sky light population\n\n\t\tfor x in range(16):\n\t\t\tfor z in range(16):\n\t\t\t\theightMap = self.getHeightMap(x, z)\n\t\t\t\ty = (self.getHighestSubChunkIndex() + 1) << 4\n\n\t\t\t\t# TODO: replace a sec...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine whether any damage is pending on this chunk.
def is_damaged(self): return self.all_damaged or bool(self.damaged)
[ "def is_damaged(self):\n return self.damaged", "def damaged(self) -> bool:\n return len(self._damaged_cells) > 0", "def can_take_damage(self):\n result = True\n if self.side_effects[\"shield\"] > 0:\n result = False\n return result", "def is_dmg_dealing(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make a packet representing the current damage on this chunk. This method is not private, but some care should be taken with it, since it wraps some fairly cryptic internal data structures. If this chunk is currently undamaged, this method will return an empty string, which should be safe to treat as a packet. Please ch...
def get_damage_packet(self): if self.all_damaged: # Resend the entire chunk! return self.save_to_packet() elif not self.damaged: # Send nothing at all; we don't even have a scratch on us. return "" elif len(self.damaged) == 1: # Use a ...
[ "def damage(self):\n out = (self.blurbs[self.state][\"damage\"])\n self.next_state(\"damage\")\n return out", "def get_damage(self):\n return self.__damage", "def get_damage(self):\n return self.playerDamage", "def get_damage():\n\n return character['Damage']", "def shi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clear this chunk's damage.
def clear_damage(self): self.damaged.clear() self.all_damaged = False
[ "def take_damage(self):\n self.health -= 1", "def Hit(self, damage):\n self.health -= damage", "def huh(self, damage):\n self.skillpoints[0] -= damage", "def damage(self):\n self.damaged = True", "def clearEffects(self):\n self.effects = None", "def reset_attack(self):\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate a chunk packet.
def save_to_packet(self): mask = 0 packed = [] ls = segment_array(self.blocklight) for i, section in enumerate(self.sections): if any(section.blocks): mask |= 1 << i packed.append(section.blocks.tostring()) for i, section in enumera...
[ "def to_chunkstruct(self, chunk_label=...):\n ...", "def _create_chunk(self):\n self.chunk = Chunk(self.chunk_id)\n self.chunk.create_chunk()\n return self.chunk", "def create_file_chunk_message(filename: str, chunkId: int, chunk_data: str) -> bytes:\n return f\"{MessageCode.FILE_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Look up skylight value.
def get_skylight(self, coords): x, y, z = coords index, y = divmod(y, 16) return self.sections[index].get_skylight((x, y, z))
[ "def getBlockSkyLight(self, x: int, y: int, z: int) -> int:\n\t\treturn self.getSubChunk(y >> 4).getBlockSkyLight(x, y & 0x0f, z)", "def _calculate_light(self):\n clouds_factor = 0.7\n\n self.weather['light'] = truncate(\n self.weather['sun'] - (self.weather['clouds'] * clouds_factor)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }