query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Creates an Experiment with totaly artificial data. Experiment has one setup with two modalities, EMG and kin. EMG has four channels, KIN has three channels. Two sessions are "recorded" for two different subjects. All EMG recordings have sampling rate of 20Hz, all KIN recordings sampling rate of 5Hz. | def setup(cls):
cls.logger = logging.getLogger('ModelTestLogger')
cls.logger.setLevel(logging.DEBUG)
s1 = model.Subject('subject1')
s2 = model.Subject('subject2')
cls.experiment = model.Experiment()
cls.experiment.put_subject(s1)
cls.experiment.put_subject(s2)
... | [
"def newExperiment(self):\n experiment = Experiment()\n newtitle = 'Untitled ' + self.getNextUntitled()\n experimentFrame = SequenceFrame(self, experiment, True, newtitle)\n experiment.setInteractionParameters(parentFrame=experimentFrame,\n graphManagerC... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
provides a number to sort related in ascending length of description | def sorter(r):
ans = len(r.description)
if additional:
for rr in r.monkey_additional:
ans += len(rr)
return ans | [
"def lenSort(e):\n return len(e)",
"def Order(self) -> int:",
"def _natural_sort_worksheet(x):\n l = re.findall(r\"\\d+$\", x.title)\n if l:\n return int(l[0])\n\n return -1",
"def get_sort_key(self, item):\n return item.number",
"def order1(e):\n return len(e[1])",
"def bigSo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialise with a MIP document | def __init__(self, document):
self._settemplates(self.onecol, self.twocol)
assert document.type_key == 'cim.2.designing.Project'
self.doc = document
# We will populate the "mip" variable with the mip era
self.mips = 'CMIP6'
self.related = []
for r in self.doc.r... | [
"def init_document(self, _, value):\n document = IamPolicy.Document(value)\n self.init_default_attr(\"document\", document)",
"def __init__(__self__,\n resource_name: str,\n args: DocumentArgs,\n opts: Optional[pulumi.ResourceOptions] = None):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
make sure the html output works | def testHTML(self):
html = self.E.html() | [
"def _process_html(self):\n pass",
"def render_html(self) -> str:",
"def test_error_html_using_patch(self):\n pass",
"def test_prep_fields_called_html_output(self):\n pass",
"def test_render_self_closing(self):\n self.body.append(self.para)\n self.body.append(self.horz)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
For example purposes, we do not remove the outputs, which is why this is NOtearDown. If you really want to use this for unit tests, rename to tearDown. | def NOtearDown(self):
for f in self.testoutput:
if os.path.exists(f):
os.remove(f) | [
"def tearDown(self):\n print('Tear down for [' + self.shortDescription() + ']\\n')",
"def teardown(self):\n pass",
"def teardown(self) -> None:\n pass",
"def tearDown(self):\n del self.test_dht22",
"def test_teardown(self):\n assert self.prometheus_handler.teardown() is No... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate bootstrap replicate of 1D data. | def bootstrap_replicate_1d(data, func):
bs_sample = np.random.choice(data, len(data))
return func(bs_sample) | [
"def bootstrap_replicate_1d(data, func):\n\treturn func(np.random.choice(data, size=len(data)))",
"def bootstrap_replicate_1d(data, func):\n bs_sample = np.random.choice(data, len(data))\n return func(bs_sample)",
"def bootstrap_replicate_1d(data, func):\n bs_sample = np.random.choice(data, len... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Si la simulación ha terminado, consigue la posición en x del mouse, y a partir de ella, consigue la posición en y, para mostrar ambas en las salidas de posicion_x y posicion_y | def show_position(self):
if(self.canvas["0"].particulas[0].estado == Estado.TERMINADO):
p_x = pygame.mouse.get_pos()[0]
if(p_x in self.canvas["0"].particulas[0].trayectoria.puntos):
self.posicion_x.set_text("x: " + str(p_x) + "m")
self.posicion_y.set_text("y: " + str(self.canvas["0"].particulas[0].traye... | [
"def trouve_position(self, x, y):\r\n\r\n xpos = 0\r\n ypos = 0\r\n\r\n # xpos est la position en x dans la grille\r\n if (x > 200) and (x < (self.width - 400) / 4 + 200):\r\n xpos = 1\r\n if (x > (self.width - 400) / 3 + 200) and (x < (self.width - 400) * 2 / 3 + 200):... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Actualiza los canvas, los pinta en esta ventana, y lleva a cabo el flip para mostrar los cambios | def display(self):
for c in self.canvas.values():
c.update()
self.superficie.blit(c.superficie, c.origen)
pygame.display.flip() | [
"def actualizar_canvas(self):\n self.lista_files = self.get_lista_files(self.directorio_actual)\n self.dibujar()",
"def draw(self):\n self._back_image = self.draw_image(\"images/tutor\")",
"def renderizar(self):\n\t\t# Limpiar la pantalla\n\t\tglClear(GL_COLOR_BUFFER_BIT)\n\t\t# Renderizar ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Setup injections Note that the actual injected current is proportional to dt of the clock So, you need to use the same dt for stimulation as for the model Strangely, the pulse gen in compartment_net refers to firstdelay, etc. | def setupinj(model, delay,width,neuron_pop):
pg = moose.PulseGen('pulse')
pg.firstDelay = delay
pg.firstWidth = width
pg.secondDelay = 1e9
for ntype in neuron_pop.keys():
for num, name in enumerate(neuron_pop[ntype]):
injectcomp=moose.element(name +'/'+model.param_cond.NAME_SOMA)... | [
"def setup():\n\n dut.prep(\"cfg_data\", [0])\n dut.prep(\"cfg_addr\", [0])\n dut.prep(\"cfg_valid\", [0])\n dut.prep(\"str_img_bus\", [0])\n dut.prep(\"str_img_val\", [0])\n dut.prep(\"image_rdy\", [0])\n\n # reset module\n dut.prep(\"rst\", [1])\n dut.tick()\n\n dut.prep(\"rst\", [0]... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Wrap a collection to print iteration progress as a percentage. | def progress_iterator(collection: Collection, message: str) -> Iterable:
num_items = len(collection)
last_percentage = -1
for i, item in enumerate(collection):
percentage = 100 * i // num_items
if percentage > last_percentage:
last_percentage = percentage
print(f"{mes... | [
"def calc_percentage(self, total_entries):\n self.percentage = self.count/total_entries * 100",
"def consume(iterator: typing.Iterable[T], progress: bool) -> None:\n i = 0\n to_feed = str(i)\n try:\n for _ in iterator:\n if progress:\n if len(to_feed) > 0:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Linearly mix two colors. A mix_amount of 0.0 gives color1, and 1.0 gives color2. | def mix_colors(color1: Color, color2: Color, mix_amount: float) -> Color:
return [(1-mix_amount)*v1 + mix_amount*v2 for v1, v2 in zip(color1, color2)] | [
"def _mix_color(c1, c2, mix):\n return round(c2 * mix + c1 * (1 - mix))",
"def mix_colors(color1: str, color2: str, color1_amount: float) -> str:\n color2_amount = 1 - color1_amount\n\n widget = porcupine.get_main_window()\n r, g, b = (\n round(color1_amount * value1 + color2_amount * value2)\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Multiply two vectors elementwise. | def multiply_vectors(vec1: Iterable[float], vec2: Iterable[float]) -> Iterable[float]:
return [v1*v2 for v1, v2 in zip(vec1, vec2)] | [
"def multVectors(vector1, vector2):\n new_vector = []\n for i in range(len(vector1)):\n new_vector.append(vector1[i] * vector2[i])\n return new_vector",
"def elementwise_mul(self, other):\n if len(self) != len(other):\n raise Exception(\"Invalid vector addition - vectors not of s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a directional light given its direction and color. The dot_clip parameter adjusts the value of the dot product used in the lighting calculation; a lower value compresses the range of brightnesses produced by the light. | def __init__(self, direction: Point3D, color: Color, dot_clip: float = 0.0):
self._direction = normalize(*direction)
self._color = color
self._dot_clip = dot_clip | [
"def vapor_trail(\n self, color: Colors, trail=10, trail_color: Colors = Colors.NONE, wait_ms=50):\n # Note that the first pass of this lights up the first 10 pixels.\n # Although that this appallingly sloppy, it also won't be noticeable\n # after the first time the path loops back t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the maximum color value that this light can produce. | def get_max_brightness(self) -> float:
return max(self._color) | [
"def maximal_color(graph, node):\n return max(get_node_colors(graph, node))",
"def getLastColorNum(self):\n return self.last_color_num",
"def last_color(self):\n idx = self._color_indexes.get(self._plotid)\n if idx is not None:\n return COLOR_CYCLE[(idx-1) % len(COLOR_CYCLE)]\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the color contributed by this light on a surface given its (unit) normal vector and material color. | def compute_shaded_color(self, normal: Point3D, material_color: Color) -> Color:
dot_product = sum(multiply_vectors(self._direction, normal))
light_amount = max(dot_product, self._dot_clip)
light_amount = (light_amount - self._dot_clip) / (1.0 - self._dot_clip)
return [vm*vl*light_amount... | [
"def _getColorFromLight(self, scene, vec, light, viewPoint):\n # Calculate some variables to work with\n normObject = self.normal(vec)\n normLight = (light.center - vec).normalize()\n isShadow = scene.isShadow(vec, light, self)\n # Calculate the color from Lamberts Diffuse Algo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Project a point in 3D world space into 2D screen space. | def project_point(self, point: Point3D) -> Point3D:
x, y, z = point
cam_x, cam_y, cam_z = self._pos
x -= cam_x
y -= cam_y
z -= cam_z
dx = self._cy*(self._sz*y + self._cz*x) - self._sy*z
dy = self._sx*(self._sy*(self._sz*y + self._cz*x) + self._cy*z) + self._cx*(se... | [
"def _world_point(self, point_3d):\n return self.obj.matrix_world @ point_3d",
"def unProject(self,x,y,z):\r\n inverse = np.linalg.inv(self.mvp)\r\n\r\n win4 = np.array((x,y,z,1.), dtype= np.float32)\r\n\r\n win4[0]=(win4[0] - self.viewport[0]) / float(self.viewport[2])\r\n win4... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fade a color depending on how far from the camera it is. | def compute_fog_faded_color(self, color: Color, dz: float) -> Color:
fade_amount = math.exp(-(dz * self._fog_factor)**2)
return mix_colors(UPPER_SKY_COLOR, color, fade_amount) | [
"def colorfade(color, fade):\n r = int(((color&0xff0000)>>16) * fade)\n g = int(((color&0x00ff00)>> 8) * fade)\n b = int( (color&0x0000ff) * fade)\n return (r<<16|g<<8|b)",
"def color_fade(bt, col1, col2, duration=100):\n set_static_color(bt, col1)\n delta = [col2.red - col1.red, col2.gree... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Shade, project, and draw a list of triangles in 3D. | def draw_triangles(self, triangles: Collection):
# project the points into 2D and compute each shaded/faded color
processed_triangles = []
for p1, p2, p3, color in progress_iterator(triangles, "Processing triangles..."):
shaded_color = self.compute_shaded_color(p1, p2, p3, color)
... | [
"def render_wireframe_3d(self, **kwds):\n wireframe = [];\n for l in self.lines:\n l_coords = self.coordinates_of(l)\n wireframe.append( line3d(l_coords, **kwds))\n for a in self.arrows:\n a_coords = self.coordinates_of(a)\n wireframe.append(arrow3d(a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the key in the _heightmap dict for the given triangle. | def _get_heightmap_key(self, p1: Point3D, p2: Point3D, p3: Point3D) -> Hashable:
return p1[0]+p2[0]+p3[0], p1[2]+p2[2]+p3[2] | [
"def getHeightMap(self, x: int, z: int) -> int:\n\t\treturn self.heightMap[(z << 4) | x]",
"def get_tile_key_from(self, x, y, z):\n h = self.height\n w = self.width\n return (z * h * w) + (y * w) + x",
"def height_at(self, x, z):\n\n return self.heightmap[x * 16 + z]",
"def get_blo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fill the background sky gradient. Uses num_steps rectangles to approximate a linear gradient that goes from the top of the screen to start_y of the way down the screen (between 0.0 and 1.0). | def fill_sky_gradient(num_steps: int, start_y: float):
# compute some helper values
min_x = -turtle.window_width() / 2
max_x = +turtle.window_width() / 2
y_step = turtle.window_height()*start_y / num_steps
min_y = turtle.window_height() / 2 - turtle.window_height()*start_y
# fill the sectio... | [
"def DrawBackground(self, dc, wnd, _rect, horizontal=True):\r\n\r\n rect = wx.Rect(*_rect)\r\n\r\n start_colour = StepColour(self._base_colour, 180)\r\n end_colour = StepColour(self._base_colour, 85)\r\n reflex_colour = StepColour(self._base_colour, 95)\r\n \r\n dc.Gradient... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Partition all the ELM events into training, validation and test indices. Training and validation sets are created based on simple splitting with validation set being `fraction_validate` of the training set or by Kfold crossvalidation. | def _partition_elms(
self, max_elms: int = None, fold: int = None
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
# get ELM indices from datafile
elm_index, _ = self._read_file()
# limit the data according to the max number of events passed
if max_elms is not None and max_el... | [
"def train_validation_split(self, threshold=None):\n for train, validation in self._get_k_folds(5, threshold):\n train_provider = train\n validation_provider = validation\n break\n return train_provider, validation_provider",
"def split_validation_training_index(alli... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
PyTorch dataset class to get the ELM data and corresponding labels according to the sample_indices. The signals are grouped by `signal_window_size` | def __init__(
self,
signals: np.ndarray,
labels: np.ndarray,
sample_indices: np.ndarray,
window_start: np.ndarray,
signal_window_size: int,
label_look_ahead: int,
stack_elm_events: bool = False,
transform=None,
):
self.signals = signals... | [
"def load_data_from_inds(data_set, inds):\n\n data = torch.cat([data_set[ind_][0].unsqueeze_(0) for ind_ in inds], 0)\n labels = torch.cat([torch.from_numpy(np.array(data_set[ind_][1])).unsqueeze_(0) for ind_ in inds], 0)\n\n return data, labels",
"def get_data_and_model_samples(self):\n model... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a Stormpath resource, we'll extract the custom data in a JSON compatible format. | def get_custom_data(self, resource):
try:
custom_data = dict(resource.custom_data)
except AttributeError:
custom_data = dict(resource['custom_data'])
custom_data['createdAt'] = custom_data['created_at'].isoformat()
custom_data['modifiedAt'] = custom_data['modifie... | [
"def _get_json(self, k8sresource):\n resource_json = self._get_raw_json(k8sresource)\n\n return resource_json",
"def metaresources():\n return jsonify(bioregistry.read_metaregistry())",
"def get_json(context_name):",
"def _get_raw_json(self, k8s_resource):\n kubectl = self._kubectl\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a Stormpath Resource, we'll extract the resource ID. | def get_id(self, resource):
try:
return resource.href.split('/')[-1]
except AttributeError:
return resource['href'].split('/')[-1] | [
"def resourceDocumentId(self, resource: Resource) -> str:",
"def resource_id(self) -> str:\n return pulumi.get(self, \"resource_id\")",
"def get_object_id(resource):\n if hasattr(resource, \"object_id\"):\n return int(resource.object_id)\n\n return int(resource.id)",
"def resourceid(self):... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Export all tenant data for this Stormpath account. | def export_tenants(self):
print('\n=== Exporting all tenant data...')
tenant = dict(self.client.tenant)
print('- Exporting tenant:', tenant['name'])
json = {
'id': self.get_id(tenant),
'href': tenant['href'],
'name': tenant['name'],
'key... | [
"def export_accounts(self):\n print('=== Exporting all account data...')\n\n for account in self.client.tenant.accounts:\n print('- Exporting account:', account.email)\n\n json = {\n 'id': self.get_id(account),\n 'href': account.href,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Export all application data for this Stormpath account. | def export_applications(self):
print('\n=== Exporting all application data...')
for application in self.client.applications:
print('- Exporting application:', application.name)
json = {
'id': self.get_id(application),
'href': application.href,
... | [
"def export_data(self):\n return self.export_all_data()",
"def export_accounts(self):\n print('=== Exporting all account data...')\n\n for account in self.client.tenant.accounts:\n print('- Exporting account:', account.email)\n\n json = {\n 'id': self.get_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Export all directory data for this Stormpath account. | def export_directories(self):
print('=== Exporting all directory data...')
for directory in self.client.directories:
print('- Exporting directory:', directory.name)
json = {
'id': self.get_id(directory),
'href': directory.href,
'n... | [
"def export_accounts(self):\n print('=== Exporting all account data...')\n\n for account in self.client.tenant.accounts:\n print('- Exporting account:', account.email)\n\n json = {\n 'id': self.get_id(account),\n 'href': account.href,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Export all organization data for this Stormpath account. | def export_organizations(self):
print('\n=== Exporting all organization data...')
for organization in self.client.organizations:
print('- Exporting organizations:', organization.name)
json = {
'id': self.get_id(organization),
'href': organization... | [
"def export_accounts(self):\n print('=== Exporting all account data...')\n\n for account in self.client.tenant.accounts:\n print('- Exporting account:', account.email)\n\n json = {\n 'id': self.get_id(account),\n 'href': account.href,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Export all group data for this Stormpath account. | def export_groups(self):
print('=== Exporting all group data...')
for group in self.client.tenant.groups:
print('- Exporting group:', group.name)
json = {
'id': self.get_id(group),
'href': group.href,
'name': group.name,
... | [
"def export_accounts(self):\n print('=== Exporting all account data...')\n\n for account in self.client.tenant.accounts:\n print('- Exporting account:', account.email)\n\n json = {\n 'id': self.get_id(account),\n 'href': account.href,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Export all account data for this Stormpath account. | def export_accounts(self):
print('=== Exporting all account data...')
for account in self.client.tenant.accounts:
print('- Exporting account:', account.email)
json = {
'id': self.get_id(account),
'href': account.href,
'username': ... | [
"def dump(self):\n username = Account.sanitize_fname(self.username)\n filepath = f'{ACCOUNTS_DIRPATH}{sep}{username}.account'\n with open(filepath, 'bw') as file:\n file.write(self.dumps())",
"def export_data(self):\n return self.export_all_data()",
"def fetch_accounts(sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Log error, then raise if is is set. | def log_error(self, error: Exception) -> None:
logging.error(error) | [
"def log_error(self, err):\n print(err)\n logging.error(err)",
"def _log_and_raise(msg):\n LOG.error(msg)\n raise Exception(msg)",
"def raise_exception():\n self.log.error(\"%s: %s\", data['code'], info_message[data['code']])\n raise ValueError(\"%s: %s\" % (data['code'... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get replacement file when original missing. | def get_replacement_file(self, path) -> Optional[bytes]:
return None | [
"def get_pristine(self):\n for path in self.get_all_files():\n if path.endswith('.orig.tar.gz'):\n return path\n return None",
"def get_original_path(self) -> Optional[str]:\n return self.original_path",
"def _get_preexisting(self, dest_format, destination_path):\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get next CID for related content. | def get_next_cid(self) -> str:
self.position += 1
return "img{}".format(self.position) | [
"def find_next_citation_gramps_id(self):\n self.cmap_index, gid = self.__find_next_gramps_id(self.citation_prefix,\n self.cmap_index, self.cid_trans)\n return gid",
"def next(self):\n try:\n return self.__next\n except AttributeError:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Collect images from html code. Return html with iamge src=cid and list of tuple with (maintype, subtype, cid, imagebytes). | def collect_images(self, html_body: str, encoding: str = "UTF-8") -> Tuple[str, List[Tuple[str, str, str, bytes]]]:
images = []
reader = etree.HTMLParser(recover=True, encoding=encoding)
root = etree.fromstring(html_body, reader)
self.init_cid()
same_content = {} # type: Dict[by... | [
"def extract_images(content):\n\n return re.findall('src=\"([^\"]+)\"', content)",
"def extract_images(self, tree, url):\n if self.debug:\n print \"\"\n print \"Extracting images from\", url\n for src in tree.xpath('/html/body//img/@src'):\n src_link = urljoin(url... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Collect attachment contents from paths or urls. | def collect_attachments(self, paths_or_urls: Iterable[str]) -> List[Tuple[str, str, str, bytes]]:
attachments = []
same_content = [] # type: List[bytes]
for src in paths_or_urls:
try:
content = self.load_file(src)
except ImageNotFound as err:
... | [
"def parse_attachments(request):\n attachments = []\n for attachment in request.files.getlist('attachment'):\n attachments.append(Attachment(attachment.filename, attachment))\n return attachments",
"def attachments(self):\n return []",
"def fetch_and_dl_attachments() -> None:\n try:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get C statistics numpy record list, or return None if the file does not exist. | def load_csv_cached(filename='../apps/naive_c_stats.csv', cache={}):
if filename in cache:
return cache[filename]
if not os.path.exists(filename):
ans = None
else:
ans = numpy.recfromcsv(filename)
cache[filename] = ans
return ans | [
"def getdata(filename):\r\n everything = [\r\n line.strip().split(',')\r\n for line in file(filename)]\r\n header = everything[0]\r\n stats = everything[1:]\r\n return (header,data)",
"def get_stats(ptrn, collect_stats=True):\n files = glob.glob(ptrn)\n file_stats = []\n total_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the lines of main program logic, excluding various less important information such as imports/comments/tests, and globals (typically used for tests). | def lines(filename, exclude_imports=True, exclude_comments=True, exclude_tests=True, exclude_globals=True, exclude_blank=True, verbose=False, is_c=False, s=None):
if s is None:
s = open(filename, 'rt').read()
L = s.split('\n')
# Hack to strip out triple and single quote string lines in a heuri... | [
"def excluded_lines(self):\n non_source_lines = set()\n \n show_parsing = SHOW_PARSING if not self._excluded_lines_shown else False\n \n if not self._tokens:\n lexer = Lexer(self.source(), self.filename, self.rs) # v1.1: Add 'rs'\n self._tokens = lexer.tokenize()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
stimate distance given estimated sensor locations. | def compute_distance_with_sensor_and_obj_loc(sensor_loc, obj_loc):
estimated_distance = scipy.spatial.distance.cdist(obj_loc,
sensor_loc,
metric='euclidean')
return estimated_distance | [
"def calculate_distance_to_stations(self, stations: list):\n for station in stations:\n import pdb; pdb.set_trace()",
"def test_sense_distance(self):\n\n\t\tmeasurements = [29, 29, 28]\n\t\tself.driver.us_dist.side_effect = lambda x: measurements.pop()\n\t\texpected_measurement = int(ultrasonic_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find and read the observing log file. | def load_obslog(pattern, fmt='obslog', verbose=True):
# find observing log in the current workin gdirectory
logname_lst = [fname for fname in os.listdir(os.curdir)
if re.match(pattern, fname)]
if len(logname_lst)==0:
print('No observation log found')
return None... | [
"def read_log():\n if config['Switches']['location'] == 'local':\n path = f\"{config['Local']['location']}Coffe_Log.json\"\n if os.path.exists(path) == False:\n print(\"no file\")\n else:\n with open(path,'r') as feedsjson:\n feeds... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Save frames to a single row or as a gif. | def save_frames(frames, out_dir, as_row=True, as_gif=False):
os.makedirs(out_dir, exist_ok=True)
if frames.dtype == torch.uint8: # save_image needs float value in [0, 1]
frames = frames.float()
frames = frames / 255.
if as_gif:
gif_dir = 'gif_images'
os.makedirs(os.path.join(out_dir, gif_dir), ex... | [
"def save_gif(frames):\n print(\"Saving gif images!\")\n for i in range(len(frames)):\n im_out_path = \"gif/gif_emilie_will_\" + str(i) + \".png\"\n plt.imsave(im_out_path, frames[i])",
"def saveFrames(filepath, frames):\n\n for i, frame in enumerate(frames):\n image = Image.fromarra... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Le constructeur permet de remplir les champs séparément ou de parser une source. Il crée ensuite une somme md5 du message pour fournir un identifiant unique. | def __init__(self, date=0, texte="", expediteur=None, destinataire=None, parse=None, not_sent=None):
if parse is not None:
valide = self.parse(parse, not_sent)
else:
valide = True
self.expediteur = expediteur
self.destinataire = destinataire
se... | [
"def __init__(self, *args, **kwargs):\n StanzaBase.__init__(self, *args, **kwargs)\n if self['id'] == '':\n if self.stream is not None:\n self['id'] = self.stream.new_id()\n else:\n self['id'] = '0'",
"def __init__(self, from_number=\"\", text_of_s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Récupère une ligne de texte, rempli les champs correspondants et renvoie False Si la correspondance ne peut être rétablie, renvoie False not_sent permet de spécifier si le nom est bien celui de l'expéditeur | def parse(self, texte, not_sent):
resultat = self.regexp.search(texte)
if resultat is not None:
infos = resultat.groupdict()
if not_sent:
self.expediteur, self.destinataire = infos["nom"], ""
else:
self.expediteur, self.destinataire = "... | [
"def non_plein(self):\n # pass\n # mon travail\n # si on trouve un espace dans le plateau , il n'est pas plein ==> true\n b = False\n for i in range(0, 3):\n for j in range(0, 3):\n if self.cases[(i, j)].contenu == \" \":\n b = True\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
mcxPyBot constructor initialises mcxDatabase connection and adds command handlers. | def __init__(self, channel, nickname, password, server, port = 6667, dbcon = False):
# IRC connection
SingleServerIRCBot.__init__(self, [(server, port)], nickname, nickname)
# register event handler for all events
self.ircobj.add_global_handler('all_events', getattr(self, 'on_event'), -... | [
"def __init__(self):\n\n self.database = Database()\n\n self.valid_commands = [\"c\", \"l\", \"r\"]",
"def __init__(self):\n\t\tself.obtainDatabaseConnection()",
"def __init__(self):\n self.conn = SQLTools().connect(credentials)\n self.db = returnDB()",
"def __init__(self) -> None:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
initialize some quit message and save them into a list by filling self.__quitmsgs | def __initQuitMsgPool(self):
self.__quitmsgs.append("Infektion festgestellt... leite Quarantaenemassnahmen ein... trenne aktive Verbindung") | [
"def getRandomQuitMsg(self):\n return self.__quitmsgs[randint(0, len(self.__quitmsgs)-1)]",
"def init_outbox(self):\n for fact in self.knowledge:\n self.inbox.append( (fact, None) )\n #self.process_fact(fact, None) ## There is no sender",
"def reset_msg(self):\n if not... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get any random quit message that was initialized by __initQuitMsgPool() | def getRandomQuitMsg(self):
return self.__quitmsgs[randint(0, len(self.__quitmsgs)-1)] | [
"def __initQuitMsgPool(self):\n self.__quitmsgs.append(\"Infektion festgestellt... leite Quarantaenemassnahmen ein... trenne aktive Verbindung\")",
"def get_msg_quit(self, username):\n return \"Bye bye\"",
"def get_message():\n msg = random.choice(messages)\n logger.info(\"{}\".format(str(ms... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
commands executed after connected to the server triggered if the chosen nickname on construction is already in use | def on_nicknameinuse(self, c, e):
c.nick(c.get_nickname() + "_") | [
"def on_nicknameinuse(self, raw_msg, busy_nickname, **kwargs):",
"def on_nicknameinuse(self, connection, event):\n nick1 = connection.get_nickname()\n nick2 = nick1 + '_'\n self.warning('nickname already in use (%s): renaming to %s...', nick1, nick2)\n self.connection.nick(nick2)",
"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
commands executed when the bot received a private message forwards the command and the event to self.do_command() | def on_privmsg(self, c, e):
self.do_command(e.arguments()[0], c, e) | [
"async def process_commands(self, message: Message) -> None:\n if message.author != self.user:\n ctx = await self.get_context(message)\n await self.invoke(ctx)",
"def do_private(self):\n # get first next word to be a command\n tokens = self.input.split(\" \", 1)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
commands executed when the bot received a dcc message currently does nothing | def on_dccmsg(self, c, e):
args = e.arguments()[0].split(" ", 1)
if len(args) > 0:
self.do_command(args[0], c, e) | [
"def mqtt_commands(self):",
"async def cc_delete(self, ctx, command : str):\n guild = ctx.guild\n guild_id = str(guild.id)\n\n command = command.lower()\n if guild_id in self.c_commands:\n cmdlist = self.c_commands[guild_id]\n if command in cmdlist:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns the userid of the connected user on a DCCConnection | def __getUserIdByDCCConnection(self, c):
try:
UserId = self.__IpToUser[self.getIpStringByDCCConnection(c)]['userid']
if UserId > 0:
return UserId
else:
return NOT_AUTHED
except KeyError:
return NOT_AUTHED | [
"def get_user_id(self):\n return self.socket.user_id",
"def getUserID(self):\n\t\treturn self.UserID",
"def get_user_id():\n csc_name = get_user_csc_name()\n if csc_name:\n return csc_name\n haka_id = get_user_haka_identifier()\n if haka_id:\n return haka_id\n return None",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
checks whether a given command is registered on the given type | def __commandExists(self, command, cmdtype):
try:
# method exists
if hasattr(self, self.__getFullCommandName(command, cmdtype)):
# command handler type exists
if self.__commandHandlerTypeExists(cmdtype):
return True
else... | [
"def __commandHandlerTypeExists(self, type):\n return self.__commandHandlers.has_key(type)",
"def is_of_type(cmd):\r\n raise NotImplementedError()",
"def _is_command(self, ext):\n try:\n return issubclass(ext, CommandExtension)\n except TypeError:\n return False... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
resolves the command type by an event and a command | def __resolveCommandType(self, command, e):
# check for existing DCC Connection
try:
if self.__IpToUser[e.source()]['auth'] == NOT_AUTHED:
return 'not_authed_dcc'
else:
return 'authed_dcc'
# DCC Connection does not exist
except KeyE... | [
"def handle_command(self, command):\n\n cmd = json.loads(command)\n cmd_type = cmd.get('type')\n\n handler = self._command_handlers.get(cmd_type)\n if not handler:\n raise ValueError(f'Unknown command {cmd_type}')\n event = handler(cmd)\n return eventd",
"def o... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
resolve the function to call by an event and a command | def __resolveCommandFunction(self, command, e):
return self.__getFullCommandName(command, self.__resolveCommandType(command, e)) | [
"def resolve_command(\n\t\t\tself,\n\t\t\tctx: click.Context,\n\t\t\targs: List[str],\n\t\t\t) -> Tuple[str, click.Command, List[str]]: # noqa: D102\n\n\t\tcmd_name = make_str(args[0])\n\t\toriginal_cmd_name = cmd_name\n\n\t\t# Get the command\n\t\tcmd = self.get_command(ctx, cmd_name)\n\n\t\t# If we can't find th... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns the method name of this object for the given command and command type | def __getFullCommandName(self, command, type):
return 'cmd_%s_%s' % (type, command) | [
"def get_command_name(self) -> str:\n pass",
"def name(self):\n return self._command",
"def commandType(self):\n return cmd_types[self.get_type()]",
"def name(self):\n module_filepath = inspect.getfile(type(self))\n module_filename = os.path.basename(module_filepath)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
adds a new command handler to the system | def __addCommandHandler(self, command, type = 'channel', requiresdb = False):
try:
# ensure we are dealing with booleans
if not requiresdb:
requiresdb = False
else:
requiresdb = True
# add the handler
# check for existi... | [
"def add_commands(self):\n self.dp.add_handler(CommandHandler(\"start\", self.start))\n self.dp.add_handler(CommandHandler(\"help\", self.help))\n self.dp.add_handler(CommandHandler(\"imprint\", self.imprint))\n self.dp.add_handler(InlineQueryHandler(self.inlinequery))",
"def add_handl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function that registered all handled command types | def __setupCommandHandlerTypes(self):
# dict saving all command handler types
self.__commandHandlers = {'channel': {}, 'query': {}, 'not_authed_dcc': {}, 'authed_dcc': {}} | [
"def register_commands(self):\n # Register the public commands\n say_command_manager.register_commands(\n (self.name, '!' + self.name),\n _send_command_menu,\n )\n\n # Register the private command\n say_command_manager.register_commands(\n '/' + se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
checks whether the given command type exists | def __commandHandlerTypeExists(self, type):
return self.__commandHandlers.has_key(type) | [
"def __commandExists(self, command, cmdtype):\n try:\n # method exists\n if hasattr(self, self.__getFullCommandName(command, cmdtype)):\n # command handler type exists\n if self.__commandHandlerTypeExists(cmdtype):\n return True\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Solves the power flow using a fast decoupled method. Solves for bus voltages given the full system admittance matrix (for all buses), the complex bus power injection vector (for all buses), the initial vector of complex bus voltages, the FDPF matrices B prime and B double prime, and column vectors with the lists of bus... | def decoupledpf(Ybus, Sbus, V0, pv, pq, ppci, options):
# old algortihm options to the new ones
pp2pypower_algo = {'fdbx': 2, 'fdxb': 3}
# options
tol = options["tolerance_mva"]
max_it = options["max_iteration"]
# No use currently for numba. TODO: Check if can be applied in Bp and Bpp
# num... | [
"def mbuspowerflow(Ybus, Vknown, Pknown, Qknown, X0='flatstart', eps=1e-4,\n mxiter=100, returnct=False, degrees=True, split=False,\n slackbus=0, lsq_eps=0.25):\n # Identify Lack of Support\n if not __NUMDIFFTOOL_SUPPORT__:\n raise ImportError(\n \"(!) Cann... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Rebuild the parameter vector. Note that this can potentially alter the parameter order if the strings are given in a different order. It mutates the parameter vector to contain the elements as specified in "parameters" with the defaults as specified in defaults. If the parameter already exists in the vector nothing hap... | def _set_params(self, params, defaults):
new_params = OrderedDict(
zip(params, [x if isinstance(x, Parameter) else Parameter() for x in defaults])
)
for key, value in self._src.items():
if key in new_params:
new_params[key] = value
self._src = new... | [
"def rebuild_param(self,vec,**kwargs):\n from collections import OrderedDict\n tmp = OrderedDict([('lengthscale',None),( 'variance',None),( 'gstds',None)])\n for key,val in kwargs.items():\n assert val!=None, \"Can't have None as fixed values\"\n tmp[key]=val\n for ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Chains a Future instance directly to another Future instance Used for recursive Promise Resolution Procedure (section 2.3.2) specified in Promise/A+ that allows .then() to piggy back on a Promise returned by success handler | def _chain_to_another_future(self, base_future):
if base_future in self._chained_futures_log:
raise CircularFuturesChainException(
'Circular Futures chain detected. Future {} is already in the resolved chain {}'.format(
base_future, set(self._chained_futures_log)... | [
"def chain_future(a, b):\r\n def copy(future):\r\n assert future is a\r\n if b.done():\r\n return\r\n if (isinstance(a, TracebackFuture) and isinstance(b, TracebackFuture)\r\n and a.exc_info() is not None):\r\n b.set_exc_info(a.exc_info())\r\n elif... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates the himesis graph representing the Simulink model HFlatten2. | def __init__(self):
# Flag this instance as compiled now
self.is_compiled = True
super(HFlatten2, self).__init__(name='HFlatten2', num_nodes=117, edges=[])
# Add the edges
self.add_edges([(5, 66), (66, 50), (5, 67), (67, 51), (5, 35), (35, 20), (5, 36), (36, 21)... | [
"def nx2homg(nxg):\n n = nxg.number_of_nodes()\n G = hlGraph(n)\n for (u, v) in nxg.edges():\n G.addEdge(u,v)\n return G",
"def build_graph(self):\n return nn.Sequential(\n nn.Linear(self.input_dim, self.hidden_dim),\n self.hidden_activation,\n nn.Linear(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Runs parameter checks This includes a determination that the value is equal to or greater than zero, and a check that all required keywords for a given | def _check_parameters(self, target_function, **kwargs):
# Ensure all arguments are =< 0 where relevant
for keyword, value in kwargs.items():
# Two conditions
value_is_less_than_zero = value < 0
keyword_is_relevant = keyword in ['mean', 'constant', 'low', 'mode', 'high... | [
"def check_params(self):\r\n \r\n # TODO: More cases?\r\n\r\n if self.N <= 0:\r\n print('Bad Parameter: N')\r\n \r\n if self.Ha_tally <= 0 or self.Ha_tally > self.N:\r\n print('Bad Parameter: Reported winner tally')\r\n \r\n if len(self.round_sc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Supply raw data to the model This takes an arbitrary array, runs some quick checks, and returns the array if appropriate. | def supply_raw(self, target, array):
# Ensure numeric
clean_array = pd.to_numeric(array)
# Coerce to series
if type(array) == pd.Series:
s = pd.Series(clean_array.values)
else:
s = pd.Series(clean_array)
# Check numeric and not null
if s.is... | [
"def _prepare_data(data):\n if isinstance(data, list):\n data = np.array(data)\n\n if len(data.shape) > 2:\n raise ValueError(\"Unexpected format.\")\n if len(data.shape) == 2:\n if data.shape[1] != 1:\n raise ValueError(\"Unexpected format.\")\n\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks keywords and returns the appropriate function object. | def _determine_func(self, **kwargs):
# Check whether keys are recognized
for key in kwargs.keys():
if key not in self._parameter_map.keys():
raise FairException('"{}"" is not a recognized keyword'.format(key))
# Check whether all keys go to same function via set compr... | [
"def find_function(keyword: str) -> Callable[[str], str]:\n if keyword in FUNCTIONS.keys():\n return FUNCTIONS[keyword]\n elif keyword in USER_FUNCTIONS.keys():\n return USER_FUNCTIONS[keyword]\n elif keyword == 'RECALL':\n return FUNCTIONS[keyword]\n else:\n return lambda x:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates constant array of size `count` | def _gen_constant(self, count, **kwargs):
return np.full(count, kwargs['constant']) | [
"def create_array( n ):",
"def createBasis(dim: int, count: int) -> List[ndarray]:\n vecList = []\n for num in range(count):\n vec = basis(dim, num)\n vecList.append(vec)\n return vecList",
"def make_array(self, bucket_count):\n A = (bucket_count * ctypes.py_object)()\n for ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks parameters, creates BetaPert, returns random values | def _gen_pert(self, count, **kwargs):
self._check_pert(**kwargs)
pert = FairBetaPert(**kwargs)
rvs = pert.random_variates(count)
return rvs | [
"def beta_defs(alpha,mu):\n\tbeta = alpha/mu - alpha\n\tval = np.random.beta(alpha, beta)\n\treturn val",
"def MH_sampler(bayes_net, initial_state):\n A_cpd = bayes_net.get_cpds(\"A\") \n AvB_cpd = bayes_net.get_cpds(\"AvB\")\n match_table = AvB_cpd.values\n team_table = A_cpd.values\n sample ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Uses pandas to load an edgelist file and returns it as a list of tuples with pairs of connected nodes. | def load_edgl(fname):
# Reads edges
df = pd.read_csv(fname, sep=" ", header=None, usecols=[0, 1])
# Convert to list of tuples
return list(df.itertuples(index=False, name=None)) | [
"def parse_edgelist(file):",
"def read_graph(filename):\n return nx.read_edgelist(filename, delimiter='\\t')",
"def read_graph():\n return nx.read_edgelist('edges.txt.gz', delimiter='\\t')",
"def read_graph():\n return nx.read_edgelist('edges_new.txt', delimiter='\\t')",
"def pandasToNetworkX(edgeL... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns whether or not a user can modify settings in a LocalSite. This checks that the user is either staff with the proper permissions, or that they're listed in the 'admins' field. By default, this is checking whether the LocalSite itself can be modified, but a different permission can be passed to check for another ... | def is_mutable_by(self, user, perm='site.change_localsite'):
return user.has_perm(perm) or self.admins.filter(pk=user.pk).exists() | [
"def has_perm(\n self,\n user: Union[AbstractBaseUser, AnonymousUser],\n perm: str,\n obj: Any = None,\n ) -> bool:\n if obj is not None and not isinstance(obj, LocalSite):\n logger.error('Unexpected object %r passed to has_perm. '\n 'Returnin... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test user_id starts from one and increments by one | def test_user_id(self):
new_user = self.app
self.assertTrue(new_user.user_id, 0)
new_user.create_user()
self.assertTrue(new_user.user_id, 1)
for key in new_user.users:
self.assertEqual(new_user.user_id, key) | [
"def get_next_id(self):\n curr_id = User.objects.latest('id')\n return curr_id.id + 1",
"def next_identity(self) -> UserId:\n ...",
"def nextId(self) -> UserId:\n raise NotImplementedError(\"\")",
"def set_val_user_id():\n\n # Get the maximum user_id in the database\n result ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test registered user can login successfully | def test_successful_login(self):
pass | [
"def test_user_login_successfully(self):\n # We attempt to create the user\n result = self.app.login('luwyxx@gmail.com', 'psw12345!')\n # To check the condition, we assert that the method returns True\n self.assertTrue(result)",
"def test_user_login_success(self):\n\n self.user.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test Shoppinglist's dict is empty at first | def test_shoplists_dictionary(self):
new_shoplist = self.app
self.assertEqual(len(new_shoplist.shoplists), 0)
new_shoplist.create_shoplist()
self.assertIsInstance(new_shoplist, Shoppinglist)
self.assertEqual(len(new_shoplist.shoplists), 1) | [
"def test_common_data_empty_cart(self):\n common_data = views.GeneralContextMixin.common_data(self.request)\n self.assertIsInstance(common_data, dict)\n self.assertEqual(common_data[\"items_in_cart\"], 0)",
"def test_create_new_shopping_list(create_shopping_list):\n shopping_list = create_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test shoplist_id starts from one and increments by one | def test_shoplist_id(self):
new_shoplist = self.app
self.assertTrue(new_shoplist.shop_id, 0)
new_shoplist.create_shoplist()
self.assertTrue(new_shoplist.shop_id, 1)
for key in new_shoplist.shoplists:
self.assertEqual(new_shoplist.shop_id, key) | [
"def test_adding_item_to_list(create_shopping_item, create_shopping_list):\n shopping_list = create_shopping_list\n items_before = shopping_list.items.values_list().count()\n new_item = create_shopping_item\n shopping_list.items.add(new_item)\n items_after = shopping_list.items.values_list().count()\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test shoplist can be created | def test_create_shoplist(self):
new_shoplist = self.app
new_shoplist.create_shoplist()
self.assertEqual(len(new_shoplist.shoplists), 1) | [
"def test_successful_shoplist_creation(self):\n result = self.app.create_shoplist()\n expected = {5: {'user_id': 0, 'name': 'apples', 'description': 'Fresh Green Apples'}}\n self.assertEqual(expected, result)",
"def test_create_shopping_list(self):\n self.application.signup(self.user_1... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test Shoppinglist creation without a user fails | def test_create_shoplist_without_user_fails(self):
User.users = {}
result = self.app.create_shoplist()
expected = {1: {'user_id': 1, 'name': 'Apple', 'description': 'Fresh Green Apples'}}
self.assertNotEqual(expected, result) | [
"def test_create_list_fails_if_user_doesnt_exist(self):\n self.assertRaises(Exception, self.app.create_shopping_list,\n 'Back to school', 'school shopping list',\n 'fakeUser@gmail.com')",
"def test_create_shopping_list(self):\n self.application.signu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test Shoppinglist creation is successful | def test_successful_shoplist_creation(self):
result = self.app.create_shoplist()
expected = {5: {'user_id': 0, 'name': 'apples', 'description': 'Fresh Green Apples'}}
self.assertEqual(expected, result) | [
"def test_api_can_create_shoppinglist(self):\n response = self.client.post(\n reverse('shoppinglists'), self.shoppinglist_data, format=\"json\"\n )\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)",
"def test_create_shoplist(self):\n new_shoplist = self.app\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test activity's dict is empty at first | def test_activity_dictionary(self):
new_activity = self.app
self.assertEqual(len(new_activity.activities), 0)
new_activity.create_activity(1)
self.assertIsInstance(new_activity, Activity)
self.assertEqual(len(new_activity.activities), 1) | [
"def test_inputs_dict_empty(self):\n self.data['inputs'] = {}\n self.analyze()\n self.assert_failed(with_errors=True)",
"def test_no_advisor(self):\n nothing = factory.build(dict, FACTORY_CLASS=ActivityFactory,\n name='Nothing',\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test activity_id starts from one and increments by one | def test_activity_id(self):
new_activity = self.app
self.assertTrue(Activity.activity_id, 0)
new_activity.create_activity(1)
self.assertTrue(new_activity.activity_id, 1)
for key in new_activity.activities:
self.assertEqual(new_activity.activity_id, key) | [
"def test_increment_activity_should_increment_activity(self):\n self.activity.increment_activity(self.kernel_id, CONNECTIONS)\n self.activity.increment_activity(self.kernel_id, CONNECTIONS)\n self.activity.increment_activity(self.kernel_id, CONNECTIONS)\n self.assertEqual(self.activity.g... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate a segmented array of variablelength, contiguous ranges between pairs of start and endpoints. | def gen_ranges(starts, ends):
if starts.size != ends.size:
raise ValueError("starts and ends must be same size")
if not ((ends - starts) > 0).all():
raise ValueError("all ends must be greater than starts")
lengths = ends - starts
segs = ak.cumsum(lengths) - lengths
totlen = lengths.s... | [
"def sa_range(start: int, end: int) -> StaticArray:\n forward = True # Declares variable for direction\n # Sets the number of elements to create\n if end > start:\n length = abs((end - start) + 1)\n else:\n length = abs((start - end) + 1)\n forward = False\n arr = StaticArray(le... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
由于灰度是从0到255的,图片是一个二维数组,如果我打印每一个图片,那种3位数两位数,就对不齐 我是想直观的感受这个数字的形状,就把正整数变成1,忽略灰度,这样能对齐了。 参数 the_array:一个二维数组。(数组中的值代表这个图像每个像素的灰度值) 返回值 没有返回值,这个函数就是把二维数打印出来,正数打印成"1",零打印成"0" 例子 每一个mnist图片都是2828的二维数组,传入这个函数即可看到结果。 | def visual_array(the_array):
if the_array.ndim != 2:
print("对不起,您传入的参数不是二维数组,请重新传参。")
return 0
for i in range(the_array.shape[0]):
for j in range(the_array.shape[1]):
if the_array[i][j] != 0:
print(1, end='')
else:
print(0, end='')
if... | [
"def binary_array(im):\n return np.clip(np.where(im == 153, 0, 1).sum(axis=2), 0, 1)",
"def pic_code(image: np.ndarray):\r\n width, height = image.shape\r\n avg = image.mean()\r\n one_hot = np.array([1 if image[i, j] > avg else 0 for i in range(width) for j in range(height)])\r\n re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Replace characters that are ok for the filesystem but have special meaning in the shell. It is assumed file_path is already passed in double quotes. | def sanitize_file_path_for_shell(file_path):
file_path_sanitized = file_path.replace('\\', '\\\\')
file_path_sanitized = file_path_sanitized.replace('$', '\\$')
file_path_sanitized = file_path_sanitized.replace('"', '\\"')
file_path_sanitized = file_path_sanitized.replace('`', '\\`')
return file_pat... | [
"def _escape_path(path):\n path = path.strip()\n return '\"{0}\"'.format(path) if _platform_windows else path.replace(\" \", \"\\ \")",
"def sanitize_file_path(file_path, replacement_text=\"\"):\n\n return __RE_INVALID_PATH.sub(replacement_text, file_path.strip())",
"def shell_escape_filename(filename)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns all parent regions of this region. | def all_parents(self) -> Iterable[Region]:
if self.parent is not None:
yield self.parent
yield from self.parent.all_parents() | [
"def getParents(self):\n return self.parents",
"def get_all_parent_skin_rigs(self) -> list['BaseSkinRig']:\n items = []\n current = self\n while current:\n items.append(current)\n current = current.get_parent_skin_rig()\n return items",
"def region(self):... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize the battery's attributes. | def __init__(self, battery_size=40):
self.battery_size = battery_size | [
"def __init__( self, battery_size = 60 ):\r\n self.battery_size = battery_size",
"def __init__(self, battery_size):\n self.battery_size = battery_size",
"def __init__(self, battery_size = 70):\r\n\t\tself.battery_size = battery_size",
"def __init__(self, battery_size=70):\r\n\t\tself.battery_siz... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to generate ground truth labels as specified by int_limit. | def generate_true_labels(int_limit, n_obs):
if int_limit > 0:
if int_limit > n_obs:
raise ValueError(f"""Invalid value of int_limit {int_limit}:
greater than the number of sequences""")
else:
true_labels = [1 if idx <=
i... | [
"def make_labels(\n entity_id,\n df,\n time_col,\n prediction_window,\n label_filter\n ):\n return 0",
"def create_classification_labels(labels: np.ndarray, max_label: int) -> np.ndarray:\n classification_labels = np.zeros_like(labels)\n for i, label in enumerate... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create the bucket where all datasets will be stored | def create_bucket() -> None:
try:
client.make_bucket(DATASETS_BUCKET)
except BucketAlreadyOwnedByYou:
logger.debug(f"Not creating bucket {DATASETS_BUCKET}: Bucket already exists")
pass
else:
logger.debug(f"Successfully created bucket {DATASETS_BUCKET}") | [
"def setup_buckets():\n s3 = boto.connect_s3()\n s3.create_bucket('mls_data.mls.angerilli.ca')",
"def create_and_fill_bucket(self):\n EmrProcessing.bucket = \\\n self.s3_handle.create_bucket(EmrProcessing.bucket_name)\n key = EmrProcessing.bucket.new_key('input/test.csv')\n i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fail if the two objects are unequal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero, or by comparing that the between the two objects is more than the given delta. Note that decimal places (from zero) are usually not the same as significant digits (measu... | def almost_equal(first, second, places=None, delta=0.1):
if first == second:
# shortcut
return True
if delta is not None and places is not None:
raise TypeError("specify delta or places not both")
if delta is not None:
if abs(first - second) <= del... | [
"def assertDictAlmostEqual(\n self, dict1, dict2, delta=None, msg=None, places=None, default_value=0\n ):\n if dict1 == dict2:\n # Shortcut\n return\n if delta is not None and places is not None:\n raise TypeError(\"specify delta or places not both\")\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Rude check if uuid is in correct uuid1 format. | def validate_uuid(self, uuid):
match = re.match(
r'([a-z0-9]+)-([a-z0-9]+)-([a-z0-9]+)-([a-z0-9]+)-([a-z0-9]+)',
uuid
)
if match:
return True
return False | [
"def _check_uuid(uuid_str, spec_version, interoperability):\n if interoperability:\n return ID_REGEX_interoperability.match(uuid_str)\n\n uuid_obj = uuid.UUID(uuid_str)\n\n ok = uuid_obj.variant == uuid.RFC_4122\n if ok and spec_version == \"2.0\":\n ok = uuid_obj.version == 4\n\n retur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if the CSV file contains all required columns. | def validate_column_names(self, cols):
self.stdout.write('Verifying CSV header')
csv_cols = set(cols)
if self.required_csv_columns <= csv_cols:
return True
else:
missing_cols = set(self.required_csv_columns).difference(csv_cols)
raise ValidationError(
... | [
"def check_declarations_csv(declaration_file):\n columns = 59\n required_fields = [0, 18, 19, 20, 21, 26, 27]\n\n for index, row in enumerate(declaration_file):\n if len(row) != columns:\n return False, \"Row incorrect length row: {}\".format(index)\n\n if row[3] == 'complete':\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Concatenate observation data into one string. | def concatenate_observation_data(
self, compartment, date, measurementmethod, orig_srid, origx, origy,
parameter, property, quality, sampledevice, samplemethod, unit, value,
):
# Convert to string before joining
data = map(str, [
compartment, date, measurementmethod, orig... | [
"def concatenate_data():",
"def obs_to_string(observations):\n str_obs = []\n for obs in observations:\n str_obs.append(obs.reshape(-1).tostring())\n return str_obs",
"def Concat(for_date, time_period):\n \n return str(for_date) +\";\"+ str(time_period)",
"def __str__(self):\n str... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes Observations or removes related Environments. | def remove_or_deref_observations(self, processing_job):
cursor = connection.cursor()
env_hash = self.make_env_hash(processing_job)
# Update observations which have the same environment setup.
# Removes these items from the array.
self.stdout.write('Dereference environment {0} in ... | [
"def del_environment(self):\n self._fetch_with_no_cache()\n self._msg.ClearField(\"environment\")\n self._update(self._msg, method=\"PUT\")",
"def _remove_envs(cls, objs, envs):\r\n for model, instances in cls.cascade_envs_to(objs, adding=False).items():\r\n model._remove_en... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if concatenated_observation_data is in self.observations | def observation_exists_locally(self, concatenated_observation_data):
local_observation = self.observations.get(
concatenated_observation_data,
None
)
if local_observation:
return local_observation['observation'] | [
"def _is_observation(self, observation: D.T_agent[D.T_observation]) -> bool:\n observation_space = self._get_observation_space()\n if self.T_agent == Union:\n return observation_space.contains(observation)\n else: # StrDict\n return all(observation_space[k].contains(v) fo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns False if point does not exist, else return locationpoint id | def point_exists(self, point):
qs = LocationPoint.objects.raw("""
SELECT * FROM script_execution_manager_locationpoint
WHERE st_dwithin(
thegeometry,
st_transform(
st_setsrid(
st_point({point.x}, {point.y}), {point.sri... | [
"def test_point_exists_returns_false(self):\n lp = factories.LocationPointFactory()\n cmd = csv_worker.Command()\n point = Point(float(lp.origx)+1, float(lp.origy), srid=4326)\n self.assertFalse(cmd.point_exists(point))",
"def test_point_exists_returns_lp(self):\n lp = factories... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make a CarlaSettings object with the settings we need. | def make_carla_settings(args):
settings = CarlaSettings()
settings.set(
SynchronousMode=True,
SendNonPlayerAgentsInfo=True,
NumberOfVehicles=0,
NumberOfPedestrians=0,
SeedVehicles = '00000',
WeatherId=1,
QualityLevel=args.quality_level)
settings.random... | [
"def make_carla_settings(args):\n settings = CarlaSettings()\n settings.set(\n SynchronousMode=False,\n SendNonPlayerAgentsInfo=True,\n NumberOfVehicles=0,\n NumberOfPedestrians=0,\n SeedVehicles = '00000',\n WeatherId=1,\n QualityLevel=args.quality_level)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
INTERNAL USE ONLY Get the fact in the KB that is the same as the fact argument | def _get_fact(self, fact):
for kbfact in self.facts:
if fact == kbfact:
return kbfact | [
"def get_fact(self, fact):\n return self.get_facts(fact)",
"def fact(self, name):\n facts = self.facts(name=name)\n return next(fact for fact in facts)",
"def parse_fact(self, factelem) -> Fact:\n\n f = Fact()\n f.tag = re.sub('{.*}', '', factelem.tag)\n f.version = sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
INTERNAL USE ONLY Get the rule in the KB that is the same as the rule argument | def _get_rule(self, rule):
for kbrule in self.rules:
if rule == kbrule:
return kbrule | [
"def rule(self):\n return self.__rule",
"def getRule(self, *args):\n return _libsbml.Model_getRule(self, *args)",
"def get_rule(RuleId=None):\n pass",
"def rule(self):\n return self._rule",
"def find(self, rule_name):\n return self.rules[rule_name]",
"def extract_rule(self) -> P... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add a fact or rule to the KB | def kb_add(self, fact_rule):
printv("Adding {!r}", 1, verbose, [fact_rule])
if isinstance(fact_rule, Fact):
if fact_rule not in self.facts:
self.facts.append(fact_rule)
for rule in self.rules:
self.ie.fc_infer(fact_rule, rule, self)
... | [
"def kb_add(self, fact_rule):\n printv(\"Adding {!r}\", 1, verbose, [fact_rule])\n if isinstance(fact_rule, Fact): # if adding a fact...\n if fact_rule not in self.facts: # check if already in kb\n self.facts.append(fact_rule)\n for rule in self.rules:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Assert a fact or rule into the KB | def kb_assert(self, fact_rule):
printv("Asserting {!r}", 0, verbose, [fact_rule])
self.kb_add(fact_rule) | [
"def testRule(rule):",
"def test_create_rule(self):\n pass",
"def test_rule_python_fact(self):\n fact = self.env.assert_string('(test-fact)')\n self.env.run()\n\n self.assertEqual(self.values[0], fact)",
"def _assert_knowledge(self, knowledge: Knowledge):\n facts = knowledge... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check whether a color is 'dark'. Currently, this is simply whether the luminance is <50% | def dark_color(color):
rgb = hex_to_rgb(color)
if rgb:
return rgb_to_hls(*rgb)[1] < 128
else: # default to False
return False | [
"def is_dark(self):\n\n return self.red() < 125 and self.green() < 125 and self.blue() < 125",
"def is_dark(self) -> bool:\n return self.lightness() < 128",
"def is_light_color(self):\n return self.get_color_lightness() > 127",
"def is_light(self, color):\r\n return colorsys.rgb_to... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Guess whether the background of the style with name 'stylename' counts as 'dark'. | def dark_style(stylename):
return dark_color(get_style_by_name(stylename).background_color) | [
"def _detect_from_widget():\n window = Gtk.Window()\n stc = window.get_style_context()\n foreground = stc.get_color(Gtk.StateFlags.NORMAL)\n background = stc.get_background_color(Gtk.StateFlags.NORMAL)\n contrast = ThemeDetector._calculate_contrast(foreground, background)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Preempt all contained states. | def request_preempt(self):
# Set preempt flag
smach.State.request_preempt(self)
# Notify concurrence that it should preempt running states and terminate
with self._done_cond:
self._done_cond.notify_all() | [
"def request_preempt(self):\n self._client.cancel_all_goals()\n smach.State.request_preempt(self)\n self.srv.shutdown()\n rospy.logwarn(\"Guide Interface Preempted!\")",
"def pre_states():\n return ['startup', 'sanity', 'acquire', 'base', 'monitor']",
"def remove_all_basic_states(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
We are going to generate 10 unique characters in the addrs and labels | def generateUniqueAddrs(saveImagePath,numUnique,trainType,addrs_labels):
print("Saving only {} unique characters for {}".format(numUnique,trainType))
train_addrs = addrs_labels[0]
train_labels = addrs_labels[1]
test_addrs = addrs_labels[2]
test_labels = addrs_labels[3]
ge... | [
"def generate_uuids():\n uuid_start = str(uuid())\n while uuid_start.startswith(\"zzzzzzzz\"):\n uuid_start = str(uuid())\n uuid_end = list(deepcopy(uuid_start))\n \n char_pool = list(string.digits) + \\\n list(string.ascii_uppercase) + \\\n list(string.ascii_lowercase) \n # p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if have an modal in the page and close it | def check_modal(client):
modal_close_btn_xpath = "/html/body/div[9]/div[3]/div/button[1]"
try:
modal_close_btn = wait(client, 20).until(
EC.visibility_of_element_located((By.XPATH, modal_close_btn_xpath))
).click()
except TimeoutException:
pass | [
"def close_the_modal(self):\n\n locator = \"css: button.slds-modal__close\"\n self.selenium.wait_until_element_is_enabled(locator)\n self.selenium.click_element(locator)\n self.wait_until_modal_is_closed()\n self._remove_from_library_search_order()",
"def wait_until_modal_is_clo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |