query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Function to process the schedule from the server. Changes a list of HMS format strings into a list of time_struct instances. | def process_reply(string_schedule):
now= time.localtime()
schedule= []
for start_time in string_schedule:
schedule.append(time.strptime(str(now.tm_year) + "," + str(now.tm_yday) + "," + str(start_time[0:2])+":"+str(start_time[2:4])+":"+str(start_time[4:6]), '%Y,%j,%H:%M:%S'))
return schedule | [
"def schedules_list(format_):\n\n project_name = get_current_project(error=True)\n\n client = init_client()\n response = client.request_schedules_list(project_name=project_name)\n client.api_client.close()\n\n print_list(response, LIST_ITEMS, rename_cols=RENAME_COLUMNS, sorting_col=1, fmt=format_)",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to append data to today's log of testIDs. Data will either be test ID's or confirmation of test ID's being saved. | def log_data(testID):
testlog = open( clientPath+"todays_testIDs.log", 'a')
testlog.write(testID+"\n")
testlog.close() | [
"def start_new_testLog():\n\n open(clientPath+\"yesterdays_testIDs.log\", 'w').close()\n shutil.copyfile(clientPath+\"todays_testIDs.log\", clientPath+\"yesterdays_testIDs.log\")\n \n today= open(clientPath+\"todays_testIDs.log\", 'w')\n today.write(time.strftime(\"%m/%d/%Y\")+\"\\n\")\n today.close()",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to clear yesterday's testID log, create a new blank log for today Only used after today and yesterday's logs have been sent to the governor server | def start_new_testLog():
open(clientPath+"yesterdays_testIDs.log", 'w').close()
shutil.copyfile(clientPath+"todays_testIDs.log", clientPath+"yesterdays_testIDs.log")
today= open(clientPath+"todays_testIDs.log", 'w')
today.write(time.strftime("%m/%d/%Y")+"\n")
today.close() | [
"def clear_old_records(self):\n try:\n with sqlite3.connect(self.alert_uuid_cache_path) as db:\n c = db.cursor()\n c.execute(\"DELETE FROM uuid_tracking WHERE insert_date < ?\",\n ((datetime.datetime.now() - datetime.timedelta(hours=48)).timest... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to create a JSON object to send to the server. | def create_JSON_message(message_type, body=None):
clientID= partnerID+"/"+groupID+"/"+deviceID
message= {"clientID" : clientID, "type": message_type, "body": body}
return json.dumps(message) | [
"def create_json(api_key, event_type, payload):\n json_dict = dict(api_key=api_key, event_type=event_type, payload=payload)\n return json.dumps(json_dict)",
"def create_json_message(county, state, rank, timestamp, creator_id, message_id,\n sender_id, message):\n message_info = {\"c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function that collects and formats all the testId's used that day and the day before to send to the server. Message formatted in JSON. | def prepare_testIDs():
message_body= []
today= open(clientPath+"todays_testIDs.log", 'r')
yesterday= open(clientPath+"yesterdays_testIDs.log", 'r')
for log_file in [today, yesterday]:
for line in log_file:
if "/" not in line:
print len(line)
message_body.append(l... | [
"def import_sent_dates():\n print ''\n success =True\n if Result.objects.filter(result_sent_date=None,\n notification_status='sent').count() == 0:\n print \"---\" * 20\n print \"---\" * 20\n print \"\\nDB table OK. All sent results already have result_sent_d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Run correction(wrong) on all (right, wrong) pairs. No return statement; just report results. | def spell_test(tests, verbose=False):
good, unknown = 0, 0
n = len(tests)
for right, wrong in tests:
w = correction(wrong)
good += (w == right)
if w != right:
unknown += (right not in WORDS)
if verbose:
print('correction({}) =>... | [
"def doCorrections(self):\n\n self.Asave = self.difference + self.addOnCorrect\n self.corrected = self.Asave + self.buoyanCorrect\n\n if self.debug:\n print 'Buoyancy correction:'\n print self.buoyanCorrect\n print'Corrected difference matrix'\n print... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Password protect database backups | def audit_601_password_protect_database_backups():
global conn
dump_files = io_params['Sybase Dump File List'].strip().split(',')
isValid = True
msg = ''
for dump_file in dump_files:
sql = "load database whatisthedatabasename99999999 from \"%s\" with headeronly" % dump_file... | [
"def backup_passwords(self):\n util.make_or_verify_dir(self.PASSWORDS_BACKUP_DIR, mode=0o600)\n util.delete_file_backup(self.PASSWORDS_FILE, chmod=0o600, backup_dir=self.PASSWORDS_BACKUP_DIR)\n with util.safe_open(self.PASSWORDS_FILE, chmod=0o600) as f:\n f.write('httpsserver.passwor... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return child by its path. | def get_child(self, path=""):
path_list = path.split("/")
first = path_list.pop(0)
if not first:
return self._child
if self._child.name == first:
if not path_list:
return self._child
try:
return self._child.get_child(pat... | [
"def _child_by_path(self, path, create=False, type='datafile'):\n names = string.split(path, '/')\n curr = self.top\n if names[0] != curr.name:\n raise ValueError(\"Child not found: \" + path + \". Could not match: \" + names[0])\n for n in names[1:]:\n nextchild = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tell the supervisor to stop the children. | def stop_children(self):
self.send_action("stop_children") | [
"def kill_subprocesses(self):\n pass",
"def stop( self, type=STOPPED ):\n\n if self.status == type:\n return\n\n self.logMsg( \"Pool stopped, stopping all children.\" )\n\n for c in self.children:\n self.endChild( c.num )\n\n self.status = type \n se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tell the supervisor to wake up. | def wake_up(self):
self.send_action("wake_up") | [
"async def wake(self, ctx):\r\n await self.client.change_presence(status=discord.Status.online)\r\n\r\n Database.Bot[\"sleeping\"] = False\r\n\r\n await ctx.send(\"Huh? What? Oh... I'm awake.\")",
"def wake(self):\n self.i2c.mem_write(0x01, self.addr, PWR_MGMT_1)",
"def wake(self):\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read the status from the specified file. | def read_status(self):
try:
tmp_file = open(self._status_file, "r")
try:
status = json.load(tmp_file)
except ValueError:
raise SimplevisorError(
"Status file not valid: %s" % (self._status_file, ))
else:
... | [
"def _read_status(self):\n self._status = shellutils.read_status(self._status_file, self._status)",
"def _ReadInstanceStatus(filename):\n logging.debug(\"Reading per-group instance status from '%s'\", filename)\n\n statcb = utils.FileStatHelper()\n try:\n content = utils.ReadFile(filename, preread=st... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Save the status in the specified file. | def save_status(self):
if self._status_file is None:
return
try:
self.logger.debug("status file: %s", self._status_file)
status_f = open(self._status_file, "w")
try:
status = {self._child.get_id(): self._child.dump_status()}
... | [
"def save_file(self):\r\n self._main.save_file()",
"def statusWrite(self):\n # this function is executed automatically (initialized at the bottom of this file), simply records current pxp status in a file\n # the text status is saved simply as 'status' and the numeric status code is saved as ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert a batch of sequences to word vectors. | def sequences_to_vectors(sequences, seq_length, w2v_model):
batch_size = len(sequences)
vec_matrix = np.zeros([batch_size, seq_length, w2v_model.vector_size], dtype=np.float32)
for i in range(batch_size):
for j in range(seq_length):
word_index = sequences[i][j]
if word_index ... | [
"def doc_transform(doc_batch):\n docs = []\n for d in doc_batch:\n words = []\n for s in d:\n words += s\n docs.append(words)\n # nw = len(words)\n return docs",
"def vectorize_documents(document_list, vectorizer):\n X = vectorizer.transform(document_list)\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Builds parser app for sending and receiving BEL statements | def build_parser_service(app, conversion_function=None):
graph = BELGraph()
graph.document.update({
METADATA_NAME: 'PyBEL Web Parser Results',
METADATA_AUTHORS: getuser(),
METADATA_DESCRIPTION: 'This graph was produced using the PyBEL Parser API. It was instantiated at {}'.format(
... | [
"def parseApplication(app):\n ...",
"def generate_python_script(self):\n self.print(\"#!/usr/bin/python\")\n stamp = datetime.datetime.now().ctime()\n self.print('\"\"\" Automatically generated on {} \"\"\"'.format(stamp))\n self.print(\"from ppci.lang.tools.grammar import Productio... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parses a URLencoded BEL statement | def parse_bel(statement):
parser.control_parser.clear()
parser.control_parser.annotations.update({
METADATA_TIME_ADDED: str(time.asctime()),
METADATA_IP: request.remote_addr,
METADATA_HOST: request.host,
METADATA_USER: request.remote_user
})
... | [
"def parse_code(url):\n result = urlparse(url)\n query = parse_qs(result.query)\n return query['code']",
"def testTagFunctionUrl(self):\n template = 'http://example.com/?breakfast=[query|url]'\n result = self.parse(template, query='\"ham & eggs\"')\n self.assertEqual(result, 'http://example.com/... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Estimates the number of moves between start_node and destination_node. To satisfy A search this can be an overestimate, but not an underestimate. | def get_estimated_cost(start_node, destination_node):
delta_x = abs(start_node.x - destination_node.x)
delta_y = abs(start_node.y - destination_node.y)
if delta_x < delta_y:
return math.sqrt(2 * delta_x^2) + delta_y - delta_x
else:
return math.sqrt(2 * delta... | [
"def search(self, start, destination):\n # attribute L records the maximum ρ() value of the route from the \n # start node s to node ni\n for node in self.nodes:\n node.L = 0\n self.nodes[start].L = 1\n\n # create priority queue sorted by node's attribute L\n pri... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a list of nodes to traverse from start_node to destination_node, without immediately going to previous_node. Implements a constrained version of A (Astar) search. | def find_path(self, start_node, previous_node, destination_node):
opened = []
closed = []
start_node.heuristic_cost = 0
start_node.f = 0
start_node.g = 0
opened.append(start_node)
while len(opened) > 0:
minimum_node = None
mini... | [
"def dijkstra_search(initial_node, dest_node):\n return queue_search(initial_node, dest_node, queue.PriorityQueue(), True)",
"def bfs(initial_node, dest_node):\n return queue_search(initial_node, dest_node, queue.Queue())",
"def search(self, start, dest):\n self.searched = []\n\n closed = se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If the function has one of the external decorators, returns it. Otherwise, returns None. | def get_external_decorator(self, elm: CodeElementFunction) -> Optional[ExprIdentifier]:
for decorator in elm.decorators:
if decorator.name in ENTRY_POINT_DECORATORS:
return decorator
return None | [
"def _check_function_exists(self, function_name):\n try:\n # Get the reference to the function\n function = getattr(self, function_name)\n return function\n except AttributeError as detail:\n #logger.error(\"while checking middleware functions: %s\\nCheck th... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds an entry describing the function to the contract's ABI. | def add_abi_entry(
self, name: str, arg_struct_def: StructDefinition, ret_struct_def: StructDefinition,
is_view: bool, entry_type: str):
inputs = []
outputs = []
for m_name, member in arg_struct_def.members.items():
assert is_type_resolved(member.cairo_type)
... | [
"def add_function(self, func):\n self._conf['functions'].append(func)",
"def add_entry(self, signature, **kwargs):\n if \"label\" in kwargs:\n label = kwargs['label']\n name = f\"glossary.{label}\"\n anchor = f\"glossary:{label}\"\n else:\n name = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Processes the return values and return retdata_size and retdata_ptr. | def process_retdata(
self, ret_struct_ptr: Expression, ret_struct_type: CairoType,
struct_def: StructDefinition,
location: Optional[Location]) -> Tuple[Expression, Expression]:
# Verify all of the return types are felts.
for _, member_def in struct_def.members.items(... | [
"def _get_res(data, params, shape_x, dtype, cast_dtype):\n pd_x, var_elta_2_cast, sub_x_mean = _get_pd_x(data, params, shape_x,\n dtype, cast_dtype)\n\n pd_gamma = _get_pd_gamma(data, params, var_elta_2_cast, sub_x_mean,\n dtype, cas... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validates the signature of an l1_handler. | def validate_l1_handler_signature(self, elm: CodeElementFunction):
args = elm.arguments.identifiers
if len(args) == 0 or args[0].name != 'from_address':
# An empty argument list has no location so we point to the identifier.
location = elm.identifier.location if len(args) == 0 e... | [
"def _check_signature(self, request, key):\n supercls = super(TokenServerAuthenticationPolicy, self)\n try:\n return supercls._check_signature(request, key)\n except HTTPUnauthorized:\n logger.warn(\"Authentication Failed: invalid hawk signature\")\n raise",
"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets endpoint on fixture, validate results | def test_get_endpoint(client):
meta = load_response(client.get_endpoint).metadata
epid = meta["endpoint_id"]
# load the endpoint document
ep_doc = client.get_endpoint(epid)
# check that the contents are basically OK
assert ep_doc["DATA_TYPE"] == "endpoint"
assert ep_doc["id"] == epid
a... | [
"def test_simple_endpoint_validation():\n eg = EveGenie(data=simple_test_data)\n data = dict(eg)\n for endpoint in data:\n v = Validator(data[endpoint])\n assert(v.validate(simple_test_data[endpoint]))",
"def test_get(self):\n # get test endpoint\n path = self.bc.qjoin_path(\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Does an `ls` on goep1, validate results, and check that the request parameters were formatted and sent correctly. | def test_operation_ls(client):
# register get_endpoint mock data
register_api_route_fixture_file(
"transfer", f"/operation/endpoint/{GO_EP1_ID}/ls", "operation_ls_goep1.json"
)
ls_path = f"https://transfer.api.globus.org/v0.10/operation/endpoint/{GO_EP1_ID}/ls"
# load the tutorial endpoint ... | [
"def test_all_input_get(self):\n response = self.client.open(\n '/nlp/all/{input}'.format(input='input_example'),\n method='GET',\n content_type='application/json')\n self.assert200(response,\n 'Response body is : ' + response.data.decode('utf-8')... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Do `autoactivate` on goep1, validate results, and check that `if_expires_in` can be passed correctly. | def test_autoactivation(client):
# register get_endpoint mock data
register_api_route_fixture_file(
"transfer",
f"/endpoint/{GO_EP1_ID}/autoactivate",
"activation_stub.json",
method="POST",
)
# load and check the activation doc
res = client.endpoint_autoactivate(GO_E... | [
"def activate_ep(api, ep):\n logger.info(\"Activating \" + ep)\n try:\n api.endpoint_autoactivate(ep)\n except Exception, err:\n logger.critical(\"Unable to activate endpoint: : %s\" % (err))\n logger.critical(\"Please log into Globus Online and activate the endpoint there\")\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a storage pool | def create_storage_pool(self, pool_name, pd_id, media_type,
use_rfcache=None, use_rmcache=None):
try:
if media_type == "Transitional":
self.module.fail_json(msg="TRANSITIONAL media type is not"
" supported during c... | [
"def create(cls, client, config):\n client.api.storage_pools.post(json=config)\n\n storage_pool = cls.get(client, config['name'])\n return storage_pool",
"def create_pool(self, **params):\n pool = self.get_pool(connect=False, **params)\n\n # Save the pool\n self.pool.appe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This method provides parameters required for the ansible Storage Pool module on powerflex | def get_powerflex_storagepool_parameters():
return dict(
storage_pool_name=dict(required=False, type='str'),
storage_pool_id=dict(required=False, type='str'),
protection_domain_name=dict(required=False, type='str'),
protection_domain_id=dict(required=False, type='str'),
media... | [
"def init_parameters(request, storage):\n self = request.node.cls\n\n self.host_ip = ll_hosts.get_host_ip(ll_hosts.get_spm_host(config.HOSTS))\n self.disk_name = storage_helpers.create_unique_object_name(\n self.__name__, config.OBJECT_TYPE_DISK\n )\n found, master_domain = ll_sd.findMasterSto... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create PowerFlex Storage Pool object and perform action on it based on user input from playbook | def main():
obj = PowerFlexStoragePool()
obj.perform_module_operation() | [
"def test_create_cloud_pool(self):\n pass",
"def test_pool_create(self):\n pool_name = p_n()\n self.unittest_command(\n [_STRATIS_CLI, \"pool\", \"create\", pool_name, StratisCertify.DISKS[0]],\n 0,\n True,\n True,\n )",
"def create_storage... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a ServiceX datasource for a particular Open Data file. | def make_datasource(fileset:dict, name: str, query: ObjectStream, ignore_cache: bool, backend_name: str = "uproot"):
datasets = [ServiceXDataset(fileset[name]["files"], backend_name=backend_name, ignore_cache=ignore_cache)]
return servicex.DataSource(
query=query, metadata=fileset[name]["metadata"], dat... | [
"def server_datasource(change_test_dir_and_create_data_path):\n return ProdServer(default_config_path)",
"def data_source(yml_filename):\n print(\"Importing data sources from '{}'\".format(yml_filename))\n with open(yml_filename) as yml_file:\n data_sources_yaml = yaml.load(yml_file)\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determine if a subsequence is contained in the biological sequence. | def __contains__(self, subsequence):
return self._munge_to_bytestring(subsequence, "in") in self._string | [
"def is_subsequence(seq, subseq):\n\n ss_len = len(subseq)\n s_index, ss_index = 0, 0\n while s_index < len(seq) and ss_index < ss_len:\n if seq[s_index] == subseq[ss_index]:\n ss_index += 1\n s_index += 1\n\n return ss_index == ss_len",
"def is_subsequence(seq1, seq2):\n s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Count occurrences of a subsequence in the biological sequence. | def count(self, subsequence, start=None, end=None):
if len(subsequence) == 0:
raise ValueError("`count` is not defined for empty subsequences.")
return self._string.count(
self._munge_to_bytestring(subsequence, "count"), start, end) | [
"def count(seq):\n return sum(1 for x in seq)",
"def count(seq): # real signature unknown; restored from __doc__\n pass",
"def numSubarraysWithSum(self, A, S):\n cum_sum = [0]\n counter = defaultdict(int)\n for i in range(len(A)):\n cum_sum.append(cum_sum[-1]+A[i])\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Yield contiguous subsequences based on `included`. | def iter_contiguous(self, included, min_length=1, invert=False):
idx = self._munge_to_index_array(included)
if invert:
idx = np.delete(np.arange(len(self)), idx)
# Adapted from http://stackoverflow.com/a/7353335/579416
for contig in np.split(idx, np.where(np.diff(idx) != 1)[... | [
"def has_contiguous_sublist(self, As: List):\n (len_As, len_self) = (len(As), len(self))\n if len_As == 0:\n yield # Succeed\n elif len_As > len_self:\n return # Fail.\n else:\n for i in range(len_self - len_As + 1):\n # Succeed for each segment of self that can be unified with A... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return bool indicating presence of quality scores in the sequence. Returns bool ``True`` if the biological sequence has quality scores, ``False`` otherwise. See Also quality | def _has_quality(self):
return self.quality is not None | [
"def isQuality(self,*args):\n _quality = self.quality\n for a in args:\n if a not in _quality:\n return False\n return True",
"def has_score(self):\n return self.lessontestscore_set.all().exists()",
"def folk_has_quality(self, slug):\n\n\treturn self.quality... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate a random name with the given number of characters. | def gen_name(length):
seed()
return ''.join(choice(ascii_lowercase) for _ in xrange(length)) | [
"def generate_name(max_chars: int):\n return \"\".join([\n random.choice(string.ascii_letters + string.digits)\n for n in range(max_chars)\n ])",
"def create_random_name(self):\n name = ''\n for _ in range(self.NAME_LENGTH):\n name += choice(ascii_letters)\n ret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
(tuple) > bool Function returnes True if ship hitted in certain coordinates | def is_hitted(self, coord):
return coord in self.__hit | [
"def InShip(ships, x, y):\n coord = (x, y)\n for ship in ships:\n if coord in ship: \n return True\n return False",
"def is_attacked_at(self, coord_x: int, coord_y: int) -> Tuple[bool, bool]:\n # Save shot\n self.set_coordinates_previous_shots.add((coord_x, coord_y))\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
(None) > list Function returnes coordinates of borders of ship | def get_borders(self):
borders = map(lambda x: (x[1]-1, ord(x[0])-65),
create_borders(self.bow, self.__length, "horizontal" if
self.horizontal else "vertical"))
return set(borders)-set(map(lambda x: (x[1]-1, ord(x[0])-65),
... | [
"def get_outer_border():\n\n\touter_border_coords = [] # stores (long, lat pairs) - e.g. (-83, 42)\n\n\t# Append vertices.\n\touter_border_coords.append((-83.098183, 42.286897))\n\touter_border_coords.append((-83.118074, 42.289572))\n\touter_border_coords.append((-83.119683, 42.287215))\n\touter_border_coords.appe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
(tuple) > Ship or False Function tries to shoot on certain coordinates and returns Ship object if hit and False if not | def shoot_at(self, coord):
if isinstance(self.board[coord[1]-1][ord(coord[0])-65], Ship):
self.board[coord[1]-1][ord(coord[0])-65].shoot_at(coord)
return self.board[coord[1]-1][ord(coord[0])-65]
else:
self.board[coord[1]-1][ord(coord[0])-65] = 3
return Fal... | [
"def ship_hit(ai_settings, stats, scoreboard, screen, ship, aliens, moving_aliens, shooting_aliens, bullets, alien_bullets, pow_ups):\r\n #Destroy all aliens and bullets\r\n aliens.empty()\r\n bullets.empty()\r\n moving_aliens.empty()\r\n shooting_aliens.empty()\r\n alien_bullets.empty()\r\n po... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This tests running nhifoutpatient endpoint with valid doctype and no query | def test_nhif_outpatient_endpoint_without_query(self):
response = self.client.get("search/nhif-outpatient?q=")
self.assertIn(b"AMIN WOMEN'S CARE CLINIC", response.data) | [
"def test_nhif_outpatient_endpoint_gets_nhif_outpatient(self):\n response = self.client.get(\"search/nhif-outpatient?q=BRISTOL\")\n self.assertIn(b\"OK\", response.data)",
"def test_nhif_outpatient_endpoint_without_query(self):\n response = self.client.get(\"search?q=\")\n self.assertI... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This tests running nhifoutpatient endpoint with valid doctype and query | def test_nhif_outpatient_endpoint_gets_nhif_outpatient(self):
response = self.client.get("search/nhif-outpatient?q=BRISTOL")
self.assertIn(b"OK", response.data) | [
"def test_nhif_outpatient_endpoint_without_query(self):\n response = self.client.get(\"search/nhif-outpatient?q=\")\n self.assertIn(b\"AMIN WOMEN'S CARE CLINIC\", response.data)",
"def test_nhif_outpatient_endpoint_without_query(self):\n response = self.client.get(\"search?q=\")\n self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This tests running nhifoutpatient endpoint with correct available keyword only | def test_nhif_outpatient_endpoint_with_keyword_only(self):
response = self.client.get("search?q=outpatient insurance")
self.assertIn(b'"status": "FAILED"', response.data) | [
"def test_nhif_outpatient_endpoint_with_nonkeyword(self):\n response = self.client.get(\"search?q=maji Kilifi\")\n self.assertIn(b'\"status\": \"FAILED\"', response.data)",
"def test_nhif_outpatient_endpoint_without_query(self):\n response = self.client.get(\"search/nhif-outpatient?q=\")\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This tests running nhifoutpatient endpoint without query | def test_nhif_outpatient_endpoint_without_query(self):
response = self.client.get("search?q=")
self.assertIn(b'"status": "FAILED"', response.data) | [
"def test_nhif_outpatient_endpoint_without_query(self):\n response = self.client.get(\"search/nhif-outpatient?q=\")\n self.assertIn(b\"AMIN WOMEN'S CARE CLINIC\", response.data)",
"def test_nhif_outpatient_endpoint_gets_nhif_outpatient(self):\n response = self.client.get(\"search/nhif-outpati... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This tests running nhifoutpatient endpoint with a keyword that is unavailable. | def test_nhif_outpatient_endpoint_with_nonkeyword(self):
response = self.client.get("search?q=maji Kilifi")
self.assertIn(b'"status": "FAILED"', response.data) | [
"def test_nhif_outpatient_endpoint_with_keyword_only(self):\n response = self.client.get(\"search?q=outpatient insurance\")\n self.assertIn(b'\"status\": \"FAILED\"', response.data)",
"def test_nhif_outpatient_endpoint_without_query(self):\n response = self.client.get(\"search?q=\")\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize restuarant_name and cuisine_type attributes. | def __init__(self, restuarant_name, cuisine_type):
self.restuarant_name = restuarant_name.title()
self.cuisine_type = cuisine_type.title() | [
"def __init__(self, restaurant_name, cuisine_type):\r\n\t\tself.restaurant_name = restaurant_name\r\n\t\tself.cuisine_type = cuisine_type",
"def __init__(self, origin, fuel_type, destination):\n super().__init__(origin, fuel_type, destination)\n self.route_data = {\n \"origin\": [],\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get intrinsic parameters of a given camera and settings (3D or 2D). These intrinsic parameters take into account the expected resolution of the point clouds captured with the given settings. If settings are not provided, intrinsics appropriate for the camera's default 3D capture settings is returned. | def intrinsics(camera, settings=None):
if settings is None:
return _to_camera_intrinsics(
_zivid.calibration.intrinsics(
camera._Camera__impl # pylint: disable=protected-access
)
)
if isinstance(settings, Settings):
return _to_camera_intrinsics(
... | [
"def get_camera_setting_by_name(self, setting_name: str) -> Dict:\n self.get_face_recognition_settings()\n return self.__face_recognition_settings[\"camera-settings\"][self.get_current_settings_index(\n self.__face_recognition_settings,\n setting_name)]",
"def get_calibration_p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Estimate camera intrinsics for a given frame. This function is for advanced use cases. Otherwise, use intrinsics(camera). | def estimate_intrinsics(frame):
return _to_camera_intrinsics(
_zivid.calibration.estimate_intrinsics(
frame._Frame__impl # pylint: disable=protected-access
)
) | [
"def compute_intrinsics(self):\n ImageSizeX = int(self.camera.attributes[\"image_size_x\"])\n ImageSizeY = int(self.camera.attributes[\"image_size_y\"])\n camFOV = float(self.camera.attributes[\"fov\"])\n\n focal_length = ImageSizeX / (2 * tan(camFOV * pi / 360))\n center_X = Imag... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Detect feature points from a calibration object. Using this version of the detectFeaturePoints function is necessary to ensure that the data quality is sufficient for use in infield verification and correction. The functionality is to be exclusively used in combination with Zivid verified checkerboards. | def detect_feature_points(camera):
return DetectionResult(
_zivid.infield_correction.detect_feature_points_infield(
camera._Camera__impl # pylint: disable=protected-access
)
) | [
"def _detect_facial_points(self, frame):\n # Rectangles of multiple faces\n rect = self._detector(frame, IMAGE_UPSAMPLE_FACTOR)\n\n # Only use the first face image\n if len(rect) > 0:\n facial_points = self._predictor(frame, rect[0])\n facial_points = face_utils.sha... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verify the current camera trueness based on a single measurement. The purpose of this function is to allow quick assessment of the quality of the infield correction on a camera (or the need for one if none exists already). This function will throw an exception if any of the provided InfieldCorrectionInput have valid()=... | def verify_camera(infield_correction_input):
return CameraVerification(
_zivid.infield_correction.verify_camera(
infield_correction_input._InfieldCorrectionInput__impl # pylint: disable=protected-access
)
) | [
"def _checkValidity(self) -> None:\n\n fresnel_zone_dist = np.sqrt(self._probe_params.wavelength * self._det_params.obj_dist)\n fresnel_zone_npix = fresnel_zone_dist / self._det_params.pixel_pitch\n\n error_str = (f\"Step size ({self._scan_params.scan_step_npix} is too small. \"\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate new infield camera correction. The purpose of this function is to calculate a new infield correction for a camera based on a series of calibration object captures taken at varying distances. This function will throw an exception if any of the provided InfieldCorrectionInput have valid()==False. The quantity a... | def compute_camera_correction(dataset):
return CameraCorrection(
_zivid.infield_correction.compute_camera_correction(
[
infield_correction_input._InfieldCorrectionInput__impl # pylint: disable=protected-access
for infield_correction_input in dataset
]... | [
"def verify_camera(infield_correction_input):\n return CameraVerification(\n _zivid.infield_correction.verify_camera(\n infield_correction_input._InfieldCorrectionInput__impl # pylint: disable=protected-access\n )\n )",
"def run(self, exposure, catalog):\n bbox = exposure.ge... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write the infield correction on a camera. After calling this function, the given correction will automatically be used any time the capture function is called on this camera. The correction will be persisted on the camera even though the camera is powercycled or connected to a different PC. Beware that calling this wil... | def write_camera_correction(camera, camera_correction):
_zivid.infield_correction.write_camera_correction(
camera._Camera__impl, # pylint: disable=protected-access
camera_correction._CameraCorrection__impl, # pylint: disable=protected-access
) | [
"def verify_camera(infield_correction_input):\n return CameraVerification(\n _zivid.infield_correction.verify_camera(\n infield_correction_input._InfieldCorrectionInput__impl # pylint: disable=protected-access\n )\n )",
"def reset_camera_correction(camera):\n _zivid.infield_corr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reset the infield correction on a camera to factory settings. | def reset_camera_correction(camera):
_zivid.infield_correction.reset_camera_correction(
camera._Camera__impl # pylint: disable=protected-access
) | [
"def resetCameraView(self):\n\t\tself.openGLWindow.setCameraPosition(distance=defaultZoom, azimuth=defaultAzimuth, elevation=defaultElevation)",
"def reset_calibration_model(self):\n\t\tif (self.calibration_manager!=None):\n\t\t\tself.calibration_manager.reset_model()\n\n\t\t\tself.set_calibration_data()",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if the camera has an infield correction written to it. This is false if write_camera_correction has never been called using this camera. It will also be false after calling reset_camera_correction. | def has_camera_correction(camera):
return _zivid.infield_correction.has_camera_correction(
camera._Camera__impl # pylint: disable=protected-access
) | [
"def verify_camera(infield_correction_input):\n return CameraVerification(\n _zivid.infield_correction.verify_camera(\n infield_correction_input._InfieldCorrectionInput__impl # pylint: disable=protected-access\n )\n )",
"def write_camera_correction(camera, camera_correction):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the time at which the camera's infield correction was created. | def camera_correction_timestamp(camera):
return _zivid.infield_correction.camera_correction_timestamp(
camera._Camera__impl # pylint: disable=protected-access
) | [
"def origintime(event):\n return event.preferred_origin().time",
"def entry_turn(self):\n return self._entry_time",
"def revocation_time(self) -> Optional[pulumi.Input[str]]:\n return pulumi.get(self, \"revocation_time\")",
"def get_time(self):\n return self.event_time",
"def registr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Construct an InfieldCorrectionInput instance. Input data should be captured by calling the version of detect_feature_points that takes a Camera argument. | def __init__(self, detection_result):
if not isinstance(detection_result, DetectionResult):
raise TypeError(
"Unsupported type for argument detection_result. Expected zivid.calibration.DetectionResult but got {}".format(
type(detection_result)
)
... | [
"def __init__(self, impl):\n if not isinstance(impl, _zivid.infield_correction.CameraCorrection):\n raise TypeError(\n \"Unsupported type for argument impl. Got {}, expected {}\".format(\n type(impl), type(_zivid.infield_correction.CameraCorrection)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the contained DetectionResult. | def detection_result(self):
return DetectionResult(self.__impl.detection_result()) | [
"def get_detector(self):\n return self._detector",
"def get_inference_image(self):\n for detection in self.cvOut[0,0,:,:]:\n score = float(detection[2])\n if score > self.Threshold:\n left = int(detection[3] * self.cols)\n top = int(detection[4] ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize CameraVerification wrapper. This constructor is only used internally, and should not be called by the enduser. | def __init__(self, impl):
if not isinstance(impl, _zivid.infield_correction.CameraVerification):
raise TypeError(
"Unsupported type for argument impl. Got {}, expected {}".format(
type(impl), type(_zivid.infield_correction.CameraVerification)
)
... | [
"def initialize(self):\n logger.debug('Initializing Basler Camera')\n tl_factory = pylon.TlFactory.GetInstance()\n devices = tl_factory.EnumerateDevices()\n if len(devices) == 0:\n raise CameraNotFound('No camera found')\n\n for device in devices:\n if self.c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the estimated local dimension trueness. The dimension trueness represents the relative deviation between the measured size of the calibration object and the true size of the calibration object, including the effects of any infield correction stored on the camera at the time of capture. Note that this estimate is lo... | def local_dimension_trueness(self):
return self.__impl.local_dimension_trueness() | [
"def accuracy(self):\n num_correct = self.prediction_matrix.diag().sum()\n num_total = self.recorded.sum()\n\n return num_correct.float() / num_total.float()",
"def getTolerance(self) -> \"float\":\n return _coin.SbCylinderSectionProjector_getTolerance(self)",
"def fraction_covered(s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the estimated dimension accuracy obtained if the correction is applied. This number represents a 1sigma (68% confidence) upper bound for dimension trueness error in the working volume (z=zMin() to z=zMax(), across the entire field of view). In other words, it represents the expected distribution of local dimension ... | def dimension_accuracy(self):
return self.__impl.dimension_accuracy() | [
"def accuracy(self):\n num_correct = self.prediction_matrix.diag().sum()\n num_total = self.recorded.sum()\n\n return num_correct.float() / num_total.float()",
"def getAccuracy(self):\r\n \r\n \tif self.predictionError <= cons.epsilon_0:\r\n \t accuracy = 1.0\r\n \telse:\r\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize CameraCorrection wrapper. This constructor is only used internally, and should not be called by the enduser. | def __init__(self, impl):
if not isinstance(impl, _zivid.infield_correction.CameraCorrection):
raise TypeError(
"Unsupported type for argument impl. Got {}, expected {}".format(
type(impl), type(_zivid.infield_correction.CameraCorrection)
)
... | [
"def __init__(self):\n\n # Here's the deal with camera matrices: the official tutorial\n # says it's necessary, but the other tutorial I used doesn't.\n # It works if I just estimate the values, so that's what I've\n # done. If we ever change to a camera with lots of distortion\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a CSV report from the trial dict. | def generate_csv_report(config, trial_results):
with open(config['CSV_REPORT_PATH'], 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(["Test Number", "Days Survived", "Max Vegetation"])
for trial in trial_results:
writer.writerow(trial_results[trial].values(... | [
"def generate_report(self) -> None:\n csv_data = self._run()\n self._write_csv(csv_data)",
"def genreport(argsdict):\n utils.sts(\"Creating Results\", 3)\n\n contests_dod = DB.load_data('styles', 'contests_dod.json')\n utils.sts(f\"Total of {len(contests_dod)} contests.\", 3)\n results_d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a JSON report from the trial dict. | def generate_json_report(config, trial_results):
with open(config['JSON_REPORT_PATH'], 'w', encoding='utf-8') as file:
json.dump(trial_results, file, ensure_ascii=False, indent=4) | [
"def json_report(self):\r\n return {\"idReport\": self.id_report, \"reason\": self.reason, \"date\": self.date,\r\n \"idService\": self.id_service, \"idMemberATE\": self.id_member_ate}",
"def _create_trial_info(self, expr_dir):\n meta = self._build_trial_meta(expr_dir)\n\n self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the domain name for the 1Password account | def get_domain() -> str:
domain = input("Please input your 1Password domain in the format <something>.1password.com: ")
return domain | [
"def get_domain_name(DomainName=None):\n pass",
"def domain_name(self):\n ret = self._get_attr(\"domainName\")\n return ret",
"def get_domain_name(self):\n domain_name = urlparse.urljoin(self.url, '/')\n return domain_name",
"def getDomain(self):\n return self.getParamete... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Helper function to sign out of 1Password | def signout():
read_bash_return("op signout") | [
"def signout():\n read_bash_return('op signout')",
"def signOut():\n authenticator.authenticate()\n token = flask.request.headers.get('auth_token')\n models.AuthTokenBlacklist(token=token).save()",
"def logout_user(self):",
"def persona_logout():\n if 'user_id' in session:\n del session['u... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Helper function to list all vaults | def list_vaults():
return json.loads(read_bash_return("op vault list --format=json", single=False)) | [
"def list_items(vault=\"Private\"):\n items = json.loads(read_bash_return(\"op list items --vault='{}'\".format(vault)))\n return items",
"def list_items(vault: str = \"Private\") -> dict:\n items = json.loads(read_bash_return(\"op items list --vault='{}' --format=json\".format(vault), single... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Helper function to list all items in a certain vault | def list_items(vault: str = "Private") -> dict:
items = json.loads(read_bash_return("op items list --vault='{}' --format=json".format(vault), single=False))
return items | [
"def list_items(vault=\"Private\"):\n items = json.loads(read_bash_return(\"op list items --vault='{}'\".format(vault)))\n return items",
"def list_vaults():\n return json.loads(read_bash_return(\"op vault list --format=json\", single=False))",
"def list(server, secret, token, profile):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes function only for `z1` < `z2`, the rest is filled with `bad_value` | def compute_for_good_redshifts(
function,
z1,
z2,
bad_value,
warning_message,
z1_arg_name="z1",
z2_arg_name="z2",
r_proj=None,
**kwargs,
):
kwargs = {z1_arg_name: locals()["z1"], z2_arg_name: locals()["z2"], **kwargs}
z_good = np.less(z1, z2)
if r_proj is not None:
... | [
"def zbrac(func, x1, x2, factor=1.6, ntry=50, tighten=True, args=(),\n full_output=0):\n \n if factor < 1:\n print 'Warning low growth of bracket interval:', factor\n\n if x1 == x2:\n print 'you must provide two disctinct guesses to zbrac'\n sys.exit()\n\n def outs(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test if brewery name h1 is in html page | def test_brewery_name(self):
self.assertEqual("The Alchemist", self.soup.h1.text) | [
"def test_brewery2_name(self):\n self.assertEqual(\"Carton Brewing Company\", self.soup.h1.text)",
"def find_title(self, html):\n return \"\"",
"def test_get__header(self):\n self.assertTrue('<h1>Contact Manager</h1>')",
"def get_h1(html:BeautifulSoup):\n h1 = None\n if html.h1:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test if brewery name h1 is in html page | def test_brewery2_name(self):
self.assertEqual("Carton Brewing Company", self.soup.h1.text) | [
"def test_brewery_name(self):\n self.assertEqual(\"The Alchemist\", self.soup.h1.text)",
"def find_title(self, html):\n return \"\"",
"def test_get__header(self):\n self.assertTrue('<h1>Contact Manager</h1>')",
"def get_h1(html:BeautifulSoup):\n h1 = None\n if html.h1:\n h1 =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load CWE definitions from a local JSON file. This data can be fetched with get_cwe_defs.py. | def load_cwe_definitions():
with open("./cwe_full_defs.json") as f:
data = json.load(f)
return data | [
"def handle_source_file(path):\n root_node = jsonized.get_json(path)\n if root_node is None:\n error(\"Failed to evaluate %s\" % path)\n clear()\n collect_base_sorts(root_node)\n collect_defs(root_node)\n collect_static_constants() # From previously collected defs.\n collect_top_level_d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a text representation of a CWE string along with a verbose translation. | def create_cwe_text(cwe_string):
cwe_defs = load_cwe_definitions()
cwe_parts = cwe_string.split("->")
final_parts = []
for part in cwe_parts:
try:
if "|" in part:
# Only one level of nesting (using parens) is allowed so strip them all and split
# to ge... | [
"def _construct_msg(self) -> str:\n return '\\n'.join([\n self._formatted_filename(), self._err_description()])",
"def ShortExplanation(self):\n return 'failed: %s' % (self.message,)",
"def _getDiagnosticString():\n text = '\\n## Diagnostic output from tacos2 ## \\n\\n'\n text += 'Tac... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reads one dbt column in Metabasefriendly format. | def _read_column(self, column: Mapping, schema: str) -> MetabaseColumn:
column_name = column.get("name", "").upper().strip('"')
column_description = column.get("description")
metabase_column = MetabaseColumn(
name=column_name,
description=column_description,
... | [
"def _parse_column(self, line, state):\n\n spec = None\n m = self._re_column.match(line)\n if m:\n spec = m.groupdict()\n spec[\"full\"] = True\n else:\n m = self._re_column_loose.match(line)\n if m:\n spec = m.groupdict()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reads in an entire file and gets its diacritized form using one request to MADAMIRA, writing the diacritized text to an output file. | def diac_file(fin, fout, server_url, separate_punct=False):
config = generate_config(fin, separate_punct)
response = requests.post(server_url, data=config.encode('utf-8'))
diac_sentences = _diac_gen(response.content)
for sentence in diac_sentences:
fout.write(sentence.encode('utf-8'))
... | [
"def read_file(self):\n\n\t\twith open(self.filename, 'r') as f:\n\t\t\tfor line in f:\n\t\t\t\tline = ' '.join(word[0].upper() + word[1:] for word in line.split())\n\t\t\t\tprint line",
"def load_text (file_name, directory_name):\n with open(directory_name+file_name, encoding=ENCODING) as f:\n string =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds a padding zero to the image number in the file names of the downloaded MSFC imagery to aid in sorting | def renum_images(dir_path, img_num=1):
fnames = sort_files(dir_path)
for f in fnames:
# Add padding zero to image number if applicable
new_img_num = str(img_num).zfill(3)
# Construct the original absolute path for the image file
dir_old = os.path.join(dir_path,... | [
"def prefixed(filename, i, digits):\n s = str(i)\n prefix = \"0\"*(max(0,digits-len(s))) + s + \"_\"\n return prefix + filename",
"def sort_key_for_filenames(filename):\n if filename[0].isdigit():\n #starts with digit\n digits = FIND_LEADING_DIGITS.findall(filename)[0]\n postfix =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Download the image files using wget and a file containing the image names on the MSFC server | def fetch_imgs(fname_file, out_dir):
base_url = 'https://weather.msfc.nasa.gov'
cmd = 'wget -B {0} -P {1} -i {2}'.format(base_url, out_dir, fname_file)
out_bytes = subprocess.check_output(cmd.split())
print(out_bytes) | [
"def download_image(imageList, name, ddir):\n for i, image in enumerate(imageList):\n wget.download(image, out= ddir + str(name + '_' +str(i)) + '.jpg')",
"def download_images(self):\n \n if not os.path.exists(self.images_folder):\n os.makedirs(self.images_folder)\n p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds a command to the DB | def add_cmd(cls, session, command):
cmd = cls(
start_time=command["Start"],
end_time=command["End"],
success=command["Success"],
target_id=command["Target"],
plugin_key=command["PluginKey"],
modified_command=command["ModifiedCommand"].strip... | [
"def add_command(cls, cmd):\n cls._commands.append(cmd)",
"def addCommand(self, command):\n self.commands.append(command)",
"def add_cmd(self, cmd):\n self._cmds.append(cmd)",
"def _insertion_command(cls) -> str:\n return sql.Metacard.insert()",
"def add_command(self, command_typ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Delete the command from the DB | def delete_cmd(cls, session, command):
command_obj = session.query(Command).get(command)
session.delete(command_obj)
session.commit() | [
"def delete(self, sql):",
"def delete_record():",
"def delete(self, conn: Conexao, comandoPersonalizado: ComandoPersonalizado):",
"def test_command_delete(self):\n pass",
"def delete(self):\n action = self.daofactory(classname=\"Workflow.Delete\")\n action.execute(id=self.id, conn=self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reallocate seat for an existing passenger | def re_allocate_seat(self, old_seat, new_seat, passenger):
old_row, old_letter = self._parse_seat(old_seat)
if self._seating[old_row][old_letter] != passenger:
raise ValueError(f"Old Seat Error. {passenger} does not occupy seat {old_seat}")
self.allocate_seat(new_seat, passenger)
... | [
"def allocate_seat(self, seat, passenger):\n rows, seatletter = self._aircraft.seating()\n letter = seat[-1] #taking the letter from the seat\n if letter not in seatletter:\n raise ValueError(\"invalid seat letter\".format(letter))\n rowtext = seat[:-1]\n try:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns total number of seats in the aircraft. | def total_seats(self):
return self._aircraft.total_seats() | [
"def num_available_seats(self):\n return sum(sum(1 for s in row.values() if s is None)\n for row in self.seating() if row is not None)",
"def get_remainig_seat(self):\n count = 0\n\n for seat in self.seats:\n if not seat.is_booked:\n count += 1\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns total number of available seats in the aircraft. | def num_available_seats(self):
return sum(sum(1 for s in row.values() if s is None)
for row in self.seating() if row is not None) | [
"def total_seats(self):\n return self._aircraft.total_seats()",
"def get_remainig_seat(self):\n count = 0\n\n for seat in self.seats:\n if not seat.is_booked:\n count += 1\n\n return count",
"def total_available(self):\n return self._total_available",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the list with all available seats in the aircraft. | def free_seats(self):
rows, seat_letters = self._aircraft.seating_plan()
free_seats = [None] + [{letter: None for letter in seat_letters if self._seating[_][letter] is None}
for _ in rows if _ is not None]
return free_seats | [
"def setOfEmptySeats(self):\n emptySeats = set()\n for seatNumber, player in self.seats.items():\n if player is None:\n emptySeats.add(seatNumber)\n return emptySeats # as a list of seat numbers, e.g. [2, 3, 5, 8, 9]",
"def _passenger_seats(self):\n row_number... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Send boarding card to be printed in a specified format. | def make_boarding_card(self, card_printer):
for passenger, seat in sorted(self._passenger_seats()):
card_printer(passenger, seat, self.number(), self.aircraft_model()) | [
"def write_card(self, size: int=8, is_double: bool=False) -> str:\n card = self.raw_fields()\n if size == 8:\n return self.comment + print_card_8(card)\n if is_double:\n return self.comment + print_card_double(card)\n return self.comment + print_card_16(card)",
"d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns tupples (passenger_name, allocated_seat) | def _passenger_seats(self):
row_numbers, seats_letters = self._aircraft.seating_plan()
for row in row_numbers:
for letter in seats_letters:
passenger = self._seating[row][letter]
if passenger is not None:
yield (passenger, f"{row}{letter}") | [
"def allocate_seat(self, seat, passenger):\n rows, seatletter = self._aircraft.seating()\n letter = seat[-1] #taking the letter from the seat\n if letter not in seatletter:\n raise ValueError(\"invalid seat letter\".format(letter))\n rowtext = seat[:-1]\n try:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Allow the input to work as a decorator. | def __call__(self, *args, **kwargs):
super().__call__(*args, **kwargs)
if not self.resource:
logger.warning("Used KafkaInput as a decorator without specifying the resource")
return self | [
"def passthrough_decorator(f):\n return f",
"def decorate(self, func):\n if not callable(func):\n raise TypeError('Cannot decorate a non callable object \"{}\"'\n .format(func))\n self.decorated = func",
"def _decorated_func(self, instance=None):\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sum of a dict of values | def sum_dict(self, dict_values):
total_sum = 0
if dict_values:
for key in dict_values.keys():
total_sum += dict_values[key]
else:
print("\n\n INVALID DICTIONARY")
return total_sum | [
"def dictionary_sum(self):\r\n values = self.expenses.values()\r\n total=sum(values)\r\n return total",
"def sum_dicts(dicts):\r\n # Sum repeated entries.\r\n sum_dict = {}\r\n for val_dict in dicts:\r\n for id_, value in val_dict.items():\r\n if id_ in sum_dict:\r\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sum of a list of values | def sum_list(self, list_values):
total_sum = 0
for value in list_values:
total_sum += value
return total_sum | [
"def sum(xs):\r\n return reduce(add, xs)",
"def sum(self, values):\n return sum(values)",
"def sum_list(l):\n return reduce(operator.add, l)",
"def _list_sum(l):\n return reduce(lambda x, y: x+y, l, 0)",
"def sum_list(numbers: list) -> int:\n\n return sum(numbers)",
"def ll_sum(list):\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates the DeclarationsHolder from a class definition. Takes into account all public attributes and OrderedDeclaration instances; ignores all attributes starting with '_'. Returns a dict containing all remaining elements. | def update_base(self, attrs):
remaining = {}
for key, value in attrs.iteritems():
if isinstance(value, OrderedDeclaration):
self._ordered[key] = value
elif not key.startswith('_'):
self._unordered[key] = value
else:
rema... | [
"def convertClassToDict(clazz):\r\n properties = {}\r\n for prop,val in clazz.__dict__.iteritems():\r\n #omit private fields\r\n if not prop.startswith(\"_\"):\r\n properties[prop] = val\r\n\r\n return traverseDict(properties)",
"def copy_declarations_to_init(self, process: Proce... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
decode a json string to a user | def userFromJsonStr(json_str):
dct = json.loads(json_str)
should_continue = True
extra_params_consumer = getattr(settings, 'EXTRA_PARAMS_CONSUMER', None)
if extra_params_consumer:
extra_params_consumer = get_callable(extra_params_consumer)
should_continue, user =... | [
"def from_json(obj: Dict[str, str]) -> Any:\n if \"type\" in obj and obj[\"type\"] == \"User\":\n return User(\n type=obj[\"type\"],\n id=obj[\"id\"],\n first_name=obj[\"firstName\"],\n last_name=obj[\"lastName\"],\n email=... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Shortcut for combined list of connections from `inboundConnections` and `outboundConnections` dicts | def connections(self):
return self.inboundConnections.values() + self.outboundConnections.values() | [
"def consolidate_connections(connections_list):\n\n\t# Sort list (optional)\n\tconnections_list.sort(key=(lambda x: (x['from'], x['to']) ))\n\n\t# Remove self loops\n\tfor i in reversed(range(0,len(connections_list))):\n\t\tif (connections_list[i]['from'] == connections_list[i]['to']):\n\t\t\tdel(connections_list[i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Shortcut for list of connections having fullyEstablished == True | def establishedConnections(self):
return [
x for x in self.connections() if x.fullyEstablished] | [
"async def wait_until_connections_change(self) -> None:\n ...",
"def get_connections(self):\n return self.connections",
"def get_connections_list() -> list[models.DatabaseConnection]:\n\n return list(get_connections_map().values()) or []",
"def get_all(self):\n\t\treturn self.all_connecti... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
What IP are we supposed to be listening on? | def getListeningIP():
if BMConfigParser().safeGet(
"bitmessagesettings", "onionhostname").endswith(".onion"):
host = BMConfigParser().safeGet(
"bitmessagesettings", "onionbindip")
else:
host = '127.0.0.1'
if (
BMConfigParser().s... | [
"def show_ip(): #TODO\n pass",
"def get_ipaddr():\n return get('https://api.ipify.org').text",
"def _recv_ip(self):\n with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock: # UDP\n # Allow the address to be re-used for when running multiple\n # components on the same ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decorator that takes a write lock. | def WriteLock(f):
def new_f(self, *args, **kwargs):
with self._lock.write_lock():
return f(self, *args, **kwargs)
return new_f | [
"def needs_write_lock(func):\n def locked(self, *args, **kwargs):\n self.lock_for_write()\n try:\n return func(self, *args, **kwargs)\n finally:\n self.unlock()\n locked.__doc__ = func.__doc__\n locked.__name__ = func.__name__\n return locked",
"def _sync_loc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns ondisk path to the cached item. | def path(self):
return self._cache._GetKeyPath(self.key) | [
"def cachepath(self):\n return self.fs.cachepath(self.url)",
"def get_cache_path(self):\n return self._recon.get_cache_path()",
"def get_cache_location(self):\n if self.cache_in_memory:\n return False\n else:\n filename = self.cache_path if \\\n s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Assigns default_path if the entry doesn't exist. | def SetDefault(self, default_path, lock=False):
if not self._Exists():
self._Assign(default_path)
if lock:
self._ReadLock() | [
"def get_default_path(self, default_path=''):\n return default_path if default_path else os.path.dirname(self.last_path)",
"def get_default_path(self, default_path=''):\n return default_path if default_path else os.path.dirname(self.last_im_path)",
"def setDefault(self,path):\n _exc.checkSt... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Inserts a file containing |text| into the cache. | def _InsertText(self, key, text):
with self._TempDirContext() as tempdir:
file_path = os.path.join(tempdir, 'tempfile')
osutils.WriteFile(file_path, text)
self._Insert(key, file_path) | [
"def put_text(self, key, text):\n parent_directory = os.path.dirname(key)\n mkdir_parents(parent_directory)\n with open(key, \"w\") as fh:\n fh.write(text)",
"def _Insert(self, key, url):\n o = urlparse.urlparse(url)\n if o.scheme in ('file', ''):\n DiskCache._Insert(sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a reference to a given key. | def Lookup(self, key):
return CacheReference(self, key) | [
"def refLookup(key):\n try:\n return pyformex.refcfg[key]\n except:\n pyformex.debug(\"!There is no key '%s' in the reference config!\"%key)\n return None",
"def get_reference(dic):\n\n service = get_service(dic)\n reference = service.reference\n\n return reference",
"async d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Insert a remote file into the cache. | def _Insert(self, key, url):
o = urlparse.urlparse(url)
if o.scheme in ('file', ''):
DiskCache._Insert(self, key, o.path)
return
with tempfile.NamedTemporaryFile(dir=self.staging_dir,
delete=False) as local_path:
self._Fetch(url, local_path.name)
... | [
"def _Insert(self, key, tarball_path):\n with osutils.TempDir(prefix='tarball-cache',\n base_dir=self.staging_dir) as tempdir:\n\n o = urlparse.urlsplit(tarball_path)\n if o.scheme == 'file':\n tarball_path = o.path\n elif o.scheme:\n url = tarball_path\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Insert a tarball and its extracted contents into the cache. Download the tarball first if a URL is provided as tarball_path. | def _Insert(self, key, tarball_path):
with osutils.TempDir(prefix='tarball-cache',
base_dir=self.staging_dir) as tempdir:
o = urlparse.urlsplit(tarball_path)
if o.scheme == 'file':
tarball_path = o.path
elif o.scheme:
url = tarball_path
tarball_pat... | [
"def _Insert(self, key, url):\n o = urlparse.urlparse(url)\n if o.scheme in ('file', ''):\n DiskCache._Insert(self, key, o.path)\n return\n\n with tempfile.NamedTemporaryFile(dir=self.staging_dir,\n delete=False) as local_path:\n self._Fetch(url, local_pat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Specialized DiskCache._KeyExits that ignores empty directories. The normal _KeyExists just checks to see if the key path exists in the cache directory. Many tests mock out RunCommand then fetch a tarball. The mock blocks untarring into it. This leaves behind an empty dir which blocks future untarring in nontest scripts... | def _KeyExists(self, key):
# Wipe out empty directories before testing for existence.
key_path = self._GetKeyPath(key)
try:
os.rmdir(key_path)
except OSError as ex:
if ex.errno not in (errno.ENOTEMPTY, errno.ENOENT):
raise
return os.path.exists(key_path) | [
"def test_cache_miss(runner: CliRunner):\n assert cache.get(\"missing key\") is None",
"def test_cannot_make_cache(self, _):\n os.environ['XDG_CACHE_HOME'] = \"/does/not/exists\"\n\n # Make sure it raises an unable to create cache exception\n with self.assertRaises(UnableToCreateCache):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reads the metadata.txt file to read in the schema of the database. Each table in database is stored in | def get_meta_info(self):
try:
info_file = open('metadata.txt', 'r')
except FileNotFoundError:
print("metadata.txt not found")
else:
table_started = False
table_name = ""
for ro in info_file:
if ro.strip() == '<begin_tabl... | [
"def parse_metadata():\n\n with open(\"metadata.txt\", \"r\") as f:\n tables_data = f.read().split(\"<begin_table>\\n\")\n\n # first entry of tables_data is empty\n del tables_data[0]\n\n for table_data in tables_data:\n \"\"\"\n table_data will look like the... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fills in the content in the database | def fill_content(self):
# First delete those tableInfo entries whose corresponding files are not present
to_be_remove = []
for table in self.tableInfo.keys():
if not os.path.isfile(str(table) + ".csv"):
to_be_remove.append(table)
for table in to_be_remove:
... | [
"def populate_database(self):\n self.dye_stocks.add_new_dye_stocks()\n self.detections.add_new_detections()\n self.profiles.add_new_profiles()",
"def fill_database_with_verbs_and_forms(self):\n\n self.dbCursor.execute(\"\"\"SELECT count(verb) FROM Main\"\"\")\n number_of_verbs =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gives the aggregate function 'fun' on 'table' for 'column' | def aggregate(self, table, column, fun, grouped_column=None, valu=None):
if column == '*':
column = next(iter(table)) # this takes care of COUNT(*), because we can safely replace column with
# first key i.e a column of table here
if column not in table.keys():
raise ... | [
"def calculate_aggregate_value(func, column):\n if func == \"min\":\n return min(column)\n elif func == \"max\":\n return max(column)\n elif func == \"avg\":\n return sum(column) / len(column)\n elif func == \"sum\":\n return sum(column)",
"def _evaluate_aggregate(self, fun... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
parses the sql query and raise exceptions if it is not correct syntactically | def parse(self):
if self.query[-1] != ';':
raise NotImplementedError("Semicolon missing")
self.query = self.query[:-1]
keywords = self.separator()
self.fill_dict(keywords)
if len(self.info["tables"]) == 0:
raise NotImplementedError("Syntax error in SQL que... | [
"def parse_query(self, sql):\n return process_sql.get_sql(self.spider_schema, sql)",
"def checkQuery(args):\n query = args['query']\n # default values for dict\n queryitems = {\n 'select': None,\n 'from': None,\n 'where': None,\n 'wherenot': None,\n 'whereop': No... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |