query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Get the interaction sites, which describe the position of interacting mutations in the genotypes. (type==list of lists, see self._build_interaction_sites) | def sites(self):
return self.data.sites.values | [
"def get_sites(self):\n st = self.site_text\n suffixes = [' residue', ' residues', ',', '/']\n for suffix in suffixes:\n if st.endswith(suffix):\n st = st[:-len(suffix)]\n assert(not st.endswith(','))\n\n # Strip parentheses\n st = st.replace('(', ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
List of site labels. Each site is represented as a list of labels returned by the `label_mapper` (see `get_label_mapper`). | def labels(self):
mapper = self.get_label_mapper()
labels = ['w.t.']
for term in self.sites[1:]:
labels.append([mapper[site] for site in term])
return labels | [
"def get_labels(self):\n return label_list",
"def list_labels(self):\n return list(self.repo.labels.list())",
"def getLabelsList(self):\n return HopperLowLevel.getLabelsList(self.__internal_segment_addr__)",
"def get_labels(self):\n return self.labels_list",
"def get_labels(self)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get epistasis of a given order. | def get_orders(self, *orders):
return EpistasisMapReference(self.data, orders) | [
"def get_ephemerides(hdr=None, return_eph=True, loc=None, epoch=None, target=None,\n cache=False, **kwargs):\n # Get info from FITS header\n if target is None:\n target = hdr['OBJECT'].casefold()\n target_dict = {\n 'io': 501,\n 'europa': 502,\n 'j... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Dictionary that maps attr1 to attr2. | def map(self, attr1, attr2):
return dict(zip(getattr(self, attr1), getattr(self, attr2))) | [
"def get_attr_map():\n custom_attributes = get_custom_attrs()\n standard_attributes = get_standard_attrs()\n mapping = {}\n for attr in custom_attributes.keys():\n mapping[f'custom:{attr}'] = attr\n mapping.update(standard_attributes)\n return mapping",
"def _get_edge_attributes(self, lin... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the interaction sites, which describe the position of interacting mutations in the genotypes. (type==list of lists, see self._build_interaction_sites) | def sites(self):
return self.data.sites.values | [
"def get_sites(self):\n st = self.site_text\n suffixes = [' residue', ' residues', ',', '/']\n for suffix in suffixes:\n if st.endswith(suffix):\n st = st[:-len(suffix)]\n assert(not st.endswith(','))\n\n # Strip parentheses\n st = st.replace('(', ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
test task with NO chain does not call task.delay | def test_task_no_chain(self):
kwargs = {"a": 400, "b": 901}
worker = wiji.Worker(the_task=self.myTask, worker_id="myWorkerID1")
self.myTask.synchronous_delay(a=kwargs["a"], b=kwargs["b"])
with mock.patch("wiji.task.Task.delay", new=AsyncMock()) as mock_task_delay:
dequeued_i... | [
"def test_task_with_chain(self):\n\n class DividerTask(wiji.task.Task):\n the_broker = self.BROKER\n queue_name = \"{0}-DividerTaskQueue\".format(uuid.uuid4())\n\n async def run(self, a):\n res = a / 3\n print(\"divider res: \", res)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
test task with chain CALLS task.delay | def test_task_with_chain(self):
class DividerTask(wiji.task.Task):
the_broker = self.BROKER
queue_name = "{0}-DividerTaskQueue".format(uuid.uuid4())
async def run(self, a):
res = a / 3
print("divider res: ", res)
return res
... | [
"def test_task_no_chain(self):\n kwargs = {\"a\": 400, \"b\": 901}\n\n worker = wiji.Worker(the_task=self.myTask, worker_id=\"myWorkerID1\")\n self.myTask.synchronous_delay(a=kwargs[\"a\"], b=kwargs[\"b\"])\n with mock.patch(\"wiji.task.Task.delay\", new=AsyncMock()) as mock_task_delay:\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
test that if parent task raises exception, the chained task is not queued | def test_no_chaining_if_exception(self):
class DividerTask(wiji.task.Task):
the_broker = self.BROKER
queue_name = "{0}-DividerTaskQueue".format(uuid.uuid4())
async def run(self, a):
res = a / 3
print("divider res: ", res)
retu... | [
"def test_task_no_chain(self):\n kwargs = {\"a\": 400, \"b\": 901}\n\n worker = wiji.Worker(the_task=self.myTask, worker_id=\"myWorkerID1\")\n self.myTask.synchronous_delay(a=kwargs[\"a\"], b=kwargs[\"b\"])\n with mock.patch(\"wiji.task.Task.delay\", new=AsyncMock()) as mock_task_delay:\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
test that if parent task is been retried, the chained task is not queued | def test_no_chaining_if_retrying(self):
class DividerTask(wiji.task.Task):
the_broker = self.BROKER
queue_name = "{0}-DividerTaskQueue".format(uuid.uuid4())
async def run(self, a):
res = a / 3
print("divider res: ", res)
retur... | [
"def task_bypassed(self, task):\n pass",
"def _retry(self):\n # TODO(dcramer): this needs to handle too-many-retries itself\n assert self.task_id\n\n task = Task.query.filter(\n Task.task_name == self.task_name,\n Task.task_id == self.task_id,\n Task.parent... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
sleep for a few seconds so that some tasks can be consumed, then shutdown worker | async def call_worker_shutdown():
await asyncio.sleep(5)
await worker.shutdown() | [
"async def call_worker_shutdown():\n await asyncio.sleep(5)\n await worker.shutdown()",
"def cleanThreadTimeToWait() -> None:\n ...",
"def _sleep(self):\n self.kill()",
"def simulated_blocking_io_task(self):\n seconds_to_run = randint(5, 10)\n sleep(se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
sleep for a few seconds so that some tasks can be consumed, then shutdown worker | async def call_worker_shutdown():
await asyncio.sleep(5)
await worker.shutdown() | [
"async def call_worker_shutdown():\n await asyncio.sleep(5)\n await worker.shutdown()",
"def cleanThreadTimeToWait() -> None:\n ...",
"def _sleep(self):\n self.kill()",
"def simulated_blocking_io_task(self):\n seconds_to_run = randint(5, 10)\n sleep(seconds_to... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Enqueues all kinds of messages. | def enqueue_all(self, requests=None, replies=None, routed=None):
fast = []
medium = []
slow = []
if requests is not None:
if SPEED_FAST in requests:
fast = requests[SPEED_FAST]
if SPEED_MEDIUM in requests:
medium = requests[SPEED_M... | [
"def send_messages(self, queues):\n for q in queues:\n queue = q['queue']\n try:\n m = queue.get(block=False)\n org, flow = q['dest_channel'].split('|')\n url = '{server}/flows/{org}/{flow}/messages'.format(\n server=self.s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds one or more messages to internal slow queue to be send later. | def enqueue_slow(self, message):
assert Message.validate_messages_for_send(message, self.app)
self.slow_queue.enqueue(message)
self.sleep.set() | [
"def add_to_queue(self):\n self.manager.client.song_q.put(self.get_text(None))",
"def flushQueuedMessages(self):\n if self.queued_time is not None:\n self.getProxy(0).massDelayedActions(self.queued_time, \n self.queued_messages)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get positions relative to unit cell i.e. fractional coordinates. If wrap is True, atoms outside the unit cell will be wrapped into the cell in those directions with periodic boundary conditions so that the scaled coordinates are between zero and one. | def get_scaled_positions(coords, cell, pbc, wrap=True):
fractional = np.linalg.solve(cell.T,
coords.T).T
if wrap:
for i, periodic in enumerate(pbc):
if periodic:
# Yes, we need to do it twice.
# See the scaled_positions.py tes... | [
"def transform(self):\n return self.cellx, 0.0, self.left, 0.0, -self.celly, self.top",
"def return_position(self, unit='volts'):\n if unit == 'volts':\n curr_x, curr_y = self.position['x'], self.position['y']\n else:\n curr_x, curr_y = self.volts_to_micron(self.position... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
fetch documents from egov by document id and save it to raw directory. | def do_fetchdoc(self, line):
if not line.strip():
print "usage: fetchdoc <document_id>\n"
key = line.strip()
url = self.base_doc_url % (key[:3], key)
print "fetchdoc: %s" % url
doc = lxml.html.parse(url).getroot()
content = lxml.html.tostring(doc, encoding='... | [
"def download_query_data(doc_id=\"16AZ9Po7h8Qa3ink55bZn4GaiS2pBPVQMMuDd2TBIByA\"):\n warn(\"We still have a dummy version of download_query_data !\")\n example_filepath = \"testdata/ex-query.csv\"\n return example_filepath",
"def retrieve_document(doc_id):\n\n db = config_db.get_db()\n success, out... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
show a list of categories and their keys | def _show_categories(self):
for (key, val) in self.categories:
separator = key % 5 == 0 and "\n" or ' ' * (15 - len(val) * 2)
print ('%02s: %s%s' % (key, val, separator)).encode('utf-8'), | [
"def categories_show(self):\n\n cursor = DatabaseManager.connection_to_database(self)\n\n cursor.execute(\"SELECT * FROM category\")\n\n my_results = cursor.fetchall()\n\n i = 1\n cat_list = []\n for cat_tuples in my_results:\n for cat_str in cat_tuples:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extract the standard_id (standard citation key) for a csl_item and modify the csl_item inplace to set its "id" field. The standard_id is extracted from a "standard_citation" field, the "note" field, or the "id" field. If extracting the citation from the "id" field, uses the infer_citekey_prefix function to set the pref... | def csl_item_set_standard_id(csl_item):
if not isinstance(csl_item, dict):
raise ValueError(
"csl_item must be a CSL Data Item represented as a Python dictionary")
from manubot.cite.citeproc import (
append_to_csl_item_note,
parse_csl_item_note,
)
note_dict = parse_c... | [
"def id_replace(self):\n aws_lookup = self.lookup()\n var_lookup_list = pcf_util.find_nested_vars(self.desired_state_definition, var_list=[])\n for (nested_key, id_var) in var_lookup_list:\n if id_var[0] == \"lookup\":\n resource = id_var[1]\n names = id... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
generator that builds the list of logo filenames | def logos():
for n in range(12):
yield "eh_logo_%d.tiff" % (n + 1) | [
"def make_image_list(image_dir):",
"def logo():",
"def create_logo(self, seqs=[]):\n # seperate headers\n headers, instances = [list(x) for x in zip(*seqs)]\n\n if self.options.sequence_type is 'rna':\n alphabet = Alphabet('ACGU')\n elif self.options.sequence_type is 'prot... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
build plaques structure from CSV file | def load_csv(filename):
plaques = []
plqs = csv.reader(open(filename, 'rb'))
for row in plqs:
image_url = row[1]
text = row[2]
# ignore id (0) and plaque url (3) for now
last_slash = image_url.rfind('/')
filename = image_url[last_slash+1:]
filename_base = os.p... | [
"def import_from_csv(self, csv_file):\n reader = csv.reader(csv_file)\n\n self.variable_labels = next(reader, None)[1:]\n self.element_labels = []\n self.data = []\n\n data_mode = True\n for row in reader:\n if not any(row):\n if data_mode:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates the value of Gamma and phi given the input site and the input parameters. | def Gamma_phi_fn(site,p):
if site.pos[0] <= p.left[-1]: #
Gamma = p.GammaL; phi = p.phiL
elif p.middle[0] <= site.pos[0] <= p.middle[-1]:
Gamma = 0; phi = 0
elif p.right[0] <= site.pos[0] <= p.right[-1]:
Gamma = p.GammaR; phi = p.phiR
else:
raise ValueError("In Gamma_phi_fn: site.pos[0] was in neither par... | [
"def get_gamma_distribution_params(mean, std):\n # mean = k * theta\n # var = std**2 = k * theta**2\n k = std**2 / mean\n theta = mean / k\n return k, theta",
"def gamma(c, g):\n\n pass",
"def invgamma(x, a, b):\n return stats.gamma.pdf(1 / x, a, scale=(1 / b)) / x ** 2",
"def gamma(x):\n return... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Hopping energy of onedimensional semiconductor, whose Hamiltonian is given as in onsite_1D_semiconductor. | def hoppingy_1D_semiconductor(site0,site1,p):
#print("%s: in hoppingy_1D_semiconductor()" %str(misc.round_time(datetime.datetime.now(),round_to=60)))
return -p.t_N*tau_z + 1j*p.alphahbar/(2*p.ay)*sigma_ytau_z | [
"def energy(params,circuit):\n # setup circuit (resolve parameters to numerical values)\n resolver = cirq.ParamResolver({'theta'+str(j):params[j] for j in range(n_var_params)})\n resolved_circuit = cirq.resolve_parameters(circuit, resolver) \n u = resolved_circuit.unitary(qubit_order = qp+qb)\n uni... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Onsite energy of 2D superconductor, e.g. used for same purpose as hoppingy_2D_superconductor_pincher. | def onsite_2D_superconductor_pincher(site,p):
return (2*(p.tx_SC_pincher+p.ty_SC_pincher) - p.mu_SC_pincher)*tau_z + p.Ez_2D_S*sigma_y/2. + p.Delta_pincher*tau_x | [
"def onsite_1D_superconductor_pincher(site,p):\n\tEz_eff = p.Ez\n\treturn (2*p.ty_SC_pincher - p.mu_SC_pincher)*tau_z + Ez_eff*sigma_y/2. + p.Delta_pincher*tau_x",
"def onsite_2D_superconductor_lead(site,p):\n\n\n\treturn (2*(p.tx_SC_lead+p.ty_SC_lead) - p.mu_SC_lead)*tau_z + p.Ez_2D_S_lead*sigma_y/2. + p.Delta_S... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Onsite energy of 1D superconductor, e.g. used for same purpose as hoppingy_2D_superconductor_pincher. | def onsite_1D_superconductor_pincher(site,p):
Ez_eff = p.Ez
return (2*p.ty_SC_pincher - p.mu_SC_pincher)*tau_z + Ez_eff*sigma_y/2. + p.Delta_pincher*tau_x | [
"def getEnergy(self) -> float:\n ...",
"def energy(self):\n return self.kinetic() + self.potential()",
"def energy(self,mu):\r\n\t\t\r\n\t\treturn -sum(sum(self.weight[i,j]*self.x[i]*self.x[j] for j in range(self.N)) for i in range(self.N))",
"def onsite_2D_superconductor_pincher(site,p):\n\n\tr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Onsite energy of 2D superconducting lead, e.g. used for same purpose as hoppingy_2D_superconductor_lead. | def onsite_2D_superconductor_lead(site,p):
return (2*(p.tx_SC_lead+p.ty_SC_lead) - p.mu_SC_lead)*tau_z + p.Ez_2D_S_lead*sigma_y/2. + p.Delta_SC_lead*tau_x | [
"def getEnergy(self) -> float:\n ...",
"def onsite_2D_superconductor_pincher(site,p):\n\n\treturn (2*(p.tx_SC_pincher+p.ty_SC_pincher) - p.mu_SC_pincher)*tau_z + p.Ez_2D_S*sigma_y/2. + p.Delta_pincher*tau_x",
"def _analytical_encircled_energy(fno, wavelength, points):\n p = points * e.pi / fno / wavel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Hopping energy in xdirection of 1D system with proximitized superconductivity. Parameters see onsite function | def hoppingx(site0,site1,p):
# print("%s: in hoppingx()" %str(misc.round_time(datetime.datetime.now(),round_to=60)))
return -p.tx*tau_z + 1j*p.alphahbar/(2.*p.ax)*sigma_ytau_z | [
"def onsite_1D_superconductor_pincher(site,p):\n\tEz_eff = p.Ez\n\treturn (2*p.ty_SC_pincher - p.mu_SC_pincher)*tau_z + Ez_eff*sigma_y/2. + p.Delta_pincher*tau_x",
"def onsite_2D_superconductor_pincher(site,p):\n\n\treturn (2*(p.tx_SC_pincher+p.ty_SC_pincher) - p.mu_SC_pincher)*tau_z + p.Ez_2D_S*sigma_y/2. + p.De... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if device is asymmetric (one Al strip) or symmetric (two Al strips). Returns | def check_asymm_device(p):
if len(p.right) == 0:
p.asymmetric = True # to be used when printing last blocks of the Hamiltonian
p.Nxasymmetric = len(p.left) + len(p.middle)
else:
p.asymmetric = False
return p.asymmetric | [
"def is_symmetric(self):\n return self._alph1 == self._alph2 \\\n and np.array_equal(self._matrix, np.transpose(self._matrix))",
"def is_symmetric(self):",
"def is_symmetric(self):\n M = self.parent().realization_of().Monomial()\n return M(self).is_symmetri... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make NN(S) subject to the calibration of the NS(Heff) system created in make_1D_NLeft_1D_S_Heff_No_NRight. Notes xcoordinate of the 1D semiconducting system is taken to be zero. xcoordinate of the 2D pincher layer is taken to be at +1. So the pincher layer is 1D, but implemented as a 2D Hamiltonian because it needs to ... | def make_1D_Nleft_1D_N_2D_S_2D_SMiddle_No_NRight(p,ppar):
print("%s: in make_1D_Nleft_1D_N_2D_S_2D_SMiddle_No_NRight()" %str(misc.round_time(datetime.datetime.now(),round_to=60)))
import kwant
sys = kwant.Builder()
sys[(lat(x,y) for x in [0] for y in range(p.Ny))] = onsite_1D_semiconductor
sys[kwant.builder.Ho... | [
"def change_cell(nsys0,X0):\n if X0.dtype != int:\n raise TypeError('X0.dtype is wrong.')\n if X0.shape != (3,3):\n raise TypeError('X0 has wrong shape.')\n X = np.array(X0,dtype=float)\n ncp = np.zeros(3,dtype=int)\n ncp[0] = X0[0,:].max()\n ncp[1] = X0[1,:].max()\n ncp[2] = X0[2... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make metallic lead that can be attached to sys (Builder) object with the same conservation_law and particle_hole symmetry as the 2D proximitized topological superconductor being considered. Has the width of par.middle, and is translationally invariant in the ydirection. | def make_lead(p):
sys_ = kwant.Builder(kwant.TranslationalSymmetry([0,1]),conservation_law=tinyarray.array(np.kron(s_z,I_x)),particle_hole=sigma_ytau_y) ## ???: symmetries - implementing complex conjugation?
sys_[(lat(x,0) for x in par.middle)] = (2*(p.tx+p.ty) - p.mu)*tau_z
sys_[kwant.builder.HoppingKind((1,0),lat... | [
"def make_1D_Nleft_1D_N_2D_S_2D_SMiddle_No_NRight(p,ppar):\n\tprint(\"%s: in make_1D_Nleft_1D_N_2D_S_2D_SMiddle_No_NRight()\" %str(misc.round_time(datetime.datetime.now(),round_to=60)))\n\n\timport kwant\n\n\tsys = kwant.Builder()\n\n\tsys[(lat(x,y) for x in [0] for y in range(p.Ny))] = onsite_1D_semiconductor \n\t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Run dynamic baseline policy. | def run_dynamic_policy(results_path, benchmark_name, num_episodes, seeds=np.arange(10)):
if benchmark_name not in NON_OPTIMAL_POLICIES:
print("No dynamic policy found for this benchmark")
policy = NON_OPTIMAL_POLICIES[benchmark_name]
run_policy(results_path, benchmark_name, num_episodes, policy, see... | [
"def add_baseline_op(self, scope = \"baseline\"):\n ######################################################\n ######### YOUR CODE HERE - 4-8 lines. ############\n\n self.baseline = build_mlp(self.observation_placeholder,\n 1,\n scope,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
1 BruteForce Traverse a and b, and use two variables x and y to store two integers. Let z = x + y. Create a new list c, representing z. x and y can be very large, refused by the interviewer. 2 List Operation O(M + N) O(M + N) Add x and y digit by digit from the start is not simple. We can not align two lists and we nee... | def solution(self, a, b):
def reverse_list(head):
p1 = None
p2 = head
while p2 is not None:
t = p2
p2 = p2.next
t.next = p1
p1 = t
return p1
a_r = reverse_list(a)
b_r = reverse_list(... | [
"def sum_list_lsd(first_list: LinkedList, second_list: LinkedList) -> int:\n result = 0\n carry = 0\n order = 1\n\n current_0 = first_list.head\n current_1 = second_list.head\n\n while current_0 and current_1:\n result += ((current_0.data + current_1.data + carry) % 10) * order\n car... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Intuition BFS O((MN) 2) O((MN) 2) Finding whether there exists a path or the shortest unweighted path, try BFS. Since we are trying to find the shortest path and the leaking will expand, there is no need to consider repeatedly visiting a grid. Hint 1 Use another queue to represent leakage, do not search the whole matri... | def solution(self, grid, m, n, x0, y0, x1, y1):
def check_exceed(x, y, m, n):
if x < 0 or x >= m:
return False
if y < 0 or y >= n:
return False
return True
def check_leak(leakage, x, y):
return leakage[x][y] == "*"
... | [
"def bfs(adj_matrix, Board, Source, Destination):\r\n\t\t# Initialize a queue and an array for storing whether the node has\r\n\t\t# been visited or not\r\n\t\tqueue = deque()\r\n\t\tvisited = [False for x in range(len(adj_matrix[0]))]\r\n\r\n\t\t# Distance array for storing the path length and prev_vert array\r\n\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create GUI for train model tab | def create_train_tab(self, tab_control):
train_tab = ttk.Frame(tab_control)
# Data dir selection
train_tab_data_dir_label = ttk.Label(train_tab, text="Data Dir : ").place(x=20, y=20)
train_tab_data_dir_entry = ttk.Entry(train_tab, width=70)
train_tab_data_dir_entry.place(x=110, y... | [
"def create_classifier_tab(self, tab_control):\n # Classifier data tab\n classifier_tab = ttk.Frame(tab_control)\n classifier_tab_data_dir_label = ttk.Label(classifier_tab, text=\"Data Dir : \").place(x=20, y=20)\n classifier_tab_data_dir_entry = ttk.Entry(classifier_tab, width=70)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create GUI for align data tab | def create_align_tab(self, tab_control):
# Align data tab
align_data_tab = ttk.Frame(tab_control)
align_data_tab_data_dir_label = ttk.Label(align_data_tab, text="Data Dir : ").place(x=20, y=20)
align_data_tab_data_dir_entry = ttk.Entry(align_data_tab, width=70)
align_data_tab_dat... | [
"def create_tabs(self):\n\n # Tabs\n self.create_setup_tab()\n self.create_part_location_tab()\n self.create_order_tab()\n self.create_challenge_tab()\n self.tab_control.pack(expand=1, fill=\"both\", padx=5, pady=5)",
"def __create_tabs(self):\r\n self.tab1 = tk.Fr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create GUI for classifier Tab | def create_classifier_tab(self, tab_control):
# Classifier data tab
classifier_tab = ttk.Frame(tab_control)
classifier_tab_data_dir_label = ttk.Label(classifier_tab, text="Data Dir : ").place(x=20, y=20)
classifier_tab_data_dir_entry = ttk.Entry(classifier_tab, width=70)
classifi... | [
"def create_image_recognition_tab(self, tab_control):\n image_recog_tab = ttk.Frame(tab_control)\n image_recog_tab_data_dir_label = ttk.Label(image_recog_tab, text=\"Image file\").place(x=20, y=20)\n image_recog_tab_data_dir_entry = ttk.Entry(image_recog_tab, width=70)\n image_recog_tab_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create GUi for image recognition tab | def create_image_recognition_tab(self, tab_control):
image_recog_tab = ttk.Frame(tab_control)
image_recog_tab_data_dir_label = ttk.Label(image_recog_tab, text="Image file").place(x=20, y=20)
image_recog_tab_data_dir_entry = ttk.Entry(image_recog_tab, width=70)
image_recog_tab_data_dir_en... | [
"def main():\n lbls = imageio.v2.imread(Path(\"sample_data/test_labels.tif\"))\n lbls2 = np.zeros_like(lbls)\n lbls2[:, 3:, 2:] = lbls[:, :-3, :-2]\n lbls2 = lbls2 * 20\n\n labels = np.unique(lbls)[1:]\n labels_2 = np.unique(lbls2)[1:]\n\n viewer = napari.Viewer()\n lbls_layer = viewer.add_l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Select directory and set the directory absolute path to entry | def select_dir(self, entry: Entry):
entry.delete(0, END)
filename = filedialog.askdirectory()
entry.insert(0, filename) | [
"def choose_dir(self):\n self.output_dir.set(filedialog.askdirectory())",
"def ask_dir(self):\n\t\targs ['directory'] = askdirectory(**self.dir_opt) \n\t\tself.dir_text.set(args ['directory'])",
"def setDirectory(*args, **kwargs):\n \n pass",
"def set_dirname(self, dirname):\n self.dir... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get Bamboo plan key. | def plan_key(self):
return self.__plan_key | [
"def encode_plan_key(self, job_id, state):\n return \"%s@%s\" % (state, job_id)",
"def _get_key(sample, project):\n return sample + \".\" + project",
"def runningclub_key(runningclub_name):\n#----------------------------------------------------------------------\n keyname = '.userpw.{}'.format(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get extra values to compound the url. | def url_extra_values(self):
return self.__url_extra_values | [
"def get_url_params(self, url_path):\n return self.url_rule.extract_params(url_path)",
"def _GetUrlParams(self, query=None):\n params = sum([c_w_c._GetUrlParams() for c_w_c in self.reactants], [])\n params.extend(self.aq_params._GetUrlParams())\n\n if query is not None:\n fo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the url mask to trigger builds. | def trigger_plan_url_mask(self):
return self.__trigger_plan_url_mask | [
"def artifact_url_mask(self):\n return self.__artifact_url_mask",
"def query_plan_url_mask(self):\n return self.__query_plan_url_mask",
"def latest_queue_url_mask(self):\n return self.__latest_queue_url_mask",
"def plan_results_url_mask(self):\n return self.__plan_results_url_mask"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the url mask to stop the current running plan. | def stop_plan_url_mask(self):
return self.__stop_plan_url_mask | [
"def query_plan_url_mask(self):\n return self.__query_plan_url_mask",
"def trigger_plan_url_mask(self):\n return self.__trigger_plan_url_mask",
"def plan_results_url_mask(self):\n return self.__plan_results_url_mask",
"def latest_queue_url_mask(self):\n return self.__latest_queue_u... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get plan results url mask. | def plan_results_url_mask(self):
return self.__plan_results_url_mask | [
"def query_plan_url_mask(self):\n return self.__query_plan_url_mask",
"def trigger_plan_url_mask(self):\n return self.__trigger_plan_url_mask",
"def stop_plan_url_mask(self):\n return self.__stop_plan_url_mask",
"def artifact_url_mask(self):\n return self.__artifact_url_mask",
"d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the query url mask. | def query_plan_url_mask(self):
return self.__query_plan_url_mask | [
"def query_url(self):\n return self._query_url",
"def plan_results_url_mask(self):\n return self.__plan_results_url_mask",
"def getParamMask(self):\n return _core.CGPopt_getParamMask(self)",
"def get_ipmask(self):\n return self._fields['ipmask']",
"def latest_queue_url_mask(self)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get latest queue url mask. | def latest_queue_url_mask(self):
return self.__latest_queue_url_mask | [
"def queue_url(self) -> pulumi.Output[str]:\n return pulumi.get(self, \"queue_url\")",
"def query_plan_url_mask(self):\n return self.__query_plan_url_mask",
"def artifact_url_mask(self):\n return self.__artifact_url_mask",
"def getQueueURL():\n q = SQS.get_queue_url(QueueName='Restaura... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get artifact url mask. | def artifact_url_mask(self):
return self.__artifact_url_mask | [
"def query_plan_url_mask(self):\n return self.__query_plan_url_mask",
"def latest_queue_url_mask(self):\n return self.__latest_queue_url_mask",
"def artifact_urls(self):\n data = self._api.get_api_data()\n artifacts_node = data['artifacts']\n retval = []\n\n for node in... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Trigger a build using Bamboo API. | def trigger_plan_build(self, bamboo_server=None, plan_key=None, req_values=None):
if not bamboo_server and not self.bamboo_server:
return {'content': "No Bamboo server supplied!"}
if not plan_key:
return {'content': "Incorrect input provided!"}
# Execute all stages by ... | [
"def RunBuildCmd(wspath, prj, bc):\n # TODO: Continue coding from here\n pass",
"def trigger_build(repository, payload_data):\n access_token = os.environ.get('QUAYIO_ACCESSTOKEN')\n quayio_apiurl = 'https://quay.io/api/v1/repository'\n\n if not access_token:\n raise RuntimeError(\"QUAYIO_ACC... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Query a plan build using Bamboo API. | def query_plan(self, bamboo_server=None, plan_key=None, query_type=None):
if not bamboo_server and not self.bamboo_server:
return {'content': "No Bamboo server supplied!"}
if not plan_key or not query_type:
return {'content': "Incorrect input provided!"}
self.bamboo_se... | [
"def stop_build(self, bamboo_server=None, plan_key=None, query_type=None):\n\n if not bamboo_server and not self.bamboo_server:\n return {'content': \"No Bamboo server supplied!\"}\n\n if not plan_key:\n return {'content': \"No Bamboo plan key provided!\"}\n\n self.bamboo_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Download artifacts from Bamboo plan. | def get_artifact(self, bamboo_server=None, plan_key=None, query_type=None, job_name=None, artifact_name=None,
url_extra_values=None, destination_file=None):
if not bamboo_server and not self.bamboo_server:
return {'content': "No Bamboo server supplied!"}
if not plan_ke... | [
"def download(self, nexus_hostname, target_dir):\n url = self.get_url(nexus_hostname)\n target_file = os.path.join(target_dir, self.filename)\n print(\"Will try to download from: %s and save as %s\" % (url, target_file))\n curl_args = ['curl', '-sSLA', 'fabric-deploy', url, '-o', target_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Stop a running plan from Bamboo using Bamboo API. | def stop_build(self, bamboo_server=None, plan_key=None, query_type=None):
if not bamboo_server and not self.bamboo_server:
return {'content': "No Bamboo server supplied!"}
if not plan_key:
return {'content': "No Bamboo plan key provided!"}
self.bamboo_server = bamboo_s... | [
"def StopBlp(self, request, context):\n context.code(beta_interfaces.StatusCode.UNIMPLEMENTED)",
"def stop(self):\n self.logger.debug('Server - td-agent-bit - stop call.')\n self.change_service_status(\"stop\")",
"def test_stop_running_job(self, db_session: Session) -> None:\n pass # TO... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Metodo que genera la matriz de rotacion para aplicar el pulso. Esta matriza es nx3x3, ya que es una matriz 3x3 para cada sitio. input | def generar_matriz_R(self, tp):
# modulo del campo en el plano xy
B1 = np.array([self.Bx, self.By])
B1 = np.linalg.norm(B1, axis=0)
# tres componentes de la direccion de rotacion. Cada U es un array de
# n elementos, uno por cada sitio. Uz son ceros porque el campo en z
... | [
"def getRotationMatrix( self):",
"def rotation_matrix(self) -> Tensor:\n return self.extrinsics[..., :3, :3]",
"def rotar(matriz, NAXIS1, NAXIS2, angulo):\n\n matriz = NDData(matriz)\n if (angulo > 360 or angulo < 1):\n print \"<Error: Imagen no rotada, angulo no permitido>\"\n return... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Displays the scatterplot of repeatedly applying function to the elements of inputs. X axis = input Y axis = function(input) | def show_scatter_plot(inputs, function, x_label, y_label):
inps = list(inputs)
plot.scatter(inps, [function(x) for x in inps])
plot.xlabel(x_label)
plot.ylabel(y_label)
plot.show() | [
"def show_scatterplot(self, *args, **kwargs):\n raise NotImplementedError()",
"def plot_results(my_func, my_points, min_x=-30, max_x=30, min_y=-30, max_y=30, nbx=100, nby=100, title=\"Title\"):\n X = np.linspace(min_x, max_x, num=nbx)\n Y = np.linspace(min_y, max_y, num=nby)\n Z=np.zeros((nbx,nby)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
(numpy.array, int, int) > numpy.array Creates a 4D, readonly view of some 2D numpy array as a 2D array of 2D patches. There are (arr_height x arr_width) patches and each patch is of size (patch_h, patch_w) | def patch_view(arr, patch_h, patch_w):
assert len(arr.shape) == 2
# Numpy stride code examples (magic):
# https://stackoverflow.com/questions/16774148/
# https://github.com/keras-team/keras/issues/2983
# New height and width are now going to be in terms of
# number of overlapping patches we ca... | [
"def make_array_2d(arr):\n if arr.ndim == 1:\n arr.shape = (arr.shape[0], 1)",
"def split_image_into_overlapping_patches(image_array, patch_size, padding_size=2):\n \n xmax, ymax, _ = image_array.shape\n x_remainder = xmax % patch_size\n y_remainder = ymax % patch_size\n \n # modulo he... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
(int > numpy.array) Creates a 2Dboolean mask of a circle with radius radius. Returns a 2D, square array with side length size 2radius + 1 | def circular_mask(radius):
diameter = 2*radius + 1
center_x = center_y = radius
x, y = np.indices((diameter, diameter))
distances = ((center_x - x) ** 2 + (center_y - y) ** 2) ** 0.5
return (distances <= radius) | [
"def create_2d_circle_kernel(radius):\n return np.array([ np.sqrt( x * x + y * y ) <= float(radius) for y in xrange(-radius, radius+1) for x in xrange(-radius, radius+1)], dtype=np.float32).reshape( radius*2+1, radius*2+1 )",
"def gen_radial_mask(shape, center, radius, mask=True,\n xy_scale=... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts keypoints into a numpy array of form [[x, y]] | def keypoints_to_coords(keypoints):
return np.array([kp.pt for kp in keypoints]) | [
"def get_gt_keypoints_array(eval_annotations):\n keypoints_list = []\n for eval_record in eval_annotations:\n keypoints_record = []\n\n keypoints = eval_record['joint_self']\n for keypoint in keypoints:\n #only pick (x,y) and drop is_visible\n keypoints_record.append... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes the affine transform of coords (form [[x, y]]) with transform_matrix. | def affine_transform(coords, transform_matrix):
# Add ones onto the end of every row, then transpose the matrix (columns are [x, y, 1])
num_pts, num_dims = coords.shape
with_ones = np.ones((num_pts, num_dims + 1))
with_ones[:, :-1] = coords
with_ones = with_ones.transpose()
# Array of ... | [
"def matrix_transform(coords, matrix):\n return ProjectiveTransform(matrix)(coords)",
"def affine_transform(pt, trans_mat):\n new_pt = np.array([pt[0], pt[1], 1.]).T\n new_pt = np.dot(trans_mat, new_pt)\n return new_pt[:2]",
"def affine(self):\n return Affine(*self.transform)",
"def transfo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Draws the polygon whose corner points are specified in clockwise order in polygon_clockwise (array of form [[x, y]]) onto a copy of img. | def draw_polygon(img, polygon_clockwise, color, thickness):
ret = np.copy(img)
num_corners = polygon_clockwise.shape[0]
for i in range(num_corners):
# Figure out which points to connect together
left_ind, right_ind = (i % num_corners), ((i + 1) % num_corners)
left, rig... | [
"def visualize_affine_transform(polygon_clockwise, img, transform_matrix):\n \n # Transform the given polygon's corner points into new space\n new_poly = affine_transform(polygon_clockwise, transform_matrix)\n \n # Return the polygon drawn on the image\n return draw_polygon(img, new_poly, (0, 255,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Visualizes the affine transformation of transform_matrix by drawing a quadrilateral (corner points specified by quadr, an array of form [[x, y]], clockwise order) onto a copy of right_img. | def visualize_affine_transform(polygon_clockwise, img, transform_matrix):
# Transform the given polygon's corner points into new space
new_poly = affine_transform(polygon_clockwise, transform_matrix)
# Return the polygon drawn on the image
return draw_polygon(img, new_poly, (0, 255, 0), 3) | [
"def plot_proj_origin(chessPic, mtx, R, T, chess_dim, chess_case_len):\n pic = Image.open(chessPic)\n Rmat = np.matrix(np.zeros((3,3)))\n cv2.Rodrigues(R, Rmat)\n mat_pass = np.matrix(np.zeros((3, 4)))\n mat_pass[:, :3] = Rmat\n mat_pass[:, 3] = T\n\n plt.imshow(pic, cmap=\"gray\")\n\n x_gri... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Algorithm (assume number of color channels identical) 1) Acquire SIFT keypoints and descriptors across each color channel 2) Match SIFT descriptors WITHIN color channels Produce an array of form [[i, j, dist, channel]], where i index of the keypoint/descriptor in left_img j index of the keypoint/descriptor in right_img... | def visualize_sift_color_matches(left_img, right_img, threshold, k):
# Images should have same shape and number of color channels
assert [len(left_img.shape), len(right_img.shape)] == [3, 3]
assert left_img.shape[-1] == right_img.shape[-1]
# Grab number of colors (should be last element of sha... | [
"def findMatchesBetweenImages(image_1, image_2, num_matches):\n # matches - type: list of cv2.DMath\n matches = None\n # image_1_kp - type: list of cv2.KeyPoint items.\n image_1_kp = None\n # image_1_desc - type: numpy.ndarray of numpy.uint8 values.\n image_1_desc = None\n # image_2_kp - type: ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
determine rank of a card. | def rank_card(card):
return RANKS[card[0]] | [
"def rank(card):\n\n if card % 100 == 1:\n return ' A'\n elif card % 100 == 11:\n return ' J'\n elif card % 100 == 12:\n return ' Q'\n elif card % 100 == 13:\n return ' K'\n else:\n return card % 100",
"def relative_rank(self, card):\n if card is None:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return ``dict`` containing extended_properties names and values. | def get_extended_properties_dict(self):
properties = {}
for prop in self.extended_properties:
if prop.delete is False:
properties[prop.name] = prop.value
return properties | [
"def get_extended_properties_list(self):\n properties = []\n for prop in self.extended_properties:\n if prop.delete is False:\n new_prop = {\n 'name': prop.name,\n 'value': prop.value,\n 'type': prop.type,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return ``list`` containing ``dict``s of extended properties details. | def get_extended_properties_list(self):
properties = []
for prop in self.extended_properties:
if prop.delete is False:
new_prop = {
'name': prop.name,
'value': prop.value,
'type': prop.type,
'guid... | [
"def get_extended_properties_dict(self):\n properties = {}\n for prop in self.extended_properties:\n if prop.delete is False:\n properties[prop.name] = prop.value\n return properties",
"def getExtendedProperties(self,):\n\n\t\turl = MozuUrl(\"/api/commerce/carts/curr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add extended property to item. | def create_extended_property(self, name='', value='',
property_type='Attribute'):
prop = _ExtendedProperty(self)
prop.name = name
prop.value = value
prop.type = property_type
self.extended_properties.append(prop) | [
"def addExtendedProperties(self,extendedProperties):\n\n\t\turl = MozuUrl(\"/api/commerce/carts/current/extendedproperties\", \"POST\", UrlLocation.TenantPod, False);\n\t\tself.client.withResourceUrl(url).withBody(extendedProperties).execute();\n\t\treturn self.client.result();",
"def append_to_properties(self, i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find previous power of two | def prevpow2(i):
# do not use numpy here, math is much faster for single values
buf = np.floor(np.log(i) / np.log(2))
return int(np.power(2, buf)) | [
"def _nextpow2(self, val):\n\t\tval = val - 1\n\t\tval = (val >> 1) | val\n\t\tval = (val >> 2) | val\n\t\tval = (val >> 4) | val\n\t\tval = (val >> 8) | val\n\t\tval = (val >> 16) | val\n\t\tval = (val >> 32) | val\n\t\treturn np.log2(val + 1)",
"def closest_power_2(x):\n Max_power = int((log(x-0.1,2)))\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if the user has enough balance | async def balance_check(self, user_id: int, guild_id: int, amount: int) -> bool:
balance = await self.currency_repository.get(user_id, guild_id)
if not bool(balance.amount >= amount):
raise NotEnoughBalance
return True | [
"async def above_balance(self, ctx, user):\r\n await ctx.send(f\"{user.mention} You exceeded your game balance. \" +\r\n \"Please wager a new amount.\")",
"def test_balance(self):\n response = self.auth('user')\n self.assertEquals(response.json()['results'][0]['user_bala... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests reading an R6 MAP file, specifically M01 | def test_R6_MAP_Structure(self):
settings = load_settings(TEST_SETTINGS_FILE)
map_filepath = path.join(settings["gamePath_R6_EW"], "data", "map", "m01", "M01.map")
loadedFile = MAPLevelReader.MAPLevelFile()
readSucessfullyToEOF = loadedFile.read_file(map_filepath)
self.assertT... | [
"def test_load_all_R6_maps(self):\n settings = load_settings(TEST_SETTINGS_FILE)\n\n discovered_files = gather_files_in_path(\".MAP\", settings[\"gamePath_R6_EW\"])\n\n for map_filepath in discovered_files:\n if map_filepath.endswith(\"obstacletest.map\") or map_filepath.endswith(\"m... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests reading materials from an R6 MAP file | def test_R6_MAP_Materials(self):
settings = load_settings(TEST_SETTINGS_FILE)
map_filepath = path.join(settings["gamePath_R6_EW"], "data", "map", "m02", "mansion.map")
loadedFile = MAPLevelReader.MAPLevelFile()
loadedFile.read_file(map_filepath)
#TODO: This is currently disabl... | [
"def test_R6_MAP_Structure(self):\n settings = load_settings(TEST_SETTINGS_FILE)\n\n map_filepath = path.join(settings[\"gamePath_R6_EW\"], \"data\", \"map\", \"m01\", \"M01.map\")\n\n loadedFile = MAPLevelReader.MAPLevelFile()\n readSucessfullyToEOF = loadedFile.read_file(map_filepath)\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Attempt to load and validate the sections of each map in the directory | def test_load_all_R6_maps(self):
settings = load_settings(TEST_SETTINGS_FILE)
discovered_files = gather_files_in_path(".MAP", settings["gamePath_R6_EW"])
for map_filepath in discovered_files:
if map_filepath.endswith("obstacletest.map") or map_filepath.endswith("mansion.map") or ma... | [
"def test_R6_MAP_Structure(self):\n settings = load_settings(TEST_SETTINGS_FILE)\n\n map_filepath = path.join(settings[\"gamePath_R6_EW\"], \"data\", \"map\", \"m01\", \"M01.map\")\n\n loadedFile = MAPLevelReader.MAPLevelFile()\n readSucessfullyToEOF = loadedFile.read_file(map_filepath)\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get metrics from training log file. | def get_metrics_from_log(fn: str) -> List[Dict[str, List[float]]]:
# Create a list for each trained model
ensemble = []
# Open the log file
with open(fn) as f:
# Read lines into a list
lines = f.readlines()
# Iterate
for line in lines:
# Add a new item when r... | [
"def load_metrics(path) -> None:\n logger.info(f\"Loading metrics from '{path}'\")\n state_dict = torch.load(path, map_location=device)\n return state_dict['train_loss_list'], state_dict['valid_loss_list'], state_dict['global_steps_list']",
"def get_val_losses(log_file : str):\n losses = []\n ctr =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate mean, min5 and max95 for each ensemble metric. | def calculate_stats(
ensemble: List[Dict[str, List[float]]]
) -> Tuple[Dict[str, np.ndarray], Dict[str, np.ndarray], Dict[str, np.ndarray]]:
# Create empty dictionaries
mean = {"training_losses": [], "validation_losses": [], "balanced_accuracy": []}
min5 = {"training_losses": [], "validation_losses": []... | [
"def ml_mean(values):\n\n # return the equation for mean\n return sum(values)/len(values)",
"def get_mean_basin_performance(metrics: dict, model: str) -> Dict:\n seeds = [k for k in metrics[model].keys() if k != \"ensemble\"]\n metric = defaultdict(list)\n for seed in seeds:\n for basin, nse... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes all characters from string 'nickname', that are not alphanumeric or '_' or '.' | def make_valid_nickname(nickname):
return re.sub('[^a-zA-Z0-9_\.]', '', nickname) | [
"def clean_usernames(text):\n return re.sub(\"@[^\\s]+\", \"\", str(text))",
"def clean_name(name):\n return name.strip()",
"def normalize_username(name):\n underscores = re.sub(r'\\s', '_', name)\n single_space = re.sub(r'_+', ' ', underscores)\n trimmed = single_space.strip()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if nickname already exists in DB. If so appends number to nickname and checks again until nickname does not exists in DB. Returns this nickname. | def make_unique_nickname(nickname):
if User.query.filter_by(nickname=nickname).first() is None:
return nickname
version = 2
while True:
new_nickname = nickname = str(version)
if User.query.filter_by(nickname=new_nickname).first() is None:
break... | [
"def find_by_id(cls, name_id: int):\n nickname = None\n if name_id:\n nickname = cls.query.get(name_id)\n return nickname",
"def get_nickname():\n\n return User.query.get(nickname)",
"def _check_existing_nickname(nickname):\n return g.con.get_user(nickname) is not None",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the area of the ring Return the area of the outer ring with radius outer. The radius of the hole is inner. | def area_of_ring(outer, inner):
return area_of_disk(outer) - area_of_disk(inner) | [
"def calculate_area(self):\n return Circle.PI * self.radius**2",
"def area_of_a_circle(radius):\n return np.pi * radius ** 2",
"def circle_area(radius):\n return numpy.pi*radius**2",
"def area_of_circle(radius: float) -> float:\n return pi * pow(radius, 2)",
"def circumference_area(radius):... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the lateral surface area of a right circular cone with height h and radius r | def area_of_cone(h, r):
return math.pi * r * math.sqrt(r ** 2 + h ** 2) | [
"def right_circular_cone(r,h):\n s = sqrt((r**2) + (h**2))\n return s",
"def cone_area(d, h):\n r = d / 2\n surface_area = np.pi * r * (r + (h ** 2 + r ** 2) ** (1 / 2)) # - np.pi * r**2\n return surface_area",
"def sphere_cap_area(h, R):\n return 2*np.pi*R*(R-h)",
"def circle_area(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the volume of the smaller sphere within the bigger sphere | def hollow_sphere(bigger, smaller):
return volume_of_sphere(bigger) - volume_of_sphere(smaller) | [
"def sphere_volume(radius: Number) -> Number:\n return (4.0/3.0) * pi * radius * radius * radius",
"def sphere_volume(r):\n return (3.0/4.0)*pi*r**3",
"def multiple_spheres_volume(radius: float, num_spheres: int) -> float:\n\n #Your code here",
"def volume_spherical_shell(r1, r2):\n vol1 = volume_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Testing the get_channel method with specific ID and expected data | def test_get_channel(self):
channel = api.get_channel(self.channel["id"])
self.assertEqual(channel.id, self.channel["id"])
self.assertEqual(channel.name, self.channel["name"]) | [
"def test_should_get_a_channel_by_id(self):\n\n response = self.client.get(\n '/api/v3/channel/1/',\n content_type='application/json',\n HTTP_AUTHORIZATION=self.auth)\n\n self.assertEqual(200, response.status_code)",
"def testRetrieveChannel(self):\n self.asse... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Testing the create_dm method with specific recipient ID and expected mock data | def test_create_dm(self):
dms = api.create_dm(406882130577063956)
self.assertEqual(int(dms.recipients[0].id), 406882130577063956) | [
"def test_dm_recipient(self):\n msg = {\n \"id_str\": \"1\",\n 'text': 'This is a dm.',\n \"sender_id\": 1,\n \"sender_id_str\": \"1\",\n \"sender_screen_name\": \"fakeuser\",\n \"sender\": {},\n \"recipient_id\": 2,\n \"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Testing the modify_current_user method with specific ID and expected mock data | def test_modify_current_user(self):
modified_user = api.modify_current_user({"username": "Ahnaf"})
self.assertEqual(modified_user.id, self.me["id"])
self.assertEqual(modified_user.username, "Ahnaf") | [
"def test_update_yourself_non_manager(self):\n user = User.objects.create_user(\n username=\"non-admin zeiyeGhaoXoh4awe3xai\",\n password=\"non-admin chah1hoshohN5Oh7zouj\",\n )\n client = APIClient()\n client.login(\n username=\"non-admin zeiyeGhaoXoh4aw... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Testing the leave_guild method with specific ID and expected mock data. | def test_leave_guild(self):
left = api.leave_guild(self.leave_guild)
self.assertEqual(left, 204) | [
"def test_team_leave(self):\r\n self.test_team_join_approve()\r\n url = reverse('team_leave', args=[self.project.slug, self.language.code])\r\n DATA = {'team_leave' : 'Leave'}\r\n resp = self.client['registered'].post(url, DATA, follow=True)\r\n self.assertContains(resp, 'You left... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The module requires an email and password for EoBot to function, and will automatically lookup and store the user ID for use in future requests | def __init__(self, email, password):
self.url_base = "https://www.eobot.com/api.aspx?"
self.email = str(email)
self.password = str(password)
self.debug = 0
url = self.url_base + 'email=' + self.email + '&password=' + self.password
self.user_id = (requests.get(url, t... | [
"def auth(client, email, password): # pragma: no cover\n user = User.authenticate(client, email, password)\n click.echo(user.meta.api_token)",
"def _fixture_user(self):\n user_model = get_user_model()\n user = user_model.objects.get(email='r2d2@naboo.gov') # r2's password = 'bleep'\n self.clien... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the current value for a Coin, expects the EoBot coin ID string | def get_coin_value(self, coin):
url = self.url_base + 'coin=' + str(coin)
if self.debug == 1:
print url
try:
result = requests.get(url, timeout=self.timeout)
except requests.exceptions.RequestException as exception:
print exception
... | [
"def coins(player):\n return player['coins']",
"def get_coin_balance(self, coin):\r\n totals = self.get_all_balances()\r\n if coin in totals.keys():\r\n if self.debug == 1:\r\n print coin\r\n\r\n return float(totals[coin])\r\n else:\r\n retur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return set email, shouldn't need this, maybe for debugging | def get_email(self):
return self.email | [
"def email(self, value):\n match = email_pattern(value)\n if match:\n self._email = value\n return\n assert 0, 'Invalid email'",
"def set_Email(self, value):\n super(UpdateTicketInputSet, self)._set_input('Email', value)",
"def email(self):\n return '{}.{... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the currently mining coin for the user account | def get_mining_coin(self):
url = self.url_base + "idmining=" + self.user_id
if self.debug == 1:
print url
try:
coin = (requests.get(url, timeout=self.timeout)).text
except requests.exceptions.RequestException as exception:
print exception
... | [
"def get_account_information(self, coin):\n\n accounts = self.auth_client.get_accounts()\n for account in accounts:\n if coin in account['currency']:\n return float(account['available'])\n\n return None",
"def coins(player):\n return player['coins']",
"async def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a specific coin balance for your account, requires a EoBot Coin String | def get_coin_balance(self, coin):
totals = self.get_all_balances()
if coin in totals.keys():
if self.debug == 1:
print coin
return float(totals[coin])
else:
return 'Bad Coin' | [
"def balance(ctx, address):\n if address == '':\n address = config.PUBLIC_KEY.to_bytes().hex()\n id__address, address = normalize_address(address, asHex=True)\n if VERBOSE:\n app_log.info(f\"Get balance for address {address}\")\n assert(len(address) == 64) # TODO: better user warning\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a dict with all mining speeds | def get_all_speeds(self):
url = self.url_base + "idspeed=" + self.user_id
if self.debug == 1:
print url
try:
speed_raw = (requests.get(url, timeout=self.timeout)).text
except requests.exceptions.RequestException as exception:
print exception... | [
"def get_speed(self):\n std_out, _, _ = self.run_command(\"speedtest-cli --simple\", default_asserts=True)\n print(std_out)\n\n current_ping = float(std_out[0].replace('Ping: ', '').replace(' ms', ''))\n current_download = float(std_out[1].replace('Download: ', '').replace(' Mbit/s', '')... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a specific mining speed, requires a EoBot mining type string | def get_one_speed(self, m_type):
speeds = self.get_all_speeds()
if m_type in speeds.keys():
if self.debug == 1:
print m_type
return speeds[m_type]
else:
return 'Bad Mining Type' | [
"def _get_speed(self):\n reply = self.query(command = b'/1?37\\r', port = self.port)\n number = reply['value']\n debug('get_speed(): reply = {}, and number = {}'.format(reply,number))\n return reply",
"def way_speed(way):\n return way['tags'].get('maxspeed_mph',DEFAULT_SPEED_LIMIT_M... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the mining coin on your account, requires a EoBot Coin String Will return string Success on success and ERROR if not. | def set_mining_coin(self, coin):
url = self.url_base + "id=" + self.user_id + "&email=" + self.email + "&password=" + self.password + \
"&mining=" + coin
if self.debug == 1:
print url
try:
requests.post(url, timeout=self.timeout)
except requ... | [
"def get_mining_coin(self):\r\n url = self.url_base + \"idmining=\" + self.user_id\r\n\r\n if self.debug == 1:\r\n print url\r\n\r\n try:\r\n coin = (requests.get(url, timeout=self.timeout)).text\r\n except requests.exceptions.RequestException as exception:\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a desposit wallet address for the EoBot Coin String | def get_deposit_address(self, coin):
url = self.url_base + "id=" + self.user_id + '&deposit=' + str(coin)
if self.debug == 1:
print url
try:
result = requests.get(url, timeout=self.timeout)
except requests.exceptions.RequestException as exception:
... | [
"async def get_deposit_address(self, **params):\r\n return await self.client_helper(\"get_deposit_address\", **params)",
"def current_address():\n return wallet['obj'].current_address",
"def get_address_for_account(email):\n query = (email, )\n conn = sqlite3.connect(WALLET_KEYS)\n c = conn.c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Withdraw currency from the specified coin string, in the specified amount, to the specified wallet | def withdraw_currency(self, coin, amount, wallet):
url = self.url_base + 'id=' + self.user_id + '&email=' + self.email + '&password=' + self.password + \
'&manualwithdraw=' + coin + '&amount=' + str(amount) + '&wallet=' + wallet
if self.debug == 1:
print url
tr... | [
"async def deposit(self, ctx, amount):\n data = await BonfideCoin(self.bot).get(ctx.guild.id, ctx.author.id)\n if data is None:\n await self.add_to_db(ctx.guild.id, ctx.author.id)\n\n data = await BonfideCoin(self.bot).get(ctx.guild.id, ctx.author.id)\n\n # return error if bal... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates and prints n words, starting with the word w, and following the distribution of the language model. | def generate(self, w, n):
# YOUR CODE HERE
w = w.lower()
res = w + " "
ix = self.index[w]
for _ in range(n-1):
choices = []
weights = []
if ix in self.bigram_prob:
for k, v in self.bigram_prob[ix].items():
... | [
"def easy_words():\n length = random.randint(4,6)\n constraints = init_constraint(length)\n return ''.join(constraints)",
"def wordGenerator(maxLength=12):\n s=''\n wordLength=random.randint(4,maxLength)\n for i in range(wordLength):\n # return random integer\n s += chr(random.rand... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Is this a simulation. | def is_simulator(self) -> bool:
... | [
"def has_been_simulated(self):\n return self.simulated",
"def is_simulate(submodule):\r\n try: # Attempt to retrieve the key from the config file\r\n is_sim = config[submodule]['simulate']\r\n if not type(is_sim) is bool: # The key is not a boolean\r\n return False\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a Mark10 driver. | def create(cls, port: str, baudrate: int = 115200, timeout: float = 1) -> "Mark10":
conn = Serial()
conn.port = port
conn.baudrate = baudrate
conn.timeout = timeout
return Mark10(connection=conn) | [
"def create_generator(instr_info):\n from visa_generator import VisaGenerator\n from anritsu_generator import AnritsuGenerator\n \n # check if instrument is proper or simulated\n if instr_info['type'] == 'sim':\n rm = visa.ResourceManager('@sim')\n else:\n rm = visa.ResourceManager('... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sends an email via IFTTT webhook integration. | def send_email(msg: str) -> int:
url = f'https://maker.ifttt.com/trigger/qseek_post/with/key/{os.environ.get("IFTTT_KEY")}'
data = {"value1": msg}
logger.info(f'Sending email with body "{msg}"')
resp = requests.post(url, data=data)
if not resp.ok:
logger.error(f'Sending email failed with sta... | [
"def email_callback(self, ch, method, properties, body):\n send_email_message = SendEmailMessage.try_create_from_body(body, self.config)\n if send_email_message:\n email_send_id = send_email_message.send_email_id\n try:\n print(\"Sending email {} to bespin-api.\".f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Perform batch lookup on matrix M using indices idx. | def batch_lookup(M, idx, vector_output=True):
batch_size, w = M.size()
batch_size2, sample_size = idx.size()
assert(batch_size == batch_size2)
if sample_size == 1 and vector_output:
samples = torch.gather(M, 1, idx).view(-1)
else:
samples = torch.gather(M, 1, idx)
return samples | [
"def batch_lookup_3D(M, idx):\n batch_size, seq_len, dim = M.size()\n _, sample_size = idx.size()\n M = M.view(batch_size*seq_len, dim)\n offset = long_var_cuda(torch.arange(batch_size).unsqueeze(1))\n idx = idx + offset * seq_len\n idx = idx.view(-1)\n # [batch_size*sample_size, dim]\n feat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Perform batch look up on a 3D tensor M using indices idx. | def batch_lookup_3D(M, idx):
batch_size, seq_len, dim = M.size()
_, sample_size = idx.size()
M = M.view(batch_size*seq_len, dim)
offset = long_var_cuda(torch.arange(batch_size).unsqueeze(1))
idx = idx + offset * seq_len
idx = idx.view(-1)
# [batch_size*sample_size, dim]
features = torch.... | [
"def batch_binary_lookup_3D(M, b_idx, pad_value):\n # Pad binary indices\n batch_size = M.size(0)\n hidden_dim = M.size(2)\n seq_len = b_idx.sum(1, keepdim=True)\n max_seq_len = int(seq_len.max())\n output_masks = batch_arange_cuda(batch_size, max_seq_len) >= seq_len\n pad_len = max_seq_len - s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Perform batch look up on a 2D tensor M using a binary mask. | def batch_binary_lookup(M, b_idx, pad_value):
batch_size = M.size(0)
seq_len = b_idx.sum(1, keepdim=True)
max_seq_len = int(seq_len.max())
output_masks = batch_arange_cuda(batch_size, max_seq_len) >= seq_len
pad_len = max_seq_len - seq_len
max_pad_len = int(pad_len.max())
M = torch.cat([M, f... | [
"def batch_binary_lookup_3D(M, b_idx, pad_value):\n # Pad binary indices\n batch_size = M.size(0)\n hidden_dim = M.size(2)\n seq_len = b_idx.sum(1, keepdim=True)\n max_seq_len = int(seq_len.max())\n output_masks = batch_arange_cuda(batch_size, max_seq_len) >= seq_len\n pad_len = max_seq_len - s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Perform batch look up on a 3D tensor M using a binary mask. | def batch_binary_lookup_3D(M, b_idx, pad_value):
# Pad binary indices
batch_size = M.size(0)
hidden_dim = M.size(2)
seq_len = b_idx.sum(1, keepdim=True)
max_seq_len = int(seq_len.max())
output_masks = batch_arange_cuda(batch_size, max_seq_len) >= seq_len
pad_len = max_seq_len - seq_len
m... | [
"def batch_lookup_3D(M, idx):\n batch_size, seq_len, dim = M.size()\n _, sample_size = idx.size()\n M = M.view(batch_size*seq_len, dim)\n offset = long_var_cuda(torch.arange(batch_size).unsqueeze(1))\n idx = idx + offset * seq_len\n idx = idx.view(-1)\n # [batch_size*sample_size, dim]\n feat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Pack the hidden state of a BiLSTM s.t. the first dimension equals to the number of layers. | def pack_bidirectional_lstm_state(state, num_layers):
assert (len(state) == 2 * num_layers)
_, batch_size, hidden_dim = state.size()
layers = state.view(num_layers, 2, batch_size, hidden_dim).transpose(1, 2).contiguous()
state = layers.view(num_layers, batch_size, -1)
return state | [
"def unpack_bidirectional_lstm_state(state, num_directions=2):\n batch_size = state.size(1)\n new_hidden_dim = int(state.size(2) / num_directions)\n return torch.stack(torch.split(state, new_hidden_dim, dim=2), dim=1).view(-1, batch_size, new_hidden_dim)",
"def init_hidden(self):\n weight = next(s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Unpack the packed hidden state of a BiLSTM s.t. the first dimension equals to the number of layers multiplied by the number of directions. | def unpack_bidirectional_lstm_state(state, num_directions=2):
batch_size = state.size(1)
new_hidden_dim = int(state.size(2) / num_directions)
return torch.stack(torch.split(state, new_hidden_dim, dim=2), dim=1).view(-1, batch_size, new_hidden_dim) | [
"def pack_bidirectional_lstm_state(state, num_layers):\n assert (len(state) == 2 * num_layers)\n _, batch_size, hidden_dim = state.size()\n layers = state.view(num_layers, 2, batch_size, hidden_dim).transpose(1, 2).contiguous()\n state = layers.view(num_layers, batch_size, -1)\n return state",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Perform list or list_details action with given params and validates result. | def _list_by_param_value_and_assert(self, params, with_detail=False):
if with_detail:
fetched_vol_list = \
self.client.list_volumes(detail=True, params=params)
else:
fetched_vol_list = self.client.list_volumes(params=params)
# Validating params of fetched... | [
"def _get_list(self, list_title, list_id, action_result):\n endpoint = 'list/'\n params = {}\n if not list_id:\n params['name'] = list_title\n ret_val, found_list_info = self._make_rest_call(endpoint, action_result, method='get', params=params)\n\n if phantom.is... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes HPDI (Highest Posterior Density Interval), which is the inteval of minimum width that includes the given `probability` (or proportion of the numbers) The following code is based on from `hpd` function from | def hpdi(values, probability):
values = np.sort(values)
n = len(values)
interval_idx_inc = int(np.floor(probability * n))
n_intervals = n - interval_idx_inc
interval_width = values[interval_idx_inc:] - values[:n_intervals]
if len(interval_width) == 0:
raise ValueError("Too few elements... | [
"def highest_density_interval(samples, mass=.95):\n _samples = np.asarray(sorted(samples))\n n = len(_samples)\n\n interval_idx_inc = int(np.floor(mass * n))\n n_intervals = n - interval_idx_inc\n interval_width = _samples[interval_idx_inc:] - _samples[:n_intervals]\n\n if len(interval_width) == 0... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Build the cache key for a particular type of cached value | def cache_key(type, user_pk):
return CACHE_TYPES[type] % user_pk | [
"def _build_cache_key(self, *args):\n return self.key if not self.key_mod else self.key % tuple(args)",
"def gen_cache(self, key, value=None, type=Cache):\n if type == MultiHeadAttention.StaticCache: # static_kv\n k, v = self.compute_kv(key, value)\n return self.StaticCache(k,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |