query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Returns XML for the article corresponding to a PMC ID. | def get_xml(pmc_id):
if pmc_id.upper().startswith('PMC'):
pmc_id = pmc_id[3:]
# Request params
params = {}
params['verb'] = 'GetRecord'
params['identifier'] = 'oai:pubmedcentral.nih.gov:%s' % pmc_id
params['metadataPrefix'] = 'pmc'
# Submit the request
res = requests.get(pmc_url,... | [
"def getPMCXML(pmcid):\n link = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pmc&format=xml&id='+str(pmcid)\n r_text = makeRequest(link)\n return r_text",
"def getPubMedXML(pmid):\n link = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&format=xml&id='+str(pmid)\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get text from the body of the given NLM XML string. | def extract_text(xml_string):
paragraphs = extract_paragraphs(xml_string)
if paragraphs:
return '\n'.join(paragraphs) + '\n'
else:
return None | [
"def extract_text(body):\n soup = BeautifulSoup(body, 'html.parser')\n text = soup.get_text()\n lines = (line.strip() for line in text.splitlines())\n chunks = (phrase.strip() for line in lines for phrase in line.split(\" \"))\n text = ' '.join(chunk for chunk in chunks if chunk)\n return text",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns list of paragraphs in an NLM XML. | def extract_paragraphs(xml_string):
tree = etree.fromstring(xml_string.encode('utf-8'))
paragraphs = []
# In NLM xml, all plaintext is within <p> tags, and is the only thing
# that can be contained in <p> tags. To handle to possibility of namespaces
# uses regex to search for tags either of the for... | [
"def get_doc_paragraphs(self):\n tokens = nltk.word_tokenize(self.doc_content.decode('utf-8'))\n paragraphs = [tokens[x:x + 500] for x in xrange(0, len(tokens), 500)]\n return paragraphs",
"def extract_paragraphs(doc_file: str):\n doc = docx.Document(doc_file)\n\n paragraphs = [para.tex... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Filter a list of PMIDs for ones with full text from PMC. | def filter_pmids(pmid_list, source_type):
global pmids_fulltext_dict
# Check args
if source_type not in ('fulltext', 'oa_xml', 'oa_txt', 'auth_xml'):
raise ValueError("source_type must be one of: 'fulltext', 'oa_xml', "
"'oa_txt', or 'auth_xml'.")
# Check if we've loaded... | [
"def get_pmid_by_pmc(pmcid):\n if pmcid.startswith('PMC'):\n pmcid = pmcid[3:]\n handle = Entrez.efetch(db=\"pmc\", id=pmcid)\n if handle:\n data = handle.read()\n if isinstance(data, bytes):\n data = data.decode('utf-8')\n data = minidom.parse(StringIO(data))\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
(list) > int Function for insertion sort realisation Returns the amount of comparison operations while running algorithm. | def insertion_sort(array):
comparison_num = 0
for i in range(1, len(array)):
key = array[i]
j = i - 1
while j >= 0 and key < array[j]:
comparison_num += 1
array[j + 1] = array[j]
j -= 1
comparison_num += 1
array[j + 1] = key
return ... | [
"def insertion_sort(lst: list) -> int:\n compars = 0\n length = len(lst)\n for i in range(1, length):\n for j in range(i, 0, -1):\n compars += 1\n if lst[j] < lst[j-1]:\n lst[j], lst[j-1] = lst[j-1], lst[j]\n else:\n break\n return co... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
(list) > int Function for shell sort realisation Returns the amount of comparison operations while running algorithm. | def shell_sort(array):
comparison_num = 0
gap = len(array) // 2
while gap > 0:
for i in range(gap, len(array)):
cur_value = array[i]
j = i
while j >= gap and array[j - gap] > cur_value:
array[j] = array[j - gap]
j -= gap
... | [
"def shellsort(lst: list) -> int:\n compars = 0\n length = len(lst)\n h = 1\n while h < length / 3:\n h = 3 * h + 1\n while h >= 1:\n for i in range(h, length):\n j = i\n while j >= h:\n compars += 1\n if lst[j] < lst[j-h]:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
(list) > int Function for selection sort realisation Returns the amount of comparison operations while running algorithm. | def selection_sort(array):
comparison_num = 0
for i in range(len(array)):
min_position = i
for j in range(i + 1, len(array)):
if array[min_position] > array[j]:
min_position = j
comparison_num += 1
temp = array[i]
array[i] = array[min_posit... | [
"def selection_sort(lst: list) -> int:\n compars = 0\n length = len(lst)\n for i in range(length):\n min_pos = i\n for j in range(i+1, length):\n compars += 1\n if lst[j] < lst[min_pos]:\n min_pos = j\n lst[i], lst[min_pos] = lst[min_pos], lst[i]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Weights Swap Crossover Implementation Randomly generates a number between 1 and max_swaps number_co_points | def weights_swap_co(parent1, parent2, max_swaps=25):
number_co_points = randint(1,max_swaps) # number of crossover points
offspring1 = parent1.copy()
offspring2 = parent2.copy()
for i in range(number_co_points): # performed number_co_points times
# randomly get a wei... | [
"def swap_mutation(offspring, max_swaps=10):\n \n mutated = offspring.copy()\n \n number_swaps = randint(1,max_swaps) # number of points to swap\n \n for i in range(number_swaps):\n \n # weight 1 for swap:\n idx1_1 = randint(1,len(offspring)) - 1\n idx2_1 = randint(1,le... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Arithmetic Crossover Implementation Randomly generates a number between 1 and max_points number_co_points | def arithmetic_co(parent1, parent2, max_points=25):
number_co_points = randint(1,max_points)
offspring1 = parent1.copy()
offspring2 = parent2.copy()
for i in range(number_co_points):
# randomly get a weight index to perform the crossover
idx1 = randint(1,len(pare... | [
"def _pick_crossover_points(num_points, genome_size):\n # See De Jong, EC, pg 145\n pp = np.arange(genome_size, dtype=int)\n\n xpts = np.random.choice(pp, size=(num_points,), replace=False)\n xpts.sort()\n xpts = [0] + list(xpts) + [genome_size] # Add start and end\n\n ret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Blend Crossover Implementation Randomly generates a number between 1 and max_points number_co_points | def blend_co(parent1,parent2,max_points=25,alpha=0.01):
number_co_points = randint(1,max_points)
offspring1 = parent1.copy()
offspring2 = parent2.copy()
for i in range(number_co_points):
# randomly get a weight index to perform the crossover
idx1 = randint(1... | [
"def arithmetic_co(parent1, parent2, max_points=25): \n\n\n number_co_points = randint(1,max_points)\n \n offspring1 = parent1.copy()\n offspring2 = parent2.copy()\n \n for i in range(number_co_points):\n \n # randomly get a weight index to perform the crossover\n idx1 = ra... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the complete_at of the latest completed and not SKIPPED build request for this builder, or None if there are no such build requests. We need to filter out SKIPPED requests because we're using collapseRequests=True which is unfortunately marking all previous requests as complete when new buildset is created. | def getNewestCompleteTime(bldr):
bldrid = yield bldr.getBuilderId()
completed = yield bldr.master.data.get(
('builders', bldrid, 'buildrequests'),
[
resultspec.Filter('complete', 'eq', [True]),
resultspec.Filter('results', 'ne', [results.SKIPPED]),
],
order=['-complete_at'], limit=1)
if not comp... | [
"def last_build_date(self) -> Optional[datetime.datetime]:\n return self.updated_date",
"def completed_date(self, qb_id, iteration):\n required = set(self.required_qs(qb_id))\n have = self.completed_qs(qb_id=qb_id, iteration=iteration)\n if required - have:\n # incomplete se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns sorted list of builders by their last timestamp of completed and not skipped build. | def prioritizeBuilders(master, builders):
def is_building(bldr):
return bool(bldr.building) or bool(bldr.old_building)
def bldr_info(bldr):
d = defer.maybeDeferred(getNewestCompleteTime, bldr)
d.addCallback(lambda complete_at: (complete_at, bldr))
return d
def bldr_sort(item):
(complete_at, bldr) = item... | [
"def prioritizeBuilders(master, builders):\n\n\tbldrNamePrio = { \"__Janitor\": 0, \"00_force_build\": 0 }\n\ti = 1\n\tfor bname in branchNames:\n\t\tbldrNamePrio[bname] = i\n\t\ti += 1\n\n\tdef is_building(bldr):\n\t\treturn bool(bldr.building) or bool(bldr.old_building)\n\n\tdef bldr_info(bldr):\n\t\td = defer.ma... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets pipeline command for rnaseq sample. | def cmd(params, lsf):
exc = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'pipeline_se.py')
cmd = ' '.join([exc] + params)
if lsf:
cmd = bsub(cmd, 'rnaseq')
return(cmd) | [
"def embedded_pipeline():\n return \"\\n\".join(args['--cmd'])",
"def setCommand(self, command):\n self.command = command if command != None else \"\"",
"def __init__(self, command: str):\n self.command = command",
"def test_base_command(self):\n c = FastqJoin()\n # test bas... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given the name of a file containing a base64encoded ciphertext, return the decoded ciphertext as an integer. | def msg_file_to_int(msg, byteorder=sys.byteorder):
with open(msg, encoding="utf-8") as f:
return int.from_bytes(base64.b64decode(f.read()), byteorder=byteorder) | [
"def decode_base64(_base64):\n return binascii.a2b_base64(_base64)",
"def _decode_int64(data: bytes) -> int:\n return struct.unpack(\">Q\", (8 - len(data)) * b'\\x00' + data)[0]",
"def base64_read_file(filepath):\n with open(filepath, 'rb') as stream:\n data = stream.read()\n file_64_encode =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given two RSA public key files in PEM format sharing the same modulus, return the modulus and the two exponents. | def parse_rsa_files(key1, key2):
rsa1 = None
rsa2 = None
with open(key1, 'rb') as f:
rsa1 = serialization.load_pem_public_key(f.read()).public_numbers()
with open(key2, 'rb') as f:
rsa2 = serialization.load_pem_public_key(f.read()).public_numbers()
if rsa1.n != rsa2.n:
print(... | [
"def add_pubkeys(pubkey1,pubkey2,outputCompressed=True):\n\n try:\n pubkey1 = hexlify_(unhexlify_(pubkey1))\n pubkey1Int = int(pubkey1,16)\n pubkey1Int = \"\"\n except:\n raise TypeError(\"Public key 1 input is not hex or is odd length.\")\n if len(pubkey1) == 130:\n if p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Perform RSA Common Modulus Attack, given the modulus, two exponents and two ciphertexts as integers. Returns the plaintext as an integer. | def common_modulus_attack(modulus, exp1, exp2, msg1, msg2):
g, s, t = gmpy2.gcdext(exp1, exp2)
if g != 1:
print("Error: GCD of the two exponents is not 1!", file=sys.stderr)
sys.exit(1)
tmp1 = gmpy2.powmod(msg1, s, modulus)
tmp2 = gmpy2.powmod(msg2, t, modulus)
return int(gmpy2.mod(t... | [
"def encrypt(message,public_exponent,modulus):\n return pow(message,public_exponent,modulus) # message^public mod modulus",
"def decrypt(ciphertext,private_exponent,modulus):\n return pow(ciphertext,private_exponent,modulus) # cipher^private mod modulus",
"def rsa_encrypt(msg, e, n, k=3):\r\n msg = tx... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate facts from a state | def GenerateFacts(state):
facts = set()
for i in state:
if len(i) > 0:
facts.add(("OnTable",i[0]))
last = i[0]
for j in i[1:]:
facts.add(("On",j,last))
last = j
facts.add(("Clear",last))
return facts | [
"def generate_child_states(state: str) -> [str]:",
"def sample_descriptions_from_state(initial_state, current_state, obj_stuff, params):\n get_nb_floor_objects = params['extract_functions']['get_nb_floor_objects']\n get_open = params['extract_functions']['get_interactions']['get_open']\n get_close = para... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert a fluent statement to a string for the given step. | def ToStringCNF(statement,step):
ar = list(statement)
newvars = []
for i in ar[1:]:
i = ord(i) - ord('A')
newvars.append(str(i))
newvars.append(str(step))
return "%s(%s)" % (ar[0], ",".join(newvars)) | [
"def _get_func_str(step):\n return None",
"def _assemble_conversion(stmt):\n reactants = _join_list([_assemble_agent_str(r) for r in stmt.obj_from])\n products = _join_list([_assemble_agent_str(r) for r in stmt.obj_to])\n\n if stmt.subj is not None:\n subj_str = _assemble_agent_str(stmt... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Count the number of blocks in a state. | def CountBlocks(state):
blocks = []
for i in state:
if i[0] == "On" and not i[1] in blocks:
blocks.append(i[1])
if i[0] == "Clear" and not i[1] in blocks:
blocks.append(i[1])
if i[0] == "OnTable" and not i[1] in blocks:
blocks.append(i[1])
return len(blocks) | [
"def num_steps(block_state):\n seen = set()\n state_tuple = tuple(block_state)\n iterations = 0\n\n while state_tuple not in seen:\n seen.add(state_tuple)\n iterations += 1\n progress(block_state)\n state_tuple = tuple(block_state)\n\n return iterations",
"def num_blocks... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Exports the network that's described by node_list and edge_list to an iGraph graph. | def export_to_igraph(node_list, edge_list, with_cost=False):
#Creates the graph, it is directed because when it is read from the graph file it is already
##separated into 2 edges if it is not directed.
graph = iG.Graph(directed=True)
#Adds the vertices
#Note that if the name is not converted to stri... | [
"def writeSpecificGraphs(self, path, graph_list):\n f = open(path, 'w')\n writer = nx.readwrite.GraphMLWriter()\n writer.add_graphs(graph_list)\n writer.dump(f)",
"def create_network(edgelist):\n g = nx.Graph(edgelist)\n # nx.draw(G, with_labels=True)\n # plt.s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calls the MSA and System Optimal Solver to compute UE (User Equilibrium) and SO (System Optimal) and PoA (Price of Anarchy), respectively. Needs either a network file path or (edge_list and node_list and od_matrix) to work. | def assignment(net_file='', iterations=400, edge_list=None, node_list=None, od_matrix=None):
if edge_list and node_list and od_matrix:
nodes, edges, od_matrix, ue, od_routes_flow = MSA.run(iterations, edge_list=edge_list, node_list=node_list,
od_matrix=od_matrix... | [
"def solve(self, get_resid, layer_sizes, max_fun_evals, create_U=True, neural_net_basis=True, U_ansatz_if_not_neural=None, x0=None):\n if neural_net_basis:\n U=lambda params,x,y:self.G(x,y)+self.D(x,y)*optnn.neural_net_predict(params,np.array([x,y]).reshape(1,2))\n x0=optnn.init_random_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given the network's base name and a list of changed edges, it creates a new name for the network. | def get_network_name(net_name, changed_edges_list):
for change in changed_edges_list:
net_name += '_' + change
return net_name | [
"def change_name(network, old, new):\n new_network = {}\n for name, param in get_named_parameters(network):\n name = name.replace(old, new)\n new_network[name] = param\n return new_network",
"def postfix_names(\n g: xpb2.GraphProto,\n postfix: str = \"_g1\",\n elem: str... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a list with the n edge with most flow. | def rank_edges(edge_list, n):
return [edge.flow for edge in sorted(edge_list, key=lambda x:x.flow, reverse=True)[:n+1]] | [
"def max_n_edges(self):\n m = 0\n for n in self.nodes:\n k = self.edges_connected(n)\n print(k)\n if k > m:\n m = k\n return k",
"def get_top_n_nodes(nodes, n=10, nx=False):\n top = OrderedDict(sorted(nodes.items(), key=lambda kv: kv[1], reve... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Provides the 'params' argument that is provided to the UDF. | def provide_params_arg(
self, udf: Callable[..., T], fp_config: FeatureProcessorConfig
) -> Dict[str, Dict]: | [
"def provide_params_arg(\n self, udf: Callable[..., DataFrame], fp_config: FeatureProcessorConfig\n ) -> Dict[str, Union[str, Dict]]:\n return (\n self.params_loader.get_parameter_args(fp_config)\n if self._has_param(udf, self.PARAMS_ARG_NAME)\n else {}\n )",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Provides any additional arguments to be provided to the UDF, dependent on the mode. | def provide_additional_kwargs(self, udf: Callable[..., T]) -> Dict[str, Any]: | [
"def provide_params_arg(\n self, udf: Callable[..., T], fp_config: FeatureProcessorConfig\n ) -> Dict[str, Dict]:",
"def kw_and_pos_args_from_func(func):",
"def provide_params_arg(\n self, udf: Callable[..., DataFrame], fp_config: FeatureProcessorConfig\n ) -> Dict[str, Union[str, Dict]]:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Provide params for the UDF. If the udf has a parameter named 'params'. | def provide_params_arg(
self, udf: Callable[..., DataFrame], fp_config: FeatureProcessorConfig
) -> Dict[str, Union[str, Dict]]:
return (
self.params_loader.get_parameter_args(fp_config)
if self._has_param(udf, self.PARAMS_ARG_NAME)
else {}
) | [
"def provide_params_arg(\n self, udf: Callable[..., T], fp_config: FeatureProcessorConfig\n ) -> Dict[str, Dict]:",
"def _has_param(self, udf: Callable, name: str) -> bool:\n return name in list(signature(udf).parameters.keys())",
"def provide_additional_kwargs(self, udf: Callable[..., T]) -> D... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Provide the Spark session. If the udf has a parameter named 'spark'. | def provide_additional_kwargs(self, udf: Callable[..., DataFrame]) -> Dict[str, SparkSession]:
return (
{self.SPARK_SESSION_ARG_NAME: self.spark_session_factory.spark_session}
if self._has_param(udf, self.SPARK_SESSION_ARG_NAME)
else {}
) | [
"def spark_session(request: FixtureRequest) -> SparkSession:\n spark = (SparkSession.builder\n .master(\"local\")\n .appName(\"test_pyspark_session\")\n .getOrCreate())\n\n # Teardown spark session between module tests\n request.addfinalizer(lambda: spark.stop())\n re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parses the parameter names from the UDF that correspond to the input data sources. This function assumes that the udf signature's `params` and `spark` parameters are at the end, in any order, if provided. | def _get_input_parameters(self, udf_parameter_names: List[str]) -> List[str]:
inputs_end_index = len(udf_parameter_names) - 1
# Reduce range based on the position of optional kwargs of the UDF.
if self.PARAMS_ARG_NAME in udf_parameter_names:
inputs_end_index = udf_parameter_names.in... | [
"def provide_params_arg(\n self, udf: Callable[..., DataFrame], fp_config: FeatureProcessorConfig\n ) -> Dict[str, Union[str, Dict]]:\n return (\n self.params_loader.get_parameter_args(fp_config)\n if self._has_param(udf, self.PARAMS_ARG_NAME)\n else {}\n )",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a data source definition, load the data as a Spark DataFrame. | def _load_data_frame(
self,
data_source: Union[FeatureGroupDataSource, CSVDataSource, ParquetDataSource],
) -> DataFrame:
if isinstance(data_source, (CSVDataSource, ParquetDataSource)):
return self.input_loader.load_from_s3(data_source)
if isinstance(data_source, Feature... | [
"def createDataFrame(sqlc, data, schema, samplingRatio=None):\n # pylint: disable=protected-access\n\n self = sqlc.sparkSession\n\n if isinstance(data, RDD):\n rdd, schema = self._createFromRDD(data, schema, samplingRatio)\n else:\n rdd, schema = self._createFromLocal(data, schema)\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determine if a function has a parameter with a given name. | def _has_param(self, udf: Callable, name: str) -> bool:
return name in list(signature(udf).parameters.keys()) | [
"def has_parameter(self, a_name):\n return a_name in self.parameters",
"def has_arg(func, argname):\n return argname in getargspec(func)[0]",
"def hasarg(func, arg):\n return arg in signature(func).parameters",
"def accepts_parameter(func, param):\n signature = inspect.signature(func)\n ret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Turns part of a URL slug into a standard constant (or constant name), e.g. cabchassis becomes CAB_CHASSIS | def slugToConstant(slug):
if slug is None:
return None
elif slug == 'suv':
return constants.SUV
return slug.replace('-', '_').upper() | [
"def as_constant(name):\n return name.upper().replace(' ','_').replace('-','_')",
"def reflected_name(constant_name):\n # Check for SHOUTY_CASE constants\n if constant_name.upper() != constant_name:\n return constant_name\n return 'k' + ''.join(part.title() for part in constant_name.split('_'))... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
hide the ticklabels on ticks except for every rep'th tick. offset specifies an offset, of tick to start on. axis specifies the x (default) or y axis. when force is True (default) this function turns on every rep'th tick. | def skip_ticklabels(ax, rep=2, offset=0, axis='x', force=True):
if axis == 'x':
tks = ax.get_xticklabels()
else:
tks = ax.get_yticklabels()
for idx, tk in enumerate(tks):
if np.mod(idx + offset, rep):
tk.set_visible(False)
elif force:
tk.set_visible(Tr... | [
"def hide(self):\n self._ax.coords[self.x].set_ticklabel_position('')\n self._ax.coords[self.y].set_ticklabel_position('')",
"def hide_tick_labels(ax, which):\n assert which in ['x', 'y']\n if which is 'x':\n pl.setp(ax.get_xticklabels(), visible=False)\n if which is 'y':\n pl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
cpcolor(x,y,c) makes a pseudocolor plot of the data in c | def cpcolor(*args, **kwargs):
threshx = np.inf
threshy = np.inf
fixgaps = True
argind = 0
if isinstance(args[0], mpl.axes.Axes):
# Data is the second (1) element of args... (see below)
argind += 1
ax = args[0]
elif ('ax' in kwargs) or ('axes' in kwargs) or ('parent' in kw... | [
"def plotCon(xx, cc, ccRes, tt, plt_profiles='all',\n locs=[1, 3], colorbar=False, styles=['--', '-'],\n save=False, path=None):\n if path is None:\n if sys.platform == \"darwin\": # folder for linux\n path = '/Users/AmanuelWK/Desktop/'\n elif sys.platform.startswi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
y1 and y2 should be the ranges. This function will then flip y2 and tack it onto y1. For meanstd=True y1 should be the mean, and y2 the std. This function will add and subtract y2 from y1. | def vecs2fillvec(y1, y2, meanstd=False, x=None, axis=0):
if meanstd:
y1, y2 = y1 + y2, y1 - y2
if x is None:
return np.concatenate((y1, y2[::-1], y1[[0]]), axis)
else:
return (np.concatenate((y1, y2[::-1], y1[[0]]), axis),
np.concatenate((x, x[::-1], x[[0]]), axis)) | [
"def add_mean_and_std(df):\r\n mean_series = df.mean(axis=0)\r\n std_series = df.std(axis=0)\r\n ret = df.copy()\r\n ret.loc[0] = mean_series\r\n ret.loc[-1] = std_series\r\n return ret.sort_index()",
"def _normalise_mean_stddev(self, mean, stddev):\n mean = (mean - self.mean_centre) / se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate the width of each axes, based on the total figure width (height) totsize, the desired frame size, frame, the desired spacing between axes gap and the number of axes n. calcAxesSize returns the size each axes should be, along with the three element vector for input to saxes. | def calcAxesSize(n, totsize, gap, frame):
if hasattr(gap, '__len__'):
gtot = np.sum(gap[:n])
else:
gtot = gap * (n - 1)
axsz = (totsize - frame[0] - frame[1] - gtot) / n
sz, v = calcFigSize(n, [axsz, gap], frame, False)
return axsz, v | [
"def calcAxesSpacer(n, totsize, gap, frame):\n if hasattr(gap, '__len__'):\n gtot = np.sum(gap[:n])\n else:\n gtot = gap * (n - 1)\n axsz = (totsize - frame[0] - frame[1] - gtot) / n\n sz, v = calcFigSize(n, [axsz, gap], frame, False)\n return axsz, v",
"def calc_subplots_size(nplots:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate the width of each axes, based on the total figure width (height) totsize, the desired frame size, frame, the desired spacing between axes gap and the number of axes n. calcAxesSize returns the size each axes should be, along with the three element vector for input to saxes. | def calcAxesSpacer(n, totsize, gap, frame):
if hasattr(gap, '__len__'):
gtot = np.sum(gap[:n])
else:
gtot = gap * (n - 1)
axsz = (totsize - frame[0] - frame[1] - gtot) / n
sz, v = calcFigSize(n, [axsz, gap], frame, False)
return axsz, v | [
"def calcAxesSize(n, totsize, gap, frame):\n if hasattr(gap, '__len__'):\n gtot = np.sum(gap[:n])\n else:\n gtot = gap * (n - 1)\n axsz = (totsize - frame[0] - frame[1] - gtot) / n\n sz, v = calcFigSize(n, [axsz, gap], frame, False)\n return axsz, v",
"def calc_subplots_size(nplots: i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
calculates the positions for the `n` axes, based on the axes vector `vec`. | def axvec2axpos(n, vec, vertflag=False, rel=False):
if rel.__class__ is False.__class__ and not rel:
# Default value.
rel = np.ones(n)
wd = (((vec[1] - vec[0]) + vec[2]) / n - vec[2]) * rel / rel.mean()
if vertflag:
pos = vec[1] - (wd + vec[2]).cumsum().reshape((n, 1)) + vec[2]
... | [
"def count_vec(vec):\n return np.matrix(np.arange(1,product(vec.shape)+1))",
"def addVecToCoord(self, vec, row_n, data, row, col):\n wc = 0\n d,v = vec.getSparse()\n for gv_data, gv_col in izip(d,v):\n data.append(gv_data)\n col.append(gv_col)\n row.append... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add text to an axes offset from a location. offset specifies the offset (in points) from the selected pos. If offset is a two element list or tuple, it specifies a different offset in the x and y directions. Returns the text object. By default the x,y positions are in data coordinates. Specify a different 'transform' t... | def offset_text(ax, x, y, s, offset=(0, 0), transform=None, **kwargs):
if transform is None:
transform = ax.transData
else:
transform = get_transform(ax, transform)
if (offset.__class__ is list) or (offset.__class__ is tuple):
osx = offset[0] / 72.
osy = offset[1] / 72.
e... | [
"def offset_text(text, offset_space):\n lines = text.split('\\n')\n offset_lines = (offset_space + line for line in lines)\n offset_text = '\\n'.join(offset_lines)\n return offset_text",
"def splitText(self, offset: int):\n text = self.args[0][:offset]\n self.args[0] = self.args[0][offse... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
annotate a corner of an axes with a string. | def annoteCorner(ax, s, pos='ll', offset=10, **kwargs):
prm = {}
yp = 0.0
xp = 0.0
prm['va'] = 'baseline'
prm['ha'] = 'left'
# prm['fontsize']='medium'
if (offset.__class__ is list) or (offset.__class__ is tuple):
osx = offset[0]
osy = offset[1]
else:
osx = offset... | [
"def add_axes_label_inches(ax, (right_left, down_up), string, corner='upper left', **kwargs):\n fig = ax.get_figure()\n fig_size = fig.get_size_inches()\n ax_bbox = ax.get_position()\n ax_rect_inches = ax_bbox.x0*fig_size[0], ax_bbox.y0*fig_size[1], ax_bbox.x1*fig_size[0], ax_bbox.y1*fig_size[1]\n if... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Label the axes with alphanumeric characters. axs are the axes over which to add labels to. vals should be a string or list of strings to annotate the axes with. It defaults to string.lowercase prefix and suffix are strings that can be | def alphNumAxes(self, vals=lowercase, prefix=None, suffix=None, **kwargs):
if suffix is None:
suffix = ')'
if prefix is None:
prefix = ''
corner_labels = np.empty(self.size, 'O')
for idx, ax in enumerate(self):
corner_labels[idx] = ax.annoteCorner(
prefix + vals[idx] ... | [
"def make_axis_labels(vmin, vmax, n, fmt):\n labels = _vtk.vtkStringArray()\n for v in np.linspace(vmin, vmax, n):\n if fmt:\n if fmt.startswith('%'):\n label = fmt % v\n else:\n label = fmt.format(v)\n else:\n label = f'{v}'\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function randomize the order of sequences in a fasta file and then selects one sequence per year. | def oneSequencePerYear(fastaFile, seed):
random.seed(seed)
sequences = SeqIO.parse(open(fastaFile),'fasta')
sequences = [x for x in sequences]
random.shuffle(sequences)
dates = []
finalSeq = []
noRegex = []
for seq in sequences:
regex = r"(/\d+_+\d+/)"
match = re.search(regex, seq.id)
if match:
matc... | [
"def genRandomSequence2(numDoms):\n files = ls(DATAPATH)\n for i in range(len(files))[::-1]:\n if '.fa' not in files[i]:\n files.pop(i)\n pool = []\n i = 0\n while i < numDoms:\n f = list(open(DATAPATH + choice(files)))[1::2]\n f = choice(f).strip()\n if len(fin... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that a user is effectively logged in after a succesful signup process | def test_user_logged_in(self):
response = self.client.post(reverse('signup'), self.data)
self.assertEquals(response.status_code, 302)
self.assertIn('_auth_user_id', self.client.session) | [
"def test_user_login(self):\n self.assertTrue(User.is_authenticated)",
"def test_user_login(self):\n\n resp = self.client().post('/auth/register', data = self.user) ## First register the user.\n self.assertEqual(resp.status_code, 200)\n self.assertIn('true', str(resp.data)) ## Return ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that a user created by the signup process is not either a chef or an admin user, (which can enter the admin panel) | def test_created_user_is_not_chef_or_admin(self):
response = self.client.post(reverse('signup'), self.data)
self.assertEquals(response.status_code, 302)
user = models.User.objects.get(username="test")
self.assertEquals(not user.is_chef and not user.is_staff, True) | [
"def _should_create_user(self, request, email):\n return authz.is_admin(request, email)",
"def test_not_admin(self):\n new_user = self.create_user(name='another_user',\n fullname='Another user',\n passhash='hash',\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that trying to access to a menu whose uuid that doesn't exist results in 404 error. | def test_404_on_non_existent_menu(self):
invalid_uuid = '5bfa3016-ded3-424c-9140-5b0554d962a6'
response = self.client.get(reverse('menu', kwargs={'unique_id': invalid_uuid}))
self.assertEquals(response.status_code, 404) | [
"def test_get_404_on_non_existent_menu(self):\n invalid_uuid = '5bfa3016-ded3-424c-9140-5b0554d962a6'\n self.client.login(username='chef_user', password='12345')\n response = self.client.get(reverse(\n 'edit_menu',\n kwargs={'unique_id': invalid_uuid}\n ))\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that an existing menu is indeed sent to the template on correct URL. | def test_menu_displays(self):
response = self.client.get(reverse(
'menu',
kwargs={'unique_id': MenuTests.valid_menu.unique_id}))
self.assertEquals(response.status_code, 200)
self.assertEquals(response.context['menu'], MenuTests.valid_menu) | [
"def test_chef_user_can_publish_menu(self):\n self.client.login(username='chef_user', password='12345')\n response = self.client.post(reverse('new_menu'), {\n 'menu_title': 'Test menu',\n 'form-0-item_text': 'Menu 1',\n 'form-0-id': '',\n 'form-1-id': '',\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that a logged in user which has a previous order sends is detected, and the previous order is sent to the template via context. | def test_catch_prev_order(self):
self.client.login(username='testuser', password='12345')
dummy_order = models.Order.objects.create(
item_choice=MenuTests.dummy_choice,
user=MenuTests.dummy_user
)
response = self.client.get(
reverse(
'm... | [
"def test_anonymous_user_order_redirect(self):\n response = self.client.get(reverse(\n 'new_order',\n kwargs={'unique_id': CreateOrderViewTests.dummy_menu.unique_id}\n ))\n self.assertEquals(response.status_code, 302)\n messages = get_messages_as_list(response)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that trying to access to a menu's orders that doesn't exist returns a 404 | def test_404_on_non_existent_menu(self):
self.client.login(username='chef_user', password='12345')
invalid_uuid = '5bfa3016-ded3-424c-9140-5b0554d962a6'
response = self.client.get(reverse('menu_orders', kwargs={'unique_id': invalid_uuid}))
self.assertEquals(response.status_code, 404) | [
"def test_get_order_not_found(self):\n resp = self.app.get(\"{}/0\".format(BASE_URL))\n self.assertEqual(resp.status_code, status.HTTP_404_NOT_FOUND)",
"def test_nonexistant_orderid(self):\r\n response = self.app.get('/api/v1/orders/20', content_type=\"application/json\")\r\n self.asse... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that trying to access to a valid menu's orders without login in is blocked | def test_block_anonymous_user(self):
response = self.client.get(
reverse(
'menu_orders',
kwargs={'unique_id': ViewMenuOrderTests.dummy_menu.unique_id}
)
)
self.assertEquals(response.status_code, 302)
messages = get_messages_as_list(... | [
"def test_block_different_user(self):\n self.client.login(username='client_user', password='12345')\n response = self.client.get(reverse(\n 'user_orders',\n kwargs={'user_id': ViewClientOrdersTests.different_client_user.pk})\n )\n self.assertEquals(response.status_c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that trying to access to a valid menu's orders while logged in as a chef results in the correct orders being sent to the template. | def test_show_orders_to_chef(self):
dummy_order = models.Order.objects.create(
item_choice=ViewMenuOrderTests.dummy_choice,
user=ViewMenuOrderTests.client_user)
self.client.login(username='chef_user', password='12345')
response = self.client.get(reverse(
'menu... | [
"def test_order_menu_items(client):\n spoof_user(client)\n menu_item = __spoof_menu_items(client)\n result = client.get('/order/new', follow_redirects=True)\n expect = 'data-menu_item_id=\"{}\"'.format(menu_item)\n assert expect in str(result.data).replace(' ', '')",
"def test_chef_user_can_access(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that a client user cannot see a different client's orders, redirecting and returning a message | def test_block_different_user(self):
self.client.login(username='client_user', password='12345')
response = self.client.get(reverse(
'user_orders',
kwargs={'user_id': ViewClientOrdersTests.different_client_user.pk})
)
self.assertEquals(response.status_code, 302)
... | [
"def test_chef_user_order_redirect(self):\n self.client.login(username='chef_user', password='12345')\n response = self.client.get(reverse(\n 'new_order',\n kwargs={'unique_id': CreateOrderViewTests.dummy_menu.unique_id}\n ))\n self.assertEquals(response.status_code... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that a client can see his own orders, resulting in the orders being sent to the template. | def test_same_user_can_access(self):
dummy_order = models.Order.objects.create(
item_choice=ViewClientOrdersTests.dummy_choice,
user=ViewClientOrdersTests.client_user
)
self.client.login(username='client_user', password='12345')
response = self.client.get(reverse(... | [
"def test_chef_user_can_access(self):\n dummy_order = models.Order.objects.create(\n item_choice=ViewClientOrdersTests.dummy_choice,\n user=ViewClientOrdersTests.different_client_user\n )\n self.client.login(username='chef_user', password='12345')\n response = self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that a chef user can access a different user's orders and see them, resulting in the orders being sent to the template | def test_chef_user_can_access(self):
dummy_order = models.Order.objects.create(
item_choice=ViewClientOrdersTests.dummy_choice,
user=ViewClientOrdersTests.different_client_user
)
self.client.login(username='chef_user', password='12345')
response = self.client.get(... | [
"def test_same_user_can_access(self):\n dummy_order = models.Order.objects.create(\n item_choice=ViewClientOrdersTests.dummy_choice,\n user=ViewClientOrdersTests.client_user\n )\n self.client.login(username='client_user', password='12345')\n response = self.client.g... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that an anonymous user cannot enter the create menu view, instead, it is redirected to the login screen with a corresponding message. | def test_anonymous_user_redirect(self):
response = self.client.get(reverse('new_menu'))
self.assertEquals(response.status_code, 302)
messages = get_messages_as_list(response)
self.assertEquals(str(messages[0]), "Para continuar debe identificarse.") | [
"def test_anonymous_user_redirect(self):\n response = self.client.get(reverse(\n 'edit_menu',\n kwargs={'unique_id': EditMenuViewTests.dummy_menu.unique_id}\n ))\n self.assertEquals(response.status_code, 302)\n messages = get_messages_as_list(response)\n self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that a client user cannot enter the create menu view, instead, it is redirected to the login screen with a corresponding message. | def test_client_user_redirect(self):
self.client.login(username='client_user', password='12345')
response = self.client.get(reverse('new_menu'))
self.assertEquals(response.status_code, 302)
messages = get_messages_as_list(response)
self.assertEquals(str(messages[0]), "Usted debe ... | [
"def test_client_user_redirect(self):\n self.client.login(username='client_user', password='12345')\n response = self.client.get(reverse(\n 'edit_menu',\n kwargs={'unique_id': EditMenuViewTests.dummy_menu.unique_id}\n ))\n self.assertEquals(response.status_code, 302... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that a chef user can indeed connect to the create menu view. | def test_chef_user_can_enter(self):
self.client.login(username='chef_user', password='12345')
response = self.client.get(reverse('new_menu'))
self.assertEquals(response.status_code, 200) | [
"def test_chef_user_can_publish_menu(self):\n self.client.login(username='chef_user', password='12345')\n response = self.client.post(reverse('new_menu'), {\n 'menu_title': 'Test menu',\n 'form-0-item_text': 'Menu 1',\n 'form-0-id': '',\n 'form-1-id': '',\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that a chef client that sends by POST a valid Menu form, gets added to the database | def test_chef_user_can_publish_menu(self):
self.client.login(username='chef_user', password='12345')
response = self.client.post(reverse('new_menu'), {
'menu_title': 'Test menu',
'form-0-item_text': 'Menu 1',
'form-0-id': '',
'form-1-id': '',
'... | [
"def test_add_meal_to_menu_without_data(client):\n rv = client.post('/api/v1/menu/')\n assert rv.status_code == 400",
"def test_chef_can_edit_menu(self):\n self.client.login(username='chef_user', password='12345')\n response = self.client.post(\n reverse('edit_menu', kwargs={'unique... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that a chef client after having created a menu for the day, cannot create another one | def test_chef_user_cannot_publish_twice(self):
self.client.login(username='chef_user', password='12345')
self.client.post(reverse('new_menu'), {
'menu_title': 'Test menu',
'form-0-item_text': 'Menu 1',
'form-0-id': '',
'form-1-id': '',
'form-1-... | [
"def test_chef_user_can_enter(self):\n self.client.login(username='chef_user', password='12345')\n response = self.client.get(reverse('new_menu'))\n self.assertEquals(response.status_code, 200)",
"def test_chef_user_can_publish_menu(self):\n self.client.login(username='chef_user', pass... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that an anonymous user cannot edit a menu, instead it is redirected to the login page with an error message. | def test_anonymous_user_redirect(self):
response = self.client.get(reverse(
'edit_menu',
kwargs={'unique_id': EditMenuViewTests.dummy_menu.unique_id}
))
self.assertEquals(response.status_code, 302)
messages = get_messages_as_list(response)
self.assertEqual... | [
"def test_anonymous_user_redirect(self):\n response = self.client.get(reverse('new_menu'))\n self.assertEquals(response.status_code, 302)\n messages = get_messages_as_list(response)\n self.assertEquals(str(messages[0]), \"Para continuar debe identificarse.\")",
"def test_block_anonymou... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that a client user cannot edit a menu, instead it is redirected to the login page with an error message. | def test_client_user_redirect(self):
self.client.login(username='client_user', password='12345')
response = self.client.get(reverse(
'edit_menu',
kwargs={'unique_id': EditMenuViewTests.dummy_menu.unique_id}
))
self.assertEquals(response.status_code, 302)
m... | [
"def test_client_user_redirect(self):\n self.client.login(username='client_user', password='12345')\n response = self.client.get(reverse('new_menu'))\n self.assertEquals(response.status_code, 302)\n messages = get_messages_as_list(response)\n self.assertEquals(str(messages[0]), \"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that a chef client that tries to edit a non existent menu gets a 404 HTTP error code. | def test_get_404_on_non_existent_menu(self):
invalid_uuid = '5bfa3016-ded3-424c-9140-5b0554d962a6'
self.client.login(username='chef_user', password='12345')
response = self.client.get(reverse(
'edit_menu',
kwargs={'unique_id': invalid_uuid}
))
self.assertE... | [
"def test_404_on_non_existent_menu(self):\n self.client.login(username='chef_user', password='12345')\n invalid_uuid = '5bfa3016-ded3-424c-9140-5b0554d962a6'\n response = self.client.get(reverse('menu_orders', kwargs={'unique_id': invalid_uuid}))\n self.assertEquals(response.status_code,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that a chef client that tries to edit an existing menu, indeed, manages to modify the menu and it gets saved to the database. | def test_chef_can_edit_menu(self):
self.client.login(username='chef_user', password='12345')
response = self.client.post(
reverse('edit_menu', kwargs={'unique_id': EditMenuViewTests.dummy_menu.unique_id}),
{
'menu_title': 'Dummy menu edited',
'form... | [
"def test_full_update_menu(self):\n menu = sample_menu()\n menu.options.add(sample_option())\n\n payload = {\n 'name': 'Chilean Menu',\n 'date': datetime.date.today(),\n 'options': []\n }\n url = detail_url(menu.id)\n self.client.put(url, pa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that an anonymous user cannot make an order, instead it is redirected to the login page with an error message. | def test_anonymous_user_order_redirect(self):
response = self.client.get(reverse(
'new_order',
kwargs={'unique_id': CreateOrderViewTests.dummy_menu.unique_id}
))
self.assertEquals(response.status_code, 302)
messages = get_messages_as_list(response)
self.as... | [
"def test_block_anonymous_user(self):\n response = self.client.get(\n reverse(\n 'menu_orders',\n kwargs={'unique_id': ViewMenuOrderTests.dummy_menu.unique_id}\n )\n )\n self.assertEquals(response.status_code, 302)\n messages = get_mess... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that a chef user cannot make an order, instead it is redirected to the login page with an error message. | def test_chef_user_order_redirect(self):
self.client.login(username='chef_user', password='12345')
response = self.client.get(reverse(
'new_order',
kwargs={'unique_id': CreateOrderViewTests.dummy_menu.unique_id}
))
self.assertEquals(response.status_code, 302)
... | [
"def test_unauthenticated_user_cannot_add_order(self):\n data = {\n \"item_name\": \"john\",\n \"amount\": \"444\",\n }\n self.client.force_authenticate(user=None)\n res = self.client.post(self.orders_url, data)\n self.assertEqual(res.status_code, status.HTTP... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create ECM class Requires condition number and matrix size as parameters. Since multiple intervention conditions can be implemented in Markov Learning class, condition number should be specified. | def __init__(self, condition, size):
# initialization
# at first, condition number and size should be determinded.
# as a result a size x size matrix is created.
self.condition = condition
self.matrix = np.zeros((size,size))
self.size = size
self.has_value = 0 | [
"def createECM(self,conditions, size):\n # create ECM according to the number of conditions\n # if conditions < 2, error\n if conditions < 2:\n return -1\n\n # if size < 2, error\n if size < 2:\n return -2\n\n # check creation failure\n flag = 1... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reset the matrix size. Once ECM class is created with a certain size, this size value can be modified with this method. It returns 1 when the modification is successful. Return value 1 indicates an error (failure). | def setsize(self,size):
# reset the size
# size should be greater than 1
if size < 2:
# failed
return -1
self.matrix = np.zeros((size,size))
self.size = size
self.has_value = 0
# size change successful
return 1 | [
"def SizeOfStiffnessMatrix(self):\n\t\tpass",
"def __len__(self):\n return len(self.__matrix)",
"def set_size(self, n: 'int') -> \"void\":\n return _vnl_diag_matrixPython.vnl_diag_matrixCF_set_size(self, n)",
"def update_size(self):\n self.size = len(self.nodes)",
"def set_size(self, n:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the current matrix elements as ratio (0 1.0) Check whether the new matrix size is identical to preset matrix size. If not, returns 10 (error) Check whether the sum of each column is 1.0 If not, setting fails > returns 11 (error) If successful > returns 1 matvalue is stored in self.matvalue, and set has_value as 1 | def setmatrix_ratio(self, matvalue):
# if the current input value represents ratio (0 - 1.0)
# first, check the size of the input matrix
# if it does not fit into the current matrix size, fail
if (len(self.matrix) != len(matvalue)):
return -10
# check whether the sum ... | [
"def setmatrix_rawvalue(self, matvalue):\n # if the current input value represents ratio (0 - 1.0)\n # first, check the size of the input matrix\n # if it does not fit into the current matrix size, fail\n if (len(self.matrix) != len(matvalue)):\n return -1\n # calculate... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the current matrix elements as absolute values Check whether the new matrix size is identical to preset matrix size. If not, returns 10 (error) If successful > returns 1 matvalue is stored in self.matvalue, and set has_value as 1 | def setmatrix_rawvalue(self, matvalue):
# if the current input value represents ratio (0 - 1.0)
# first, check the size of the input matrix
# if it does not fit into the current matrix size, fail
if (len(self.matrix) != len(matvalue)):
return -1
# calculate ratio matr... | [
"def setmatrix_ratio(self, matvalue):\n # if the current input value represents ratio (0 - 1.0)\n # first, check the size of the input matrix\n # if it does not fit into the current matrix size, fail\n if (len(self.matrix) != len(matvalue)):\n return -10\n # check wheth... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Conduct evolution with a given t0value. The size of t0value should match with the current mat size. If not, then returns None (error) If successful, then returns the product (current matrix (self.matvalue . t0value). | def evolution_t1(self, t0value):
# evolve for t + 1
# t0value is the current status
# sizes (matrix and t0value) should match
if (len(self.matrix) != len(t0value)):
return None
# if match, then calculate the product of two matrices
return np.dot(self.matrix,... | [
"def tensor_full_contract(self, T):\n return np.einsum(\"...ij,...ij\", self, T, optimize='greedy')",
"def evaluate_C(self, q, t=None):\n # node on rigid body in GCS\n rP_i = u_P_lcs2gcs(self.u_P_LCS_list[self.body_id_list.index(self.body_id_i)], q, self.body_id_i)\n\n # node on fl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
continuously fetch event from upstream queue, wrapper it as ArtTask, the push downstream task queue | def run(self):
logging.info('start fetch task')
while(self._stop_flag != True):
for message in self._upstream_task_queue.receive_messages():
try:
art_task_request = json.loads(message.body)
logging.debug('fetched task id: '+art_task_req... | [
"def __call__(self, event, payload):\n # as we defined a threadpool we can enqueue our item\n # and move to the next.\n self.threadpool.enqueue(event, payload)\n print(\"Thread with payload \" + str(payload) + \" is enqueued\")",
"def run(self):\n logging.info('start output push... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
listening on upstream task queue, upload output image to cloud storage and push completion event to downstream task queue if get taks event from upstream queue. | def run(self):
logging.info('start output pusher.')
while(self._stop_flag != True):
try:
art_task = self._upstream_task_queue.get_nowait()
output_image_url = self._upload_output_image(art_task)
self._notify_completion(art_task,output_image_url)... | [
"def _upload_worker(\n file_queue: Union[queue.Queue[Tuple[str, str, bool]], multiprocessing.JoinableQueue[Tuple[str, str, bool]]],\n completed_queue: Union[queue.Queue[str], multiprocessing.JoinableQueue[str]],\n exception_queue: Union[queue.Queue[Exception], multiprocessing.JoinableQueue[Exception]],\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Produce a list of instructions and constants from an annotated ast. | def generate_code(tree: ast.Ast) -> Tuple[List[bc.Constant], List[bc.Instruction]]:
generator = CodeGenerator()
tree.accept(generator)
return generator.program.constants, generator.program.code | [
"def compile(self, ast):\n\n # collect\n self.constant_occurrences = collections.defaultdict(int)\n self.walk_ast_tree(ast, self.add_occurrence)\n\n # sort them according to how often they occur\n all_constants = list(self.constant_occurrences.keys())\n all_constants.sort(k... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Context manager for creating a type tagged function with upvalues. | def function(
self, type_annot: ts.Type, upvalues: List[an.IndexAnnot]
) -> Iterator[None]:
# Make the function struct, which stores the ip and any upvalues
# Tagged with the function type
with self.struct(type_annot, field_count=1 + len(upvalues)):
self.append_op(bc.Opco... | [
"def tagCreated(self, tag: ghidra.program.model.listing.FunctionTag, type: int) -> None:\n ...",
"def add_type_dict_for_context(self, var_dict):\n import traceback\n\n func_name = traceback.extract_stack(None, 2)[0][2]\n\n self.__add_type_dict_for_context(var_dict, func_name)",
"def ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Emit a jump instruction, possibly checking for a boolean condition. Returns an index used by end_jump. | def begin_jump(self, condition: Optional[bool] = None) -> int:
if condition is None:
self.append_op(bc.Opcode.JUMP)
else:
if condition:
self.append_op(bc.Opcode.NOT)
self.append_op(bc.Opcode.JUMP_IF_FALSE)
index = len(self.code)
self.ap... | [
"def jump(self, condition, to_addr, jumpkind=JumpKind.Boring, ip_offset=None):\n to_addr_ty = None\n if isinstance(to_addr, VexValue):\n # Unpack a VV\n to_addr_rdt = to_addr.rdt\n to_addr_ty = to_addr.ty\n elif isinstance(to_addr, int):\n # Direct ju... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a target index loops back to the instrucion at that index. | def loop_back(self, target: int) -> None:
self.append_op(bc.Opcode.LOOP)
index = len(self.code)
self.append_op(0)
size = bc.size(self.code[target + 1 :])
self.code[index] = size | [
"def __getitem__(self, index):\n return self.target[self.position + index]",
"def replan_move_target(self,idx,loc):\n self.crowd.requestMoveTargetReplan(idx,pyrecast.uintp_getitem(loc[0],0),loc[1])",
"def rollback_to(self, target_step):\n x, i, t = self.load_nearest_checkpoint(target_step)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get an upvalue from the function. | def get_upvalue(self, index: int) -> None:
# Load the function struct
self.append_op(bc.Opcode.PUSH_LOCAL)
self.append_op(0)
# If it's not the recursion upvalue get it from the struct
if index != 0:
self.append_op(bc.Opcode.GET_FIELD)
self.append_op(1 + in... | [
"def upvalue(self, index_annot: an.IndexAnnot) -> None:\n if index_annot.kind == an.IndexAnnotType.UPVALUE:\n self.get_upvalue(index_annot.value)\n else:\n # Assume that it isn't a global, since globals aren't ever upvalues\n self.append_op(bc.Opcode.REF_LOCAL)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make an upvalue to an index. | def upvalue(self, index_annot: an.IndexAnnot) -> None:
if index_annot.kind == an.IndexAnnotType.UPVALUE:
self.get_upvalue(index_annot.value)
else:
# Assume that it isn't a global, since globals aren't ever upvalues
self.append_op(bc.Opcode.REF_LOCAL)
self.... | [
"def get_upvalue(self, index: int) -> None:\n # Load the function struct\n self.append_op(bc.Opcode.PUSH_LOCAL)\n self.append_op(0)\n # If it's not the recursion upvalue get it from the struct\n if index != 0:\n self.append_op(bc.Opcode.GET_FIELD)\n self.appe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adding silence is easy we add zeros to the end of our array | def append_silence(audio, duration_milliseconds=500):
num_samples = duration_milliseconds * (sample_rate / 1000.0)
for x in range(int(num_samples)):
audio.append(0.0) | [
"def chunk_sound(bits):\n global buffer\n buffer = np.append(buffer, bits)\n abs_buffer = np.absolute(buffer)\n # Keep accumulating if not enough silence has been detected\n if len(buffer) <= SILENCE_FRAME_THRESHOLD:\n return np.array([])\n # If enough silence, clear the buffer\n last_timespan = abs_buffe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute title from last and first name | def _compute_title(self):
names = []
if self.lastName:
names.append(self.lastName)
if self.firstName:
names.append(self.firstName)
return safe_unicode(', '.join(names)) | [
"def full_name(first_name, last_name):\n return (first_name + ' ' + last_name).title()",
"def _get_formatted_name(first, middle, last):\n full_name = f\"{first} {middle} {last}\"\n return full_name.title()",
"def full_name(first, last):\n\n full = first + ' ' + last\n return full",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load a slice from a DCIMG file | def imread_dcimg(path, z):
with DCIMGFile(path) as arr:
img = arr[z]
return img | [
"def get_slice(fname, nSlice):\n\n nx, ny, nz = get_dims(fname)\n\n with open(fname, mode = \"rb\") as fid:\n # Seek to the proper location in the binary file\n fid.seek(1024 + (nx * ny) * (nSlice - 1) ,0) \n\n # Get the image slice as a Numpy array\n imgSlice = mrc_to_numpy(fid, n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the image shape of a DCIMG file | def check_dcimg_shape(path):
with DCIMGFile(path) as arr:
shape = arr.shape
return shape | [
"def get_image_shape(self) -> Tuple[int, int]:",
"def getShape(im=None):\n if im==None: im=getImage()\n return (im.getNSlices(), im.getWidth(), im.getHeight())",
"def image_shape(self):\n return self.mri_imgs[0].shape",
"def get_dims(fname):\n\n with open(fname, mode = \"rb\") as fid:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decompose `img` using discrete (decimated) wavelet transform using `wavelet` | def wavedec(img, wavelet, level=None):
return pywt.wavedec2(img, wavelet, mode='symmetric', level=level, axes=(-2, -1)) | [
"def naive_denoising(im):\n im_bayes = denoise_wavelet(im, multichannel=True,method='BayesShrink', mode='soft')\n return im_bayes",
"def decWave2D(image, ld, hd):\n\n # Decomposition on rows\n sx, sy = image.shape\n\n LrA = np.zeros((sx, int(sy/2)))\n HrA = np.zeros((sx, int(sy/2)))\n\n for i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a gaussian notch filter | def gaussian_filter(shape, sigma):
g = notch(n=shape[-1], sigma=sigma)
g_mask = np.broadcast_to(g, shape).copy()
return g_mask | [
"def gaussfiltering(img, sigma):\n\n return np.array(smooth_img)",
"def filter(self, signal):\n return self._custom_gaussian_filter(signal, self.n)",
"def gaussian_filter(F, sigma):\n neighbours = 2*(int(2.884402748387961466*sigma-0.5) // 2) + 1\n return cvGB(F, (neighbours, neighbours), sigma)"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Same as `read_filter_save' but with a single input dictionary. Used for pool.imap() in batch_filter | def _read_filter_save(input_dict):
# input_path = input_dict['input_path']
# output_path = input_dict['output_path']
# sigma = input_dict['sigma']
# level = input_dict['level']
# wavelet = input_dict['wavelet']
# crossover = input_dict['crossover']
# threshold = input_dict['threshold']
#... | [
"def filterdict(itemfunc, dictionary):\r\n return dict(filter(itemfunc, dictionary.items()))",
"def fetch_aggregator(self, filter_dict={}):\n try:\n partition = self.partition_names[frozenset(filter_dict.keys())]\n except KeyError:\n # TODO: discern what exactly goes wrong h... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
It assumes the CNF formula is defined in one line in the file. | def _read_cnf_formula(self) -> str:
with open(self._path, encoding='utf-8') as file:
cnf_formula = file.readline()
return cnf_formula | [
"def evidence_to_formula(self: BayesGraph, file_object: TextIO):\n evidence_description = [ int(i) for i in file_object.read().split()]\n if evidence_description[0] != (len(evidence_description) - 1) / 2:\n raise Exception(\"evidence file is improperly formatted\")\n indicators_map = [0]\n for card... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Using the expired_token_loader decorator, we will now call this function whenever an expired token attempts to access an endpoint but otherwise valid access | def my_expired_token_callback():
log.debug("-@- expired token checker")
### if user is not confirmed, delete user from DB
### otherwise return a link to refresh refresh_token
return jsonify({
'msg' : 'The token has expired',
'status' : 401,
'sub_status': 42,
}), 401 | [
"def my_expired_token_handler(expired_token):\n return jsonify({\n 'status': 400,\n 'message': 'The provided token has expired'\n }), 401",
"def jwt_refresh_token_required(fn):\n @wraps(fn)\n def wrapper(*args, **kwargs):\n verify_jwt_refresh_token_in_request()\n return fn(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if access_token has a claim 'renew_pwd' == True | def renew_pwd_required(func):
@wraps(func)
def wrapper(*args, **kwargs):
log.debug("-@- renew_pwd checker")
verify_jwt_in_request()
claims = get_jwt_claims()
log.debug("claims : \n %s", pformat(claims) )
log.debug("kwargs : \n %s", pformat(kwargs) )
try :
if claims["renew_pwd"] == True:
ret... | [
"def renew(self):\n \n self.check_auth()\n response = self.oauth.get(self.renew_token_url)\n response.raise_for_status()\n return True",
"def reset_pwd_required(func):\n\t@wraps(func)\n\tdef wrapper(*args, **kwargs):\n\t\t\n\t\tlog.debug(\"-@- reset_pwd checker\")\n\n\t\tverify_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if access_token has a claim 'reset_pwd' == True | def reset_pwd_required(func):
@wraps(func)
def wrapper(*args, **kwargs):
log.debug("-@- reset_pwd checker")
verify_jwt_in_request()
claims = get_jwt_claims()
log.debug("claims : \n %s", pformat(claims) )
log.debug("kwargs : \n %s", pformat(kwargs) )
try :
if claims["reset_pwd"] == True:
r... | [
"def user_is_reset_token_valid(token: str) -> bool:\n sql = __get_sql_script(\"user_is_reset_token_valid\")\n with __connect_to_db() as db:\n return bool(db.query(sql, token=token).one())",
"def renew_pwd_required(func):\n\t@wraps(func)\n\tdef wrapper(*args, **kwargs):\n\t\t\n\t\tlog.debug(\"-@- rene... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if access_token has a claim 'confirm_email' == True | def confirm_email_required(func):
@wraps(func)
def wrapper(*args, **kwargs):
log.debug("-@- confirm_email checker")
verify_jwt_in_request()
claims = get_jwt_claims()
log.debug("claims : \n %s", pformat(claims) )
if claims["confirm_email"] != True:
return { "msg" : "'confirm_email' token expected !... | [
"def test_confirmation_token(app, users):\n user = users[0][\"obj\"]\n token = generate_confirmation_token(user)\n # Valid\n expired, invalid, token_user = confirm_email_token_status(token)\n assert expired is False and invalid is False and token_user is user\n # Expired\n time.sleep(4)\n ex... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
retrieve github jobs data in form of a list of dictionaries after json processing | def get_github_jobs_data() -> List[Dict]:
all_data = []
page = 1
more_data = True
while more_data:
url = f"https://jobs.github.com/positions.json?page={page}"
raw_data = requests.get(url)
if "GitHubber!" in raw_data: # sometimes if I ask for pages too quickly I get an error; onl... | [
"def get_github_jobs_data() -> List[Dict]:\r\n all_data = []\r\n page = 1\r\n more_data = True\r\n while more_data:\r\n url = f\"https://jobs.github.com/positions.json?page={page}\"\r\n raw_data = requests.get(url)\r\n if \"GitHubber!\" in raw_data.text: # sometimes if I ask for pa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Save the authors, update time, make an excerpt | def save_model(self, request, entry, form, change):
if not entry.excerpt and entry.status == PUBLISHED:
entry.excerpt = Truncator(strip_tags(entry.content)).words(50)
if entry.pk and not request.user.has_perm('zinnia.can_change_author'):
form.cleaned_data['autho... | [
"def add_authors_age(soup: BeautifulSoup, file_path: str, authors_list: Typings.AuthorsBirths):\n file_name_uri = extract_article_uri(file_path)\n if len(file_name_uri) == 0:\n return\n datetime_span = soup.select_one('.article-aside time')\n if datetime_span is None:\n return\n datetim... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructs a Datastore key for a RunningClub entry with runningclub_name. | def runningclub_key(runningclub_name):
#----------------------------------------------------------------------
keyname = '.userpw.{}'.format(runningclub_name)
thisrckey = db.Key.from_path('SubApp', '.userpw', 'RunningClub', keyname)
return thisrckey | [
"def build_key(cls, user_id):\n key = ndb.Key(cls, user_id)\n return key",
"async def create_club(c: ClubIn) -> str:\n return await DbClub.add(c.dict())",
"def stats_key(member_name='stats_key'):\n return ndb.Key('stats', stats_name)",
"def generate_keyname():\n return str(uuid.uuid1())",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns userpw from database matching username, maybe creates user | def getcreateuserpw(runningclub_name,username):
#----------------------------------------------------------------------
pkey = runningclub_key(runningclub_name)
pname = '.userpw.{}'.format(runningclub_name)
user = UserPw.get_or_insert('{}.{}'.format(pname,username),parent=pkey)
return user | [
"def getuserpw(runningclub_name,username):\n#----------------------------------------------------------------------\n pkey = runningclub_key(runningclub_name)\n rcname = '.userpw.{}'.format(runningclub_name)\n uname = '{}.{}'.format(rcname,username)\n key = db.Key.from_path('SubApp', '.userpw', 'Running... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns userpw from database matching username, maybe creates user | def getuserpw(runningclub_name,username):
#----------------------------------------------------------------------
pkey = runningclub_key(runningclub_name)
rcname = '.userpw.{}'.format(runningclub_name)
uname = '{}.{}'.format(rcname,username)
key = db.Key.from_path('SubApp', '.userpw', 'RunningClub', rcn... | [
"def getcreateuserpw(runningclub_name,username):\n#----------------------------------------------------------------------\n pkey = runningclub_key(runningclub_name)\n pname = '.userpw.{}'.format(runningclub_name)\n user = UserPw.get_or_insert('{}.{}'.format(pname,username),parent=pkey)\n return user",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get all the numeric values from a line | def GetValues(line):
# LIN {X 1671.189,Y -562.497,Z -243.070,A 173.363,B -8.525,C -113.306} C_DIS
line = line.replace(",", " ")
line = line.replace("}", " ")
values = line.split(" ")
list_values = []
for value in values:
try:
value = float(value)
except:
... | [
"def _get_numeric_values(text):\n numeric_spans = parse_text(text)\n return itertools.chain(*(span.values for span in numeric_spans))",
"def get_floats(line, n, low=-1e100, high=1e100):\n if re.match('^(-?\\d*(\\.\\d*)? )*-?\\d*(\\.\\d*)?$', line) == None:\n abort('not a line with floats separated by si... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Assert that attachment content is as expected | def assertAttachment(self, attachment, filename=None):
if filename is None:
filename = attachment.datas_fname
data = self.files.joinpath(filename).read_bytes()
self.assertEqual(attachment.datas_fname, filename)
self.assertEqual(base64.b64decode(attachment.datas), data) | [
"def test_post_attachments(self):\n pass",
"def _assert__attachment(attachment):\n if not isinstance(attachment, (Attachment, EmbedImage)):\n raise AssertionError(\n f'`attachment` can be `{Attachment.__name__}`, `{EmbedImage.__name__}`, got '\n f'{attachment.__class__.__nam... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes the maximum length of the longest ORF over num_trials shuffles of the specfied DNA sequence | def longest_ORF_noncoding(dna, num_trials):
longest_length = 0
for i in range(0, num_trials):
shuffled_dna = shuffle_string(dna)
shuffled_dna_longest_length = len(longest_ORF(shuffled_dna))
if shuffled_dna_longest_length > longest_length:
longest_length = shuffled_dna_longest_length
ret... | [
"def longest_ORF_noncoding(dna, num_trials):\n for x in range (0,num_trials):\n shuffle= shuffle_string(dna)\n maxlengthORF= longest_ORF(shuffle)\n return maxlengthORF",
"def longest_ORF_noncoding(dna, num_trials):\n \n longest_ORFs = []\n s = list(dna)\n for i in range(0,num_trial... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a properly formatted Kinesis, S3, or SNS record. Supports a dictionary or string based data record. Reads in event templates from the test/integration/templates folder. | def format_record(test_record):
service = test_record['service']
source = test_record['source']
compress = test_record.get('compress')
data_type = type(test_record['data'])
if data_type == dict:
data = json.dumps(test_record['data'])
elif data_type in (unicode, str):
data = test... | [
"def test_correctly_parse_valid_kinesis_event_record(kinesis_event_record):\n record = KinesisEventRecord(**kinesis_event_record)\n\n # top-level fields\n assert \"1.0\" == record.event_version\n assert (\n \"aws:kinesis\" == record.event_source\n and EventSource.kinesis == record.event_so... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check the test_record contains the required keys | def check_keys(test_record):
req_keys = {
'data',
'description',
'service',
'source',
'trigger'
}
optional_keys = {
'trigger_count',
'compress'
}
record_keys = set(test_record.keys())
return (
req_keys == record_keys or
an... | [
"def test_in(self):\n self.assertIn('k1', self.record.data_values)\n self.assertIn('k2', self.record.data_values)\n self.assertIn('k3', self.record.data_values)\n self.assertNotIn('no_such_key', self.record.data_values)",
"def _check_pivot_keys(self) -> bool:\n for obj in self.j... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
read_comp_and_energy_points(datafile) Generates points in composition and energy space for use in convex hull algorithms. | def read_comp_and_energy_points(datafile):
with open(datafile) as f:
data = json.load(f)
points = [
[x[0] for x in entry["comp"]] + [entry["formation_energy"]] for entry in data
]
points = np.array(points)
return points | [
"def _read_elliptic_files(self):\n file_1_2 = os.path.join(\n mm.DATA_PATH, 'interpolate_elliptic_integral_1_2.dat')\n file_3 = os.path.join(\n mm.DATA_PATH, 'interpolate_elliptic_integral_3.dat')\n\n (x, y1, y2) = np.loadtxt(file_1_2, unpack=True)\n PointLens._inte... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find if specified coordinates are above, on or below the specified lower convex hull. | def checkhull(hull_vertex, test_coords):
# TODO: function that ony returns projected energy
# Split data into composition and energy
hull_comps = hull_vertex[:, 0:-1]
hull_energies = hull_vertex[:, -1]
x_test = test_coords[:, 0:-1]
y_test = test_coords[:, -1]
# Fit linear grid
interp_h... | [
"def is_cow_within_bounds(cow_position, boundary_points):\r\n x=cow_position[0]\r\n y=cow_position[1]\r\n x1=boundary_points[0][0]\r\n y1=boundary_points[0][1]\r\n x2=boundary_points[2][0]\r\n y2=boundary_points[2][1]\r\n if x1<x and x2>x and y>y2 and y<y1:\r\n print (\"1\")\r\n else:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |