query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Loads the optimizer configuration and parameters from an XML tree. | def fromXml(xmlDoc, plant, orderList, simulator, evaluator):
optimizer = Optimizer(plant, orderList, simulator, evaluator)
element = xmlDoc.getElementsByTagName("optimizer")
# there should only be 1 optimizer node in the XML tree!
assert len(element) == 1
element = element[0]
# load the different attr... | [
"def fromXmlFile(filename, plant, orderList, simulator, evaluator):\n\t\tfile = open(filename, \"r\")\n\t\tdoc = minidom.parse(file)\n\t\toptimizer = Optimizer.fromXml(doc, plant, orderList, simulator, evaluator)\n\t\tfile.close()\n\t\treturn optimizer",
"def loadXML(self):\n if self.currentFileName is Non... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Loads the optimizer configuration and parameters from an XML tree. | def fromXmlFile(filename, plant, orderList, simulator, evaluator):
file = open(filename, "r")
doc = minidom.parse(file)
optimizer = Optimizer.fromXml(doc, plant, orderList, simulator, evaluator)
file.close()
return optimizer | [
"def fromXml(xmlDoc, plant, orderList, simulator, evaluator):\n\t\toptimizer = Optimizer(plant, orderList, simulator, evaluator)\n\t\telement = xmlDoc.getElementsByTagName(\"optimizer\")\n\t\t\n\t\t# there should only be 1 optimizer node in the XML tree!\n\t\tassert len(element) == 1\n\t\telement = element[0]\n\t\t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sorts the population based on fitness, to have the better individuals at the beginning of the population list. | def sortPopulation(self, population):
population.sort(lambda a, b: cmp(b.fitness, a.fitness)) | [
"def sort_population(self):\n self.population.sort(key=lambda x: x.fitness, reverse=True)",
"def sort_population(self, optargs):\n self.evaluate_population(optargs)\n self.population.sort(key=lambda individual: individual.fitness)",
"def sort_by_fitness(population):\n\n population.sort(k... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Mutates a population. Selects the best n individuals (based on the selectionRate) to mutate (maybe they'll give us even better individuals!). After mutating an individual, it checks if we have an individual that is similar to the mutated one, if so, then try to mutate again, otherwise, we simply calculate its fitness a... | def mutatePopulation(self, population):
for i in range(int(math.ceil(self.selectionRate * len(population)))):
mutatedIndiv = self.mutateIndividual(population[i])
while self.isIndividualInPopulation(mutatedIndiv, population) == True:
mutatedIndiv = self.mutateIndividual(population[i])
self.calcIndividualF... | [
"def genetic_algorithm(population, sack, NumIterations, MaxWeight):\n for i in range(NumIterations):\n new_generation = member_crossover(population)\n for member in new_generation:\n population.append(member)\n population = population_selection(population, sack, MaxWeight)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if an individual is in a population. | def isIndividualInPopulation(self, individual, population):
for i in population:
if i == individual:
return True
return False | [
"def __eq__(self, population):\n return self.chromosome_list == population.chromosome_list",
"def infected_present(self):\n for x in self.population.flatten():\n if x.state == State.infected:\n return True\n return False",
"def __contains__(self, item):\n fo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets a value and returns a mutation of it based on the mutation range. | def mutateGene(self, value):
addent = int(random.uniform(0, self.mutationRange))
if (random.uniform(0, 1) < 0.5):
addent = -addent
return max(0, value + addent) | [
"def mutate(self, mutation_range, mutation_rate, context):\n return NotImplemented",
"def _mutation(self, chromosome):\n return chromosome.mutate()",
"def mutation(self, i: int) -> Character:\n chance = random.uniform(0, 1)\n if chance <= self.mutation_rate:\n return self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates an initial individual based on order deadlines minimum processing time. Account whether an order has a current machine and current overtime. | def initialIndividual(self):
indiv = Schedule()
for o in self.orderList.orders:
if o.currentMachine == "":
minProcTime = o.recipe.calcMinProcTime(self.plant)
machineName = o.recipe.recipe[0][0]
else:
machineName = o.currentMachine
minProcTime = o.recipe.calcMinProcTime(self.plant, o.current... | [
"def _set_first_gen(self) -> None:\r\n # Create the floor if FIRST_GEN, but not if it's in progress\r\n if self.state == States.FIRST_GEN:\r\n self.floor = Floor(self.world)\r\n\r\n # We are now in progress of creating the first gen\r\n self.state = States.FIRST_GEN_IN_PROGRES... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read the FOX news comments dataset | def read_fox_comments_dataset():
with open("../data/fox-news-comments.json") as f:
df = pd.DataFrame([json.loads(line) for line in f.readlines()])
# Remove irrelevant columns
for col_name in ["title", "succ", "meta", "user", "mentions", "prev"]:
del df[col_name]
return df | [
"def _readComments(self): \n self.NSCOML = nappy.utils.text_parser.readItemFromLine(self.file.readline(), int)\n self._readSpecialComments()\n self.NNCOML = nappy.utils.text_parser.readItemFromLine(self.file.readline(), int)\n self._readNormalComments()",
"def getAllComments():"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Applies a directional scaling to a set of vectors. An example usage for this is to flatten a mesh against a single plane. Direction MUST be normalised prior to this call. | def apply_direction_scale( vectors, direction, scale ):
"""
scaling is defined as:
[p'][1 + (k - 1)n.x^2, (k - 1)n.x n.y^2, (k - 1)n.x n.z ]
S(n,k) = [q'][(k - 1)n.x n.y, 1 + (k - 1)n.y, (k - 1)n.y n.z ]
[r'][(k - 1)n.x n.z, (k - 1)n.y n.z, 1 + (k - 1)n.z^2 ]
where:
v' ... | [
"def apply_scale( vectors, scale ):\n # create a scaling matrix\n matrix = numpy.array([\n [ scale[ 0 ], 0.0, 0.0 ],\n [ 0.0, scale[ 1 ], 0.0 ],\n [ 0.0, 0.0, scale[ 2 ] ]\n ])\n return numpy.dot( vectors, matrix )",
"def scale_vectors(vectors, f):\n return [scale_vector(ve... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Applies a 3 dimensional scale to a set of vectors. | def apply_scale( vectors, scale ):
# create a scaling matrix
matrix = numpy.array([
[ scale[ 0 ], 0.0, 0.0 ],
[ 0.0, scale[ 1 ], 0.0 ],
[ 0.0, 0.0, scale[ 2 ] ]
])
return numpy.dot( vectors, matrix ) | [
"def scale(s, vectors):\n return [scalar_product(s, v) for v in vectors]",
"def scale_vectors(vectors, f):\n return [scale_vector(vector, f) for vector in vectors]",
"def apply_scale( vertices, scale=1.0 ):\n checkVerticesValidity( vertices )\n if type(scale) != float:\n raise ValueError\n \... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get extras for a gym.envs.toy_text.nchain.NChainEnv | def nchain_extras(env, gamma=0.99):
# How to handle <TimeLimit<______>> and other Wrappers?
# assert isinstance(env, gym.envs.toy_text.nchain.NChainEnv)
# Action constants
A_FORWARD = 0
A_BACKWARD = 1
states = np.arange(env.observation_space.n)
actions = np.arange(env.action_space.n)
... | [
"def _create_extra_environment(self):\n return {}",
"def extra_options():\n extra_vars = {\n 'shared_libs': [None, \"Deprecated. Use build_shared_libs\", CUSTOM],\n 'openmp': [True, \"Enable OpenMP support\", CUSTOM],\n 'all_exts': [True, \"Enable all Trilinos packag... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set vacancy probabilities uniformly to 1 / cardinality of vacancy difference values | def set_uniform_probabilities(self, sentence_aligned_corpus):
max_m = longest_target_sentence_length(sentence_aligned_corpus)
# The maximum vacancy difference occurs when a word is placed in
# the last available position m of the target sentence and the
# previous word position has no v... | [
"def set_probablity(self, probablity, values):\n if self.is_root():\n value = values[0]\n\n self.distribution.set(probablity, [value])\n self.distribution.set(1 - probablity, [not value])\n\n else:\n self.distribution.set(probablity, values)",
"def update_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sample the most probable alignments from the entire alignment space according to Model 4 Note that Model 4 scoring is used instead of Model 5 because the latter is too expensive to compute. First, determine the best alignment according to IBM Model 2. With this initial alignment, use hill climbing to determine the best... | def sample(self, sentence_pair):
sampled_alignments, best_alignment = super().sample(sentence_pair)
return self.prune(sampled_alignments), best_alignment | [
"def hillclimb(self, alignment_info, j_pegged=None):\n alignment = alignment_info # alias with shorter name\n max_probability = IBMModel4.model4_prob_t_a_given_s(alignment, self)\n\n while True:\n old_alignment = alignment\n for neighbor_alignment in self.neighboring(alig... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes alignments from ``alignment_infos`` that have substantially lower Model 4 scores than the best alignment | def prune(self, alignment_infos):
alignments = []
best_score = 0
for alignment_info in alignment_infos:
score = IBMModel4.model4_prob_t_a_given_s(alignment_info, self)
best_score = max(score, best_score)
alignments.append((alignment_info, score))
thr... | [
"def clean_alignment(alignment):\n site_length = len(alignment[:, 0])\n cleaned_alignment = Align.MultipleSeqAlignment(\n [seq[:0] for seq in alignment])\n\n if args.n_ratio:\n logging.info(f\"Removing sites with > {int(args.n_ratio * 100)}% of \"\n + f\"N's from '{alignme... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Starting from the alignment in ``alignment_info``, look at neighboring alignments iteratively for the best one, according to Model 4 Note that Model 4 scoring is used instead of Model 5 because the latter is too expensive to compute. There is no guarantee that the best alignment in the alignment space will be found, be... | def hillclimb(self, alignment_info, j_pegged=None):
alignment = alignment_info # alias with shorter name
max_probability = IBMModel4.model4_prob_t_a_given_s(alignment, self)
while True:
old_alignment = alignment
for neighbor_alignment in self.neighboring(alignment, j_pe... | [
"def find_best_alignment(query, targets):\n score = 0\n best_ali = None\n for target in targets:\n for strict_ali in Bio.pairwise2.align.globalxx(query, target, one_alignment_only=True):\n if int(strict_ali[2]) == len(query):\n for proper_ali in Bio.pairwise2.align.globalms... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method that close a connection | def closeConnection(connection):
connection.close() | [
"def close_connection(self):\n\n self._connection.close()\n print(\"Closed connection....\")",
"def closeConnection(self):\n print(\"closing connection...\")\n self.s.close()\n quit()",
"def close_connection(self):\r\n if self.conn:\r\n self.conn.close()",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method that reads the possible names from a file | def readNames():
namesRead = []
with open("Files/Names.txt", 'r', encoding='utf8') as f:
for line in f:
if line == "\n":
continue
namesRead.append(line.rstrip('\n').rstrip().lstrip())
f.close()
return namesRead | [
"def load_names_from_txt(file_like, onerror=\"raise\"):\n if onerror not in (\"pass\", \"raise\", \"warn\"):\n raise ValueError(\"value for onerror keyword not understood\")\n\n bad_names = set()\n names = set()\n for name in file_like:\n name = name.strip()\n if name:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method that reads the possible surnames from a file | def readSurnames():
surnamesRead = []
with open("Files/Surnames.txt", 'r', encoding='utf8') as f:
for line in f:
if line == "\n":
continue
surnamesRead.append(line.rstrip('\n').rstrip().lstrip())
f.close()
return surnamesRead | [
"def generate_surnames():\r\n surnames = read_file(surnames_file,'\\t|\\n')\r\n surnames_list = convert_to_list(surnames, 4)\r\n return surnames_list",
"def load_surnames():\n dict_ = {}\n file_name = \"surnames.txt\"\n unpacked = load_config_from_file(CONFIGS_PATH, file_name)\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method that reads the possible vaccines from a file | def readVaccines():
vaccinesRead = []
with open("Files/Vaccines.txt", 'r', encoding='utf8') as vaccine_file:
for vaccine_lines in vaccine_file:
vaccineDetails = vaccine_lines.split(",")
details = []
for vaccineDetail in vaccineDetails:
details.append(... | [
"def read_candidates(file_path):\n pass",
"def read(filename):\n f = open('%s/files/%s.babel' % (projdir, filename))\n string = f.read()\n tokens = scan(string)\n for t in tokens:\n print(t)",
"def parse_file(self, path):\r\n return self._parse(antlr3.ANTLRFileStream(path))",
"def rea... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method that finds all the nodes Person in the data base | def findAllPerson(tx):
query = (
"MATCH (p:Person) "
"RETURN p , ID(p);"
)
results = tx.run(query).data()
return results | [
"def get_all_persons(self):\r\n return self.__person_repository.elements",
"def get_people(self):\n cursor = self.cur()\n cursor.execute('SELECT * FROM {tn} '.format(tn=\"person\"))\n all_people = cursor.fetchall()\n return all_people",
"def get_all():\n with database()... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method that finds all the nodes House in the data base | def findAllHome(tx):
query = (
"MATCH (h:House) "
"RETURN h , ID(h);"
)
results = tx.run(query).data()
return results | [
"def fetch_nodes(self):\n nodes = []\n\n node_query = \"SELECT Node from nodes\"\n\n raw_result = self.sql_select_query(node_query)\n\n for row in raw_result:\n if 'host' in row[0]:\n nodes.append(self.fetch_host_info(row[0]))\n else:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method that finds all the nodes Location in the data base | def findAllLocation(tx):
query = (
"MATCH (l:Location) "
"RETURN l , ID(l);"
)
results = tx.run(query).data()
return results | [
"def get_all_locations(self):",
"def locations(self):\n\t\tresult_list = []\n\n\t\tfor ancestryPerson in AncestryRelation.objects.filter(ancestry=self):\n\t\t\tperson = ancestryPerson.person\n\n\t\t\tif person.birth_location is not None:\n\t\t\t\tresult_list.append(LocationInfo(person.birth_location.lon, person.b... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method that finds all the nodes Vaccine in the data base | def findAllVaccine(tx):
query = (
"MATCH (v:Vaccine) "
"RETURN v , ID(v);"
)
results = tx.run(query).data()
return results | [
"def findAllGetVaccineRelationships(tx):\n query = (\n \"MATCH (n1:Person)-[r:GET_VACCINE]->(n2:Vaccine) \"\n \"RETURN ID(n1) , r , r.date , r.country , r.expirationDate , ID(n2);\"\n )\n results = tx.run(query).data()\n return results",
"def get_all_nodes(self):\n pass",
"def r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method that finds all the nodes Test in the data base | def findAllTest(tx):
query = (
"MATCH (t:Test) "
"RETURN t , ID(t);"
)
results = tx.run(query).data()
return results | [
"def getNodeTests():\n\n nodeTestsQuery = NodeTest.query.all()\n \n if nodeTestsQuery: \n nodeTestList = []\n for nodeTestQuery in nodeTestsQuery:\n nodeTestList.append(nodeTestQueryToObject(nodeTestQuery))\n return nodeTestList\n else:\n return None",
"def tes... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method that finds all Live relationships in the data base | def findAllLiveRelationships(tx):
query = (
"MATCH (n1:Person)-[r:LIVE]->(n2:House) "
"RETURN ID(n1) , r , ID(n2);"
)
results = tx.run(query).data()
return results | [
"def get_relationships(self):\n raise NotImplementedError(\n 'operation get_relationships(...) not yet implemented')",
"def relationships(self):",
"def getRelationships(self):\n text = self.generateRequest('/v2.1/Relationships', 'GET', '')\n return self.dictToList(json.loads(text... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method that finds all App_Contact relationships in the data base | def findAllAppContactRelationships(tx):
query = (
"MATCH (n1:Person)-[r:APP_CONTACT]->(n2:Person) "
"RETURN ID(n1) , r , r.date , r.hour, ID(n2);"
)
results = tx.run(query).data()
return results | [
"def get_relations(self):\n return self.client.call('GET', 'contact_relation', {})",
"def get_all_contacts(self):\n self.init_db(self._testing)\n\n query = \"SELECT {} FROM {} ORDER BY id;\".format(\", \".join(Contact.columns_with_uid), Contact.table_name)\n\n data = self.db.conn.execu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method that finds all VISIT relationships in the data base | def findAllVisitRelationships(tx):
query = (
"MATCH (n1:Person)-[r:VISIT]->(n2:Location) "
"RETURN ID(n1) , r , r.date , r.start_hour , r.end_hour , ID(n2);"
)
results = tx.run(query).data()
return results | [
"def relationships(self):",
"def get_relationships(self):\n raise NotImplementedError(\n 'operation get_relationships(...) not yet implemented')",
"def findAllLiveRelationships(tx):\n query = (\n \"MATCH (n1:Person)-[r:LIVE]->(n2:House) \"\n \"RETURN ID(n1) , r , ID(n2);\"\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method that finds all GET (a vaccine) relationships in the data base | def findAllGetVaccineRelationships(tx):
query = (
"MATCH (n1:Person)-[r:GET_VACCINE]->(n2:Vaccine) "
"RETURN ID(n1) , r , r.date , r.country , r.expirationDate , ID(n2);"
)
results = tx.run(query).data()
return results | [
"def get_relationships(self):\n raise NotImplementedError(\n 'operation get_relationships(...) not yet implemented')",
"def getRelationships(self):\n text = self.generateRequest('/v2.1/Relationships', 'GET', '')\n return self.dictToList(json.loads(text))",
"def findAllVaccine(tx)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method that finds all MAKE (a test) relationships in the data base | def findAllMakeTestRelationships(tx):
query = (
"MATCH (n1:Person)-[r:MAKE_TEST]->(n2:Test) "
"RETURN ID(n1) , r , r.date , r.hour , r.result , ID(n2);"
)
results = tx.run(query).data()
return results | [
"def relationships(self):",
"def test_get_relationship_templates(self):\n pass",
"def test_get_relations():\n with get_fixture_uri((\n 'collections/artists.json',\n 'collections/albums.json',\n 'collections/tracks.json'\n )) as (\n artists_uri,\n albums_uri,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method that finds all INFECTED relationships in the data base | def findAllInfectedRelationships(tx):
query = (
"MATCH (n1:Person)-[r:COVID_EXPOSURE]->(n2:Person) "
"RETURN ID(n1) , r , r.date , r.name , ID(n2);"
)
results = tx.run(query).data()
return results | [
"def get_relationships(self):\n raise NotImplementedError(\n 'operation get_relationships(...) not yet implemented')",
"def relationships(self):",
"def related_intenions(self):\n return self._related_intenions",
"def get_all_relationship(self, include_properties=False):\n raise... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method that creates the query for the creation of the vaccines node | def createNodeVaccines(vaccinesList):
vaccinesQuery = []
for vaccineEl in vaccinesList:
currentQuery = (
"CREATE (v:Vaccine {name: \"" + str(vaccineEl[int(VaccineAttribute.NAME)]) + "\" , producer: \"" +
str(vaccineEl[int(VaccineAttribute.PRODUCER)]) + "\"}); "
)
... | [
"def bv(query):\n return biovelo(query)",
"def buildQuery():",
"def construct_query(self):\n raise NotImplementedError() # override this method",
"def createRelationshipsGetVaccine(d, pIds, vIds):\n # Choose how many new visit relationships\n numberOfVaccines = MAX_NUMBER_OF_VACCINE\n\n fo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method that creates VISIT relationships | def createRelationshipsVisit(d, pIds, lIds):
# Choose how many new visit relationships
numberOfVisits = MAX_NUMBER_OF_VISIT
for _ in range(0, numberOfVisits):
lIndex = randint(0, len(lIds) - 1)
locationId = lIds[lIndex]
pIndex = randint(0, len(pIds) - 1)
personId = pIds[pInd... | [
"def relationships(self):",
"def new_visit(self, context):\n with context.resource.entity_set.get_target(\n 'Visits').open() as collection:\n visit = collection.new_entity()\n visit['Permissions'].set_from_value(context.permissions)\n visit['Resource'].bind_e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method that creates GET vaccine relationships | def createRelationshipsGetVaccine(d, pIds, vIds):
# Choose how many new visit relationships
numberOfVaccines = MAX_NUMBER_OF_VACCINE
for _ in range(0, numberOfVaccines):
vIndex = randint(0, len(vIds) - 1)
vaccineId = vIds[vIndex]
pIndex = randint(0, len(pIds) - 1)
personId =... | [
"def findAllGetVaccineRelationships(tx):\n query = (\n \"MATCH (n1:Person)-[r:GET_VACCINE]->(n2:Vaccine) \"\n \"RETURN ID(n1) , r , r.date , r.country , r.expirationDate , ID(n2);\"\n )\n results = tx.run(query).data()\n return results",
"def findAllVaccine(tx):\n query = (\n \... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method that creates MAKE test relationships | def createRelationshipsMakeTest(d, pIds, tIds):
# Choose how many new visit relationships
numberOfTest = MAX_NUMBER_OF_TEST
for _ in range(0, numberOfTest):
probability = random()
tIndex = randint(0, len(tIds) - 1)
testId = tIds[tIndex]
pIndex = randint(0, len(pIds) - 1)
... | [
"def test_resource_relation_resource_add_relations_post(self):\n pass",
"def findAllMakeTestRelationships(tx):\n query = (\n \"MATCH (n1:Person)-[r:MAKE_TEST]->(n2:Test) \"\n \"RETURN ID(n1) , r , r.date , r.hour , r.result , ID(n2);\"\n )\n results = tx.run(query).data()\n return... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method that executes the query to create a VISIT relationship | def createVisit(tx, query, personId, locationId, date, startHour, endHour):
tx.run(query, personId=personId, locationId=locationId, date=date, startHour=startHour,
endHour=endHour) | [
"def new_visit(self, context):\n with context.resource.entity_set.get_target(\n 'Visits').open() as collection:\n visit = collection.new_entity()\n visit['Permissions'].set_from_value(context.permissions)\n visit['Resource'].bind_entity(context.resource)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method that finds all the positive person | def findAllPositivePerson():
query = (
"""
MATCH (p:Person)-[t:MAKE_TEST{result: \"Positive\"}]->()
WHERE NOT EXISTS {
MATCH (p)-[t2:MAKE_TEST{result: \"Negative\"}]->()
WHERE t2.date > t.date
}
RETURN distinct ID(p) , t.date as infectionDate , t.hour ... | [
"def get_people(solution, samples):\n mask = pd.Series(solution['person covered status']).astype(bool)\n people_covered = pd.Series(samples)[mask].tolist()\n return (people_covered)",
"def search(self, predicate:'function')->'list[Person]':\n people_list = self.get()\n\n result=[]\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method that deletes exposure for people who made a negative test after a covid exposure | def delete_negative_after_exposure():
query = ("match ()-[c:COVID_EXPOSURE]->(p)-[m:MAKE_TEST{result:\"Negative\"}]->(t) "
"where m.date >= c.date + duration({days: 7}) "
"delete c")
with driver.session() as session:
session.run(query) | [
"def delete_exposure(self, expid):\n\n Exposure.objects.filter(exposure_id=expid).delete()",
"def kill_exposure(self):\n out = self.asn_direct.exposures.pop(self.idx)\n out = self.asn_grism.exposures.pop(self.idx)\n self.idx-=1\n self.nexp-=1\n self.goNext()",
"def dele... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method that executes the query to find the infected member of a family | def findInfectInFamily(tx, query, id):
result = tx.run(query, id=id).data()
return result | [
"def search_family(self, family):",
"def test_can_access_family_via_member(self):\n user = db.session.query(User).filter(User.name==\"user1\").one()\n self.assertEqual(len(user.family), 2)",
"def test_familes_have_members(self):\n family1 = db.session.query(Family).filter(Family.name==\"Fam... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method that retrieves all the ids of Person Node | def getPersonIds(withApp=False):
with driver.session() as s:
ids = s.write_transaction(getPersonId, withApp)
pIds = []
for idEl in ids:
pIds.append(idEl["ID(p)"])
return pIds | [
"def get_all_ids(self):\r\n return self.__person_repository.get_all_ids()",
"def findAllPerson(tx):\n query = (\n \"MATCH (p:Person) \"\n \"RETURN p , ID(p);\"\n )\n results = tx.run(query).data()\n return results",
"def get_person_ids(self) -> np.ndarray:\n return self.p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method that retrieves all the ids of Location Node | def getLocationsIds():
with driver.session() as s:
ids = s.write_transaction(getLocationsId)
lIds = []
for idEl in ids:
lIds.append(idEl["ID(l)"])
return lIds | [
"def _get_nodes_ids(self):\n nodes = self._get_nodes()\n nodes_ids = []\n for node in nodes:\n nodes_ids.append(node[\"id\"])\n return nodes_ids",
"def findAllLocation(tx):\n query = (\n \"MATCH (l:Location) \"\n \"RETURN l , ID(l);\"\n )\n results = t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method that retrieves all the ids of test Node | def getTestsIds():
with driver.session() as s:
ids = s.write_transaction(getTestsId)
tIds = []
for idEl in ids:
tIds.append(idEl["ID(t)"])
return tIds | [
"def _get_nodes_ids(self):\n nodes = self._get_nodes()\n nodes_ids = []\n for node in nodes:\n nodes_ids.append(node[\"id\"])\n return nodes_ids",
"def xmlrpc_get_node_ids(self):\n return self.node_info.keys()",
"def listNodeIds(self,ignoreStops=True):\n node... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method use to print the database structure using PlotDBStructure module | def printDatabase():
with driver.session() as s:
personNodes = s.read_transaction(findAllPerson)
houseNodes = s.read_transaction(findAllHome)
locationNodes = s.read_transaction(findAllLocation)
vaccineNodes = s.read_transaction(findAllVaccine)
testNodes = s.read_transaction(f... | [
"def print_db_schema(self): \n raise NotImplementedError(\"Subclasses should overwrite this Method.\")",
"def do_printdb(self, arg):\n print('db_shop TABLES:')\n print(classes.keys())",
"def show_database_structure(self):\n self.analyze()\n items = []\n for model in get... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate PW based on the current state, ie. current chunk, previously computed chunks and the current counter. | def generate_pw(self):
chunks = []
for chunk_no in range(self.CHUNKS):
if chunk_no < self.chunk:
chunks.append(self.verified_chunks[chunk_no])
elif chunk_no == self.chunk:
chunks.append(str(self.counter).zfill(self.PASSWORD_LENGTH /
... | [
"def password_generate(self):\n password = ''\n password_base = self._password_base()\n for _ in range(self.size):\n password += choice(password_base)\n return password",
"async def password_generate_complex(self, ctx):\n await ctx.send(\n \"\".join(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate the delta from the result. Returns a tuple of (delta, confident) Where ``delta`` is either a positive value that has been repeated at the last ``self.confirmations`` times or a negative value indicating an irregular delta. Confident is True if the value also satisfies the extra checks. | def confirm(self, result):
delta = result.source_port - self.last_source_port
self.last_source_port = result.source_port
log.debug("source_port={0}, last_source_port={1}, "
"real_delta={2}".format(
result.source_port, self.last_source_port, delta))
... | [
"def _calculate_difference(self, prev_state, curr_state, reward, last_action, \n terminal):\n future_reward = 0\n if not terminal:\n future_reward = self._get_max_q_value(curr_state)\n\n expected_reward = self._get_q_value(prev_state, last_action)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sends a read request using the specified function byte. Returns a response payload containing the result of the read request; the format of its contents depend on the function byte. | def request_read(self, function_byte: int) -> bytes:
_validate_function_byte(function_byte)
message = [
_BRAVIA_READ_REQUEST_HEADER_BYTE,
_BRAVIA_REQUEST_CATEGORY_BYTE,
function_byte,
0xFF,
0xFF,
]
message.append(_calculate_che... | [
"def reader_from_byte_generator_accepting_function(func):\r\n\r\n return _general_push_pull_adaptor(func, _greenlet_byte_generator)",
"async def i2c_read_request(self, address, register, number_of_bytes,\n read_type, cb=None):\n if address not in self.i2c_map:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sends a write request using the specified function byte and corresponding payload. Does not return a response. | def request_write(self, function_byte: int, payload: Sequence[int]) -> None:
_validate_function_byte(function_byte)
# Length of the payload plus the checksum
message_length_byte = len(payload) + 1
if message_length_byte > 255:
raise ValueError(
f"Payload is t... | [
"def execute_write(function):\n raise NotImplementedError(\"execute_write() has not been implemented\")",
"def send_function(self, command, func):\n func_code = marshal.dumps(func.func_code)\n self.send_command(command, func_code)",
"def perform_write(self, addr, data):\n\t\treturn 0",
"d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function uses self.get_state to find the locations of the robot and ball and returns a number in [0, NUM_STATES) representing that state | def get_state_num(self):
robot_state = self.get_state('turtlebot3_waffle_pi','world')
ball_state = self.get_state('soccer_ball','world')
# each object is in a "box" that is RESOLUTION meters wide.
robot_xbox = np.ceil((robot_state.pose.position.x-Learn.FIELD_XLEFT)/Learn.RESOLUTION)
... | [
"def get_state_arr(self):\n rpos = self.sim.getAgentPosition(self.robot_num)\n rvel = self.sim.getAgentVelocity(self.robot_num)\n rrad = self.sim.getAgentRadius(self.robot_num)\n v_pref = self.sim.getAgentMaxSpeed(self.robot_num)\n theta = math.atan2(rvel[1], rvel[0])\n # R... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given an action in (self.MOVE_LEFT, self.STAY_PUT, self.MOVE_RIGHT], performs that action by moving the turtlebot accordingly. | def apply_action(self, action):
robot_state = self.get_state('turtlebot3_waffle_pi','world')
robot_x = robot_state.pose.position.x
robot_y = robot_state.pose.position.y
# Set the distance moved in an action such that it is at least as large as the
# minimum distance that would le... | [
"def _move(self, action):\n row, col = self.agent.position\n delta_row, delta_col = MOVE_DELTAS[action]\n row, col = row + delta_row, col + delta_col\n\n if self._within_bounds(row, col) and (row, col) not in self.obstacles:\n self.agent.position = (row, col)\n\n # Rend... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Peform the QLearning algorithm until convergence of self.Q | def algorithm(self):
convergence_threshold = 50
reward_num_threshold = 300
alpha = 1
gamma = 0.5
while (self.reward_num < reward_num_threshold) and (self.count<convergence_threshold):
print('------')
print('Iteration', self.reward_num, '/', reward_num_thre... | [
"def q_algorithm(self):\n\n # Loop runs until the Q-matrix has converged and the state is back at 0\n while self.counter < 50 or self.state != 0:\n # Sleep to prevent race conditions.\n rospy.sleep(1.5)\n\n # Select an action at random.\n possible_actions = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a dictionary containing the total score for ``obj`` and the number of votes it's received. Thus, it can be used to calculate the best rated objects in a very simplified scale. This isn't a very good rating function right now, because an object that has got a lot of up and downvotes is a reflection of its popularity... | def get_score(self, obj):
content_type = ContentType.objects.get_for_model(obj)
result = self.filter(content_type=content_type,
object_id=obj._get_pk_val()).aggregate(
score=Sum('vote'),
... | [
"def get_score(self, obj):\n ctype = ContentType.objects.get_for_model(obj)\n result = self.filter(object_id=obj._get_pk_val(),\n content_type=ctype).extra(\n select={\n 'score': 'COALESCE(SUM(vote), 0)',\n 'num_votes': 'COALESCE(COU... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Record a user's vote on a given object. Only allows a given user to vote once, though that vote may be changed. A zero vote indicates that any existing vote should be removed. | def record_vote(self, obj, vote, user):
if vote not in (+1, 0, -1):
raise ValueError('Invalid vote (must be +1/0/-1)')
content_type = ContentType.objects.get_for_model(obj)
# First, try to fetch the instance of this row from DB
# If that does not exist, then it is the first t... | [
"def record_vote(self, obj, user, vote):\r\n if vote not in (+1, 0, -1):\r\n raise ValueError('Invalid vote (must be +1/0/-1)')\r\n ctype = ContentType.objects.get_for_model(obj)\r\n try:\r\n v = self.get(user=user, content_type=ctype,\r\n object_id... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the top N scored objects for a given model. Yields (object, score) tuples. | def get_top(self, model, limit=10, inverted=False):
content_type= ContentType.objects.get_for_model(model)
#Get a queryset of all the objects of the model. Get their scores
results = self.filter(content_type=content_type).values('object_id').annotate(score=Sum('vote'))
if inverted:
... | [
"def get_top(self, Model, limit=10, reversed=False):\n ctype = ContentType.objects.get_for_model(Model)\n query = \"\"\"\n SELECT object_id, SUM(vote) as %s\n FROM %s\n WHERE content_type_id = %%s\n GROUP BY object_id\"\"\" % (\n connection.ops.quote_name('score'... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the vote made on the given object by the given user, or ``None`` if no matching vote exists. | def get_for_user(self, obj, user):
if not user.is_authenticated:
return None
content_object = ContentType.objects.get_for_model(obj)
try:
vote = self.get(voter=user, content_type=content_object, object_id=obj._get_pk_val())
except ObjectDoesNotExist:
... | [
"def get_for_user(self, obj, user):\n\t\tif not user.is_authenticated():\n\t\t\treturn None\n\t\tctype = ContentType.objects.get_for_model(obj)\n\t\ttry:\n\t\t\tvote = self.get(content_type=ctype, object_id=obj._get_pk_val(),\n\t\t\t\t\t\t\tuser=user)\n\t\texcept models.ObjectDoesNotExist:\n\t\t\tvote = None\n\t\tr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the number of upvotes made on the object by all users | def get_upvotes(self, obj):
content_type = ContentType.objects.get_for_model(obj)
votes = self.filter(content_type=content_type, object_id=obj._get_pk_val(), vote__exact=UPVOTE).aggregate(upvotes=Sum('vote'))
if votes['upvotes'] is None:
votes['upvotes'] = 0
return votes['... | [
"def count_upvotes(self):\n return self.filter(value=1).count()",
"def recieve_upvotes(self, num_upvotes):\n self.upvotes += num_upvotes",
"def get_votecount(self):\r\n countlist = SongVote.objects.filter(user=self.user)\r\n return len(countlist);",
"def get_total_upvotes(self, sug... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the number of downvotes on the object by all users | def get_downvotes(self, obj):
content_type = ContentType.objects.get_for_model(obj)
votes = self.filter(content_type=content_type, object_id=obj._get_pk_val(), vote__exact=DOWNVOTE).aggregate(downvotes=Sum('vote'))
if votes['downvotes'] is None:
votes['downvotes'] = 0
retu... | [
"def count_downvotes(self):\n return self.filter(value=-1).count()",
"def count_upvotes(self):\n return self.filter(value=1).count()",
"def get_upvotes(self, obj):\n content_type = ContentType.objects.get_for_model(obj)\n\n votes = self.filter(content_type=content_type, object_id=obj... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Append additional fields to the self.list_display. | def get_list_display(self, request):
list_display = self.list_display
if 'admin_created' not in list_display:
list_display += ('admin_created', )
if 'admin_modified' not in list_display:
list_display += ('admin_modified', )
return list_display | [
"def get_fields_to_show(self):\r\n\r\n return [self[f] for f in extra_fields]",
"def get_fieldsets(self, request, obj=None):\n fieldsets = super().get_fieldsets(request, obj)\n fieldsets += (\n (_(\"Extra info\"), {\n \"fields\": [\n \"created\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ask the user if he wants to reboot and use adhoc reboot command | def choose_reboot():
while True:
choice = input("Would you like to reboot now ? [y\\N] ")
if choice.lower() == 'n' or choice == '':
return
elif choice.lower() == 'y':
break
else:
continue
if os.name == 'nt':
call('shutdown /r /t 00')
... | [
"def reboot_system():\n reboot()",
"def reboot(self):\n module = 'reboot'\n method = 'POST'\n print(self.device + ' Calling reboot command on the device')\n response = self.axapi_call(module, method,'')\n if '2' in str(response.status_code):\n print(self.device + '... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a list of 25 random tweets from the authenticated user's lists. | def grab_tweets():
tweets = []
long_tweets = []
for each in lists:
tweets = tweets + twitter.GetListTimeline(list_id=each.id,
count=count,
include_rts=True)
for tweet in tweets:
if len(t... | [
"def list_tweets():\n tweets = []\n tuples = query_db('''\n select message.*, user.* from message, user\n where message.author_id = user.user_id\n order by message.pub_date desc limit ?''', [PER_PAGE])\n for tuple in tuples:\n tweet = {}\n tweet[\"username\"] = tuple['use... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a single randomly selected tweet. | def choose_tweet(pos_tweets):
tweet = choice(pos_tweets)
return tweet | [
"def random_tweet(self):\n chosen_tweet = random.choice(self.get_tweets())\n return self.tweet_id_url(chosen_tweet['id_str'])",
"def get_tweet(tweets_file, excluded_tweets=None):\n\n with open(tweets_file) as csvfile:\n reader = csv.DictReader(csvfile)\n possible_tweets = [row[\"twe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Authenticated user likes all tweets in pos_tweets. | def like_tweets(pos_tweets):
for tweet in pos_tweets:
twitter.CreateFavorite(status_id=tweet.id)
return | [
"def like_livecoding_tweets(request):\n q = request.GET.get('q')\n if q is None:\n search_results = api.search(q='@livecodingtv')\n else:\n try:\n search_results = api.search(q=q)\n except Exception as e:\n print(e)\n\n data = []\n tweet_count = 0\n for s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Authenticated user retweets tweet. | def retweet(tweet):
twitter.PostRetweet(tweet.id, trim_user=False)
return | [
"def tweet(self, username, tweet):\n return self._tweet(username, tweet)",
"def retweet(tweet_id):\n r = requests.post(twitter_api_base + \"/statuses/retweet/\" +\n tweet_id + \".json\",\n auth=oauth_credentials)\n if r.status_code != 200:\n print(\"Attempted to retweet t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Wrap an html code str inside a div. | def add_div_around_html(div_html_text, output_string=False, div_style="{width: 80%}"):
div = f"""<div style="{div_style}">{div_html_text}</div>"""
if output_string:
return div
#get_ipython().set_next_input(div, 'markdown')
else:
return Markdown(div) | [
"def render_div(self, data, depth):\n assert data[\"type\"] == \"div\"\n child = self.render_snippet(data[\"data\"], depth) if \"data\" in data else \"\"\n buf = \"<div style='%s'>%s</div>\" % (data.get(\"css\", \"\"), child)\n return buf",
"def wrap(self, source, outfile):\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update base branch and rebase topic branch. | def update_base_branch(self):
# Make sure base branch is up to date
print("Checking out base branch '{}'...".format(self.base_branch))
self.git.checkout(self.base_branch)
print('Updating base branch...')
self.git.pull('--rebase') | [
"def rebase_topic_branch_and_push(self):\n # Rebase topic branch\n print('Checking out topic branch..')\n self.git.checkout(self.topic_branch)\n print('Updating topic branch with work from base branch...')\n self.git.rebase(self.base_branch)\n\n # Push rebased version (so i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create topic branch locally and remotely. | def create_topic_branch(self, topic_branch_name):
print("Creating topic branch locally...")
self.git.checkout(self.base_branch)
self.git.checkout('-b', topic_branch_name)
print("Pushing topic branch to base branch's remote...")
self.git.push('-u', self.base_branch_remote(), topic... | [
"def main(github_token, branch_name, repository, sha):\n create_branch(github_token, branch_name, repository, sha)\n click.echo(f\"Successfully created branch {branch_name}\")",
"def create_topic(conf, topic, part=3, repl=2):\n\n admin_client = AdminClient(conf)\n admin_client.create_topics([NewTopic(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return name of active branch. | def active_branch(self):
return self.repo.active_branch.name | [
"def get_current_branch_name(self):\n # type: () -> Optional[str]\n branch = self.get_current_branch()\n if branch:\n return branch.name\n return None",
"def branch(self) -> str:\n return pulumi.get(self, \"branch\")",
"def branch_name(self):\n return f'phab-... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check whether a branch exists locally in the current repository. | def local_branch_exists(self, branch):
return branch in self.repo.branches | [
"def _branch_exists(repository, branch_name):\n try:\n repository.get_branch(branch_name)\n except:\n return False\n return True",
"def branch_exists(branch):\n\n try:\n git('show-ref', branch)\n return True\n except subprocess.CalledProcessError:\n return False",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return remote of base branch. | def base_branch_remote(self):
return self.git.config('--get', 'branch.{}.remote'.format(self.base_branch)) | [
"def get_remote_branch(self, branch_name: str):\n if branch_name in self.origin.refs:\n return self.origin.refs[branch_name]\n return None",
"def _get_remote(self, local_branch):\n remote = self._get_git_config('branch.%s.remote' % local_branch)\n\n if remote:\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create topic branch merge helper instance. | def __init__(self, base_branch, topic_branch=None, delete_local=False):
super(TopicMerge, self).__init__(base_branch)
self.topic_branch = topic_branch
self.delete_local = delete_local
if not topic_branch:
self.topic_branch = self.active_branch()
print("Using act... | [
"def create_topic_branch(self, topic_branch_name):\n print(\"Creating topic branch locally...\")\n self.git.checkout(self.base_branch)\n self.git.checkout('-b', topic_branch_name)\n print(\"Pushing topic branch to base branch's remote...\")\n self.git.push('-u', self.base_branch_r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Rebase topic branch with work from base branch and push. | def rebase_topic_branch_and_push(self):
# Rebase topic branch
print('Checking out topic branch..')
self.git.checkout(self.topic_branch)
print('Updating topic branch with work from base branch...')
self.git.rebase(self.base_branch)
# Push rebased version (so it'll get mar... | [
"def create_topic_branch(self, topic_branch_name):\n print(\"Creating topic branch locally...\")\n self.git.checkout(self.base_branch)\n self.git.checkout('-b', topic_branch_name)\n print(\"Pushing topic branch to base branch's remote...\")\n self.git.push('-u', self.base_branch_r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Merge topic branch then delete remotely and, optionally, locally. | def merge_and_cleanup(self):
print('Checking out base branch and merging topic branch...')
self.git.checkout(self.base_branch)
self.git.merge('--ff-only', self.topic_branch)
# Push merge and delete topic branch
print('Pushing base branch with topic branch merged...')
sel... | [
"def check_out_topic_branch_from_remote(self):\n self.git.checkout('-b', self.topic_branch, '{}/{}'.format(self.base_branch_remote(), self.topic_branch))",
"def __gitDeleteBranch(self):\n self.vcs.gitDeleteRemoteBranch(self.project.getProjectPath())",
"def delete_remote():\n branch = git.curren... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check out local version of topic branch. | def check_out_topic_branch_from_remote(self):
self.git.checkout('-b', self.topic_branch, '{}/{}'.format(self.base_branch_remote(), self.topic_branch)) | [
"def checkout(branch=\"lf-dev\"):\n with cd(FOLDER):\n sudo('git fetch', user='tomcat')\n sudo('git checkout %s' % branch, user='tomcat')\n status()",
"def checkout_latest():\n with cd(env.repo_path):\n run('git checkout %(branch)s;' % env)\n run('git pull origin %(branch)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check whether a branch exists remotely using base branch's origin. | def remote_branch_exists(self, branch):
try:
self.git.show_ref("refs/remotes/{}/{}".format(self.base_branch_remote(), branch))
return True
except git.exc.GitCommandError:
return False | [
"def remote_branch_exists(self):\n if self.settings.non_interactive:\n return True\n else:\n branches = self.clean_branches(self.run_git(\"branch -r\"))\n\n def replace_origin(b): return b.replace('origin/', '')\n\n return self.branch in map(replace_origin, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return Git log output for unmerged commits. | def unmerged_log(self):
return self.git.log('{}..{}'.format(self.base_branch, self.topic_branch)) | [
"def commit_msgs(start_commit, end_commit):\n fmt_string = (\"'%s%n* [#{pr_num}]\"\n \"(\" + PROJECT_URI + \"/{pr_num}) - %b'\")\n return subprocess.check_output([\n \"git\",\n \"log\",\n \"--pretty=format:%s\" % fmt_string,\n \"--merges\", \"%s..%s\" % (start_comm... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return number of unmerged commits. | def unmerged_total(self):
return int(self.git.rev_list('--count', '{}..{}'.format(self.base_branch, self.topic_branch))) | [
"def get_git_commiter_count(path):\n process = subprocess.Popen(['git', 'shortlog', '-sn'], cwd=path, stdout=subprocess.PIPE)\n stdout, _ = process.communicate()\n committers = stdout.decode(\"ISO-8859-1\")\n return len(committers.split('\\n'))",
"def get_commit_count():\n if COMMIT_COUNT is None:\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the current datetime (UTC+0). The accuracy is limited to milliseconds and the remaining microseconds are cleared. | def now() -> datetime:
now = datetime.now(tz=timezone.utc)
return now.replace(microsecond=now.microsecond - now.microsecond % 1000) | [
"def nowUTC():\n return datetime.datetime.now(pytz.utc)",
"def now_utc() -> datetime.datetime:\n return datetime.datetime.now(datetime.timezone.utc)",
"def get_utc_now_as_dt():\n return datetime.now(tz=timezone.utc)",
"def now():\n\tnow = datetime.now()\n\treturn now.replace( second = 0, microsecond ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a datetime (UTC+0) from a given representation. | def from_string(representation: str) -> datetime:
return parse(representation).replace(tzinfo=timezone.utc) | [
"def FromNowUTC(cls):\n t = pytime.time()\n utcTime = pytime.gmtime(t)\n return cls.FromStructTime(utcTime).WithZone(zDirection=0)",
"def convert_utc(utc) -> dt.datetime:\n return iso8601.parse_date(utc)",
"def datetime_utc_epoch_start() -> datetime:\n return timestamp_to_datetime... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update NLPIR license file if it is outofdate or missing. | def update_license_file(data_dir):
license_file = os.path.join(data_dir, LICENSE_FILENAME)
temp_dir = tempfile.mkdtemp()
gh_license_filename = os.path.join(temp_dir, LICENSE_FILENAME)
try:
_, headers = urlretrieve(LICENSE_URL, gh_license_filename)
except IOError as e:
# Python 2 uses... | [
"def update_frozen_license() -> int:\n srcpath = Path(\"doc/src/license.rst\")\n dstpath = Path(\"cx_Freeze/initscripts/frozen_application_license.txt\")\n try:\n content = srcpath.read_text(encoding=\"utf-8\")\n except OSError:\n print(ERROR1, file=sys.stderr)\n return 1\n conte... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find rhombus from a contour If shape is not found, return none and unidentified string | def detect_rhombus(approx):
max_length_diff = Rhombuses.get_max_length_diff_in_quad(approx)
if max_length_diff > Rhombuses.MAX_SIDE_LENGTH_DIFF:
return None, Shapes.UNIDENTIFIED_SHAPE
return approx, Shapes.RHOMBUS_SHAPE | [
"def detectShape(c):\n shape = \"unidentified\"\n peri = cv2.arcLength(c, True)\n approx = cv2.approxPolyDP(c, 0.04 * peri, True)\n\n # if the shape is a triangle, it will have 3 vertices\n if len(approx) == 3:\n shape = \"triangle\"\n \n # if the shape has 4 vertices, it is either a square... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Draw idxth rhombus on image | def __draw_rhombus(img, rhombus):
for i, point in enumerate(rhombus):
p1 = tuple(rhombus[i][0])
p2 = tuple(rhombus[(i+1) % 4][0])
cv2.line(img, p1, p2, color=(29, 131, 255), thickness=2)
return img | [
"def draw_rhombus(self, screen):\n pygame.gfxdraw.filled_polygon(screen, self.list_of_coordinates, self.color)\n\n return screen",
"def footprint_corner_indices():",
"def draw_heaters(ax, windtunnel):\n draw_heater(ax, windtunnel.heater_l)\n draw_heater(ax, windtunnel.heater_r)",
"def gen_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find leftmost, rightmost, uppermost, and bottommost point of a quadrilateral and count maximum length between points as a rhombus | def get_max_length_diff_in_quad(points):
leftmost, uppermost, rightmost, bottommost = (points[0, 0] for i in range(4))
for point in points:
x = point[0, 0]
y = point[0, 1]
if x < leftmost[0]:
# Point is located on the left side of leftmost point
... | [
"def get_max_width(sphere):\n true_vector = []\n for i in range(len(sphere)):\n for j in range(len(sphere[0])):\n if sphere[i][j] == True:\n true_vector.append((i,j))\n max_dist = 0\n x_min = 0\n x_max = 0\n y_min = 0\n y_max = 0\n i = 0\n j = 0\n\n for... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Utility method to build a the PayPal Pay request for starting the transaction process. The response will contain a payKey that will be used when we redirect the user to PayPal to complete the transaction. | def create_pay_request(donation_amount, charities):
# Try to split the donation amount equally amount all charities
l = len(charities)
split_amount = round(donation_amount/l, 2)
# Test that the amount was equally split. If it's not we must
# adjust one of the split amounts to make the sum of the d... | [
"def create_payment_request():\n amount_of_money = AmountOfMoney()\n amount_of_money.currency_code = \"CAD\"\n amount_of_money.amount = 2345\n billing_address = Address()\n billing_address.country_code = \"CA\"\n customer = Customer()\n customer.billing_address = billing_address\n order = Or... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Utility method to retrieve the payKey from a PayPal response | def get_pay_key(response):
return response.get("payKey") | [
"async def get_verification_key(request: web.BaseRequest):\n context = request.app[\"request_context\"]\n\n seed = request.match_info[\"id\"]\n wallet_mgr = WalletManager(context)\n walletverificationkey = await wallet_mgr.get_verification_key(seed)\n result = {\n \"key\": walletverificationke... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Utility method to retrieve the list of errors (if any) from a PayPal response. | def get_errors(response):
errors = response.get("error")
if errors:
return [e.get("message") for e in errors]
return None | [
"def errors(self) -> List[str]:\n return [e.get('message')\n for e in self._error.response.json().get('errors', [])]",
"def _get_resp_body_errors(self):\n\n if self._resp_body_errors and len(self._resp_body_errors) > 0:\n return self._resp_body_errors\n\n errors = []... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Running evaluation on test set, appending results to a submission. | def evaluate(model, dataset, append_submission, dataset_root):
with open(os.path.join(dataset_root, dataset + '.json'), 'r') as f:
image_list = json.load(f)
print('Running evaluation on {} set...'.format(dataset))
count_img=0
for img in image_list:
img_path = os.path.join(dataset_root... | [
"def evaluate(self, test_set, classifier=..., accuracy=..., f_measure=..., precision=..., recall=..., verbose=...):\n ...",
"def run_evaluation(self):\n print(\"start of evaluation\")\n self.metrics.append({\"index\": 0, \"runs\": []})\n for run in range(self.num_of_runs):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Asks Noembed_ for the embedding HTML code for arbitrary URLs. Sites supported include Youtube, Vimeo, Twitter and many others. Successful embeds are always cached for 30 days. Failures are cached if ``cache_failures`` is ``True`` (the default). The | def oembed_html(url, cache_failures=True):
# Thundering herd problem etc...
key = 'oembed-url-%s' % md5(url.encode('utf-8')).hexdigest()
html = cache.get(key)
if html is not None:
return html
try:
html = requests.get(
'https://noembed.com/embed',
params={
... | [
"def embed(url, **options):\n wrapper = match_wrapper(url)\n if wrapper:\n return wrapper.render(wrapper.clean_url(url), options)\n return ''",
"def get_embed_url(self):\n if not self.get_video_id():\n return ''\n \n if not self.embed_url:\n self.embed_url = 'ht... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets or creates a Folder based the list of folder names in hierarchical order (like breadcrumbs). get_or_create_folder(['root', 'subfolder', 'subsub folder']) creates the folders with correct parent relations and returns the 'subsub folder' instance. | def get_or_create_folder(self, folder_names):
if not len(folder_names):
return None
current_parent = None
for folder_name in folder_names:
current_parent, created = Folder.objects.get_or_create(
name=folder_name, parent=current_parent)
if creat... | [
"def get_folder(self, folder_name, create=False, parent=None):\n\t\tif( folder_name in self.folders.keys() ):\n\t\t\treturn self.folders[folder_name]\n\t\tif( create ):\n\t\t\tnew_folder = IMAPFolder(folder_name, parent=parent)\n\t\t\tself.folders[new_folder.path] = new_folder\n\t\t\treturn new_folder\n\t\telse:\n\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate a dictionary of random product IDs and their prices | def generateProducts(self):
# Creates items in each category
for i in range(self.num_of_items):
self.ID_DICT[i+self.num_of_items] = random.randint(1, 10)
self.ID_DICT[i+self.num_of_items*2] = random.randint(1, 10)
self.ID_DICT[i+self.num_of_items*3] = random.ra... | [
"def _initialize_products(self, products: List) -> Dict[str, int]:\n\n product_request = urllib.request.Request(url=URL_PRODUCTS, headers={'User-Agent': URL_USER_AGENT})\n product_response = urllib.request.urlopen(product_request)\n all_products = json.load(product_response)\n\n product_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given floats used for weighted choices, random purchases are made for a customer | def generatePurchases(self, num_of_purchases, food, medical, electronics, outdoors, clothing, beauty, customer):
# Empty purchases
self.customer_purchases = []
# Customer is *likely* to buy from some categories, but anything can happen
weighted_categories = [('Food', food), ('Med... | [
"def generateCustomers(self):\r\n\r\n # Counters\r\n shoppers = 0\r\n models = 0\r\n oldl = 0\r\n oldf = 0\r\n doctor = 0\r\n nudist = 0\r\n hippie = 0\r\n nerd = 0\r\n\r\n for i in range(self.num_of_customers):\r\n\r\n # With these we... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate employees, each with a name, clock in, clock out, and wage | def generateEmployees(self):
# Name
maleNames = ['Perry Lovan', 'Horacio Arvidson', 'Gale Skipworth', 'Joshua Lodge', 'Noble Shutter', 'Kristopher Talor', 'Jarod Harrop', 'Joan Henrichs', 'Wilber Vitiello', 'Clayton Brannum', 'Joel Sennett', 'Wiley Maffei', 'Clemente Flore', 'Cliff Saari', 'Miquel P... | [
"def test_emp_man_hours(self):\n start = timezone.make_aware(dt.datetime(2016, 6, 3, 6, 30))\n stop = timezone.make_aware(dt.datetime(2016, 6, 3, 10, 30))\n emp_hours = 0\n\n expected_emp_hours = 20.95\n\n # getting employee objects that are clocked in\n clocked_in_emp = ge... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Customer data generation based on weighted random choices | def generateCustomers(self):
# Counters
shoppers = 0
models = 0
oldl = 0
oldf = 0
doctor = 0
nudist = 0
hippie = 0
nerd = 0
for i in range(self.num_of_customers):
# With these weights, our store has plenty of yo... | [
"def generatePurchases(self, num_of_purchases, food, medical, electronics, outdoors, clothing, beauty, customer):\r\n\r\n # Empty purchases\r\n self.customer_purchases = []\r\n\r\n # Customer is *likely* to buy from some categories, but anything can happen\r\n weighted_categories = [('Fo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function calculates the Fourier Transform of a specific signal | def DFT(signal):
n = signal.shape[0]
omega = np.exp(((((-2) * np.pi)*1j) / n))
e_items = np.vander(omega**np.arange(n), n, True)
fourier_signal = np.dot(e_items, signal)
return fourier_signal.astype(np.complex128) | [
"def DFT(signal):\r\n return fft(signal)",
"def fourier(freq, a, b, x):\n sig = 2.0 * np.pi * freq * x\n return a * np.sin(sig) + b * np.cos(sig)",
"def numpyFourierTransform(self,graph):\n z=[complex(*graph[i]) for i in range(len(graph))]\n return np.fft.fft(z)",
"def FourierTransform(data... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function calculates the magnitude of derivative of an image using convolution | def conv_der(im):
derevitive_conv = np.array([[1], [-1]])
dx = scipy.signal.convolve2d(im, derevitive_conv, 'same')
dy = scipy.signal.convolve2d(im, derevitive_conv.transpose(), 'same')
magnitude = np.sqrt(np.abs(dx)**2 + np.abs(dy)**2)
return magnitude.real.astype(np.float64) | [
"def conv_der(im):\n\n derivative = np.fromiter((0.5, 0, -0.5), dtype='float64').reshape(1, 3)\n dx = convolve2d(im, derivative, mode=\"same\")\n dy = convolve2d(im, derivative.T, mode=\"same\")\n dxy = magnitude(dx, dy).astype('float64')\n\n return dxy",
"def gradient_magnitude(image, order=1):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function calculates the magnitude of derivative of an image using Fourier transform | def fourier_der(im):
ft_img = DFT2(im)
ft_img = np.fft.fftshift(ft_img)
n_x = im.shape[1]
coeff_x = (2 * np.pi * 1j)/n_x
u_freq = np.array([n if n < int(n_x/2) else (n-n_x) for n in range(n_x)]) * 1j
u_freq = np.array([np.fft.fftshift(u_freq)]*im.shape[0]).transpose()
dx_ft = coeff_x * IDFT... | [
"def fourier_der(im):\n\tn,m = im.shape\n\tu, v = grid(n, m)\n\tF = fftshift(fft2(im))\n\tFX = np.multiply(F,u)\n\tFY = np.multiply(F,v)\n\tdx = ifft2(ifftshift(FX)) * (2 * np.pi * 1j / m)\n\tdy = ifft2(ifftshift(FY)) * (2 * np.pi * 1j/ n)\n\treturn magnitude(dx,dy)",
"def fourier_der(im):\n im = im.astype(np.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This is a helper method to calculate the correct approximation of the gaussian kernel according to its size. Using convolution and the binomial coefficients. | def gaus_kernel_calc(kernel_size):
base_gaus_binom = np.array([[1], [1]])
kernel = base_gaus_binom
if kernel_size == 1:
# If the kernel size is 1 we need a 2d array that keeps the image the same.
kernel = np.array([[1]])
kernel = scipy.signal.convolve2d(kernel, kernel.transpose())
... | [
"def gaussian_2dkernel(size=5, sig=1.0):\r\n gkern1d = signal.gaussian(size, std=sig).reshape(size, 1)\r\n gkern2d = np.outer(gkern1d, gkern1d)\r\n return gkern2d / gkern2d.sum()",
"def make_gaussian_kernel(size,fwhm=3):\n x = np.arange(0, size, 1, np.float64)\n y = x[:,np.newaxis]\n x0 = y0 = s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function creates blur filter with gaussian matrix, using Fourier Transform. | def blur_fourier(im, kernel_size):
kernel = gaus_kernel_calc(kernel_size)
zeros = np.zeros(im.shape)
x_mid = np.math.floor(im.shape[1] / 2)
y_mid = np.math.floor(im.shape[0] / 2)
distance = np.math.floor(kernel_size / 2)
zeros[x_mid - distance: x_mid + distance + 1, y_mid - distance: y_mid + d... | [
"def Gaussian_Blur_Filter():\n\n filter_0 = np.array([[[1.0 / 36, 0, 0], [4.0 / 36, 0, 0], [1.0 / 36, 0, 0]],\n [[4.0 / 36, 0, 0], [16.0 / 36, 0, 0], [4.0 / 36, 0, 0]],\n [[1.0 / 36, 0, 0], [4.0 / 36, 0, 0], [1.0 / 36, 0, 0]]],\n dtype=np.flo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Masks the genotype call if it is not in a native segment. It does this by determining whether position is between start and end intervals for that ind (bed files are NAT_NAT regions | def ind_pos(position, ind, current_geno, chr_starts, chr_ends):
ind_starts = chr_starts[ind]
ind_ends = chr_ends[ind]
#print [position, ind, current_geno, ind_starts, ind_ends]
in_interval = False
for interval in range(len(ind_starts)):
if position > int(ind_starts[interval]) and position < ... | [
"def _isInSegment(offset:int, segment:Elfile.ElfSegHeaderType) -> bool:\n\t\t\treturn (0 <= (offset - segment.offset) < segment.size)",
"def _segment_mask(self):\n\n return self._segment_img.data[self._slice] != self.label",
"def get_isolated_segment(labeled_mask, peak):\n seg_index = labeled_mask[pea... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
For the selected reports (training or testing) in the database, process each report with peFinder | def processReports(self):
count = 0
for r in self.reports:
#need to change the next two lines so that the fields are not hard-coded
self.currentCase = r.id
self.currentText = r.impression.lower()
self.analyzeReport(self.currentText,
... | [
"def all(self):\n for name, cls in self.reports.items():\n report = cls()\n report.run(self.outfile)",
"def run_test(self):\n\n # populate *_ps sets\n self.enter_project_file()\n\n # populate *_dir sets\n self.enter_directories()\n\n # The files in t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute the area of a geospatial value. Returns FloatingValue The area of `self` | def area(self) -> ir.FloatingValue:
return ops.GeoArea(self).to_expr() | [
"def area(self) -> float:\n return self.polygon.area",
"def area(self):\n if len(self.exterior) < 3:\n raise Exception(\"Cannot compute the polygon's area because it contains less than three points.\")\n poly = self.to_shapely_polygon()\n return poly.area",
"def area(self)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the geometry as wellknown text (WKT) without the SRID data. Returns StringValue String value | def as_text(self) -> ir.StringValue:
return ops.GeoAsText(self).to_expr() | [
"def getWKT(self):\n logger.debug(\"Entering in ocentricWKT.getWkt\")\n\n # building WKT string\n wkt = OcentricWKT.GEODCRS % (\n self.getGeoGcsName(), self.getDatumName(), self.getSpheroidName(), self.getRadius(), self.getInverseFlattening(),\n self.getRadius(), self.getA... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the geometry as wellknown bytes (WKB) with the SRID data. Returns BinaryValue WKB value | def as_ewkb(self) -> ir.BinaryValue:
return ops.GeoAsEWKB(self).to_expr() | [
"def get_bbox_wkt(xml_parse):\n bounds = xml_parse.find(\"idinfo/spdom/bounding\")\n x_1 = float(bounds.find(\"westbc\").text)\n x_2 = float(bounds.find(\"eastbc\").text)\n y_1 = float(bounds.find(\"northbc\").text)\n y_2 = float(bounds.find(\"southbc\").text)\n return wkt.dumps(Polygon([(x_1, y_1... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |