query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Test that we can multiple a matrix by a tuple
def test_matrix_tuple_multiplication(self): M = matrices.Matrix(4, 4) M.set_row(0, [1, 2, 3, 4]) M.set_row(1, [2, 4, 4, 2]) M.set_row(2, [8, 6, 4, 1]) M.set_row(3, [0, 0, 0, 1]) t = tuples.Tuple(["x", "y", "z", "w"], 1, 2, 3, 1) t2 = M * t self.assertE...
[ "def test_classic_2x2(self):\r\n # problem\r\n A = [[0, 1], [1, 0]]\r\n B = [[2, 3], [3, 2]]\r\n\r\n # solution\r\n answer = [[3, 2], [2, 3]]\r\n\r\n # test\r\n C = matrix_multiply(A, B)\r\n self.assertEqual(C, answer)", "def test_classic_4x4(self):\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test we can transpose a matrix
def test_matrix_transpose(self): M = matrices.Matrix(3, 3) M.set_row(0, [1, 2, 3]) M.set_row(1, [3, 2, 1]) M.set_row(2, [2, 4, 6]) M = M.transpose() expected = matrices.Matrix(3, 3) expected.set_row(0, [1, 3, 2]) expected.set_row(1, [2, 2, 4]) e...
[ "def test_transpose(self):\r\n size = (5, 4)\r\n x = create_var(size)\r\n expr, constr = transpose(x)\r\n assert len(constr) == 0\r\n self.assertEqual(expr.size, (4, 5))\r\n coeffs = get_coefficients(expr)\r\n assert len(coeffs) == 1\r\n id_, var_size, mat = c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test we can calculate the determinant of a 2x2 matrix
def test_determinant_2_by_2(self): M = matrices.Matrix(2, 2) M.set_row(0, [1, 5]) M.set_row(1, [-3, 2]) self.assertEqual(M.det(), 17)
[ "def determinant(m):\n\treturn np.linalg.det(m)", "def determinant(self):\n if not self.is_square():\n raise(ValueError, \"Cannot calculate determinant of non-square matrix.\")\n #if self.h > 2:\n #raise(NotImplementedError, \"Calculating determinant not implemented for matrice...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test we can calculate the determinant of a 3x3 matrix
def test_determinant_3_by_3(self): M = matrices.Matrix(3, 3) M.set_row(0, [1, 2, 6]) M.set_row(1, [-5, 8, -4]) M.set_row(2, [2, 6, 4]) self.assertEqual(M.cofactor(0, 0), 56) self.assertEqual(M.cofactor(0, 1), 12) self.assertEqual(M.cofactor(0, 2), -46) s...
[ "def test_determinant_2_by_2(self):\n\n M = matrices.Matrix(2, 2)\n M.set_row(0, [1, 5])\n M.set_row(1, [-3, 2])\n\n self.assertEqual(M.det(), 17)", "def test_determinant_4_by_4(self):\n\n M = matrices.Matrix(4, 4)\n M.set_row(0, [-2, -8, 3, 5])\n M.set_row(1, [-3,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test we can calculate the determinant of a 4x4 matrix
def test_determinant_4_by_4(self): M = matrices.Matrix(4, 4) M.set_row(0, [-2, -8, 3, 5]) M.set_row(1, [-3, 1, 7, 3]) M.set_row(2, [1, 2, -9, 6]) M.set_row(3, [-6, 7, 7, -9]) self.assertEqual(M.cofactor(0, 0), 690) self.assertEqual(M.cofactor(0, 1), 447) ...
[ "def test_determinant_2_by_2(self):\n\n M = matrices.Matrix(2, 2)\n M.set_row(0, [1, 5])\n M.set_row(1, [-3, 2])\n\n self.assertEqual(M.det(), 17)", "def determinant(m):\n\treturn np.linalg.det(m)", "def determinant(self):\n if not self.is_square():\n raise(ValueErr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test we can calculate submatrices
def test_get_submatrix(self): # First up a 3x3 example M = matrices.Matrix(3, 3) M.set_row(0, [1, 5, 0]) M.set_row(1, [-3, 2, 7]) M.set_row(2, [0, 6, -3]) result = M.submatrix(0, 2) expected = matrices.Matrix(2, 2) expected.set_row(0, [-3, 2]) e...
[ "def test_subsampling():\n test_data = np.array([1])\n with raises(ValueError) as errorinfo:\n sub_data = _subsampling(test_data, 1)\n assert \"Unrecognized matrix dimension\" in str(errorinfo.value)\n\n test_data = np.random.rand(2, 3, 4)\n sub_data = _subsampling(test_data, sub_depth=2)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test we can calculate the minor of a 3x3 matrix
def test_minor_3_by_3(self): M = matrices.Matrix(3, 3) M.set_row(0, [3, 5, 0]) M.set_row(1, [2, -1, -7]) M.set_row(2, [6, -1, 5]) result = M.minor(1, 0) self.assertEqual(result, M.submatrix(1, 0).det()) self.assertEqual(result, 25)
[ "def minor(self, row, col):\r\n return self.submatrix(row, col).determinant()", "def minor(self, i, j):\n return self.submatrix(i, j).det()", "def minor(matrix):\n if type(matrix) is not list or not len(matrix):\n raise TypeError(\"matrix must be a list of lists\")\n\n if matrix == [[...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test we can calculate the cofactors of a 3x3 matrix
def test_cofactor_3_by_3(self): M = matrices.Matrix(3, 3) M.set_row(0, [3, 5, 0]) M.set_row(1, [2, -1, -7]) M.set_row(2, [6, -1, 5]) self.assertEqual(M.minor(0, 0), -12) self.assertEqual(M.cofactor(0, 0), -12) self.assertEqual(M.minor(1, 0), 25) self.ass...
[ "def cofactors(mat):\n minorsMat = minors(mat)\n coMat = [[(-1) ** (row + col) * minorsMat[row][col]\n for col in range(len(minorsMat[row]))]\n for row in range(len(minorsMat))]\n return Matrix(coMat)", "def cofactor(m):\n cof = np.empty((3, 3))\n\n cof[0][0] = m[1][1]*m[2]...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that multipling a matrix by its inverse does what is expected
def test_inverse_self_multiply(self): A = matrices.Matrix(4, 4) A.set_row(0, [3, -9, 7, 3]) A.set_row(1, [3, -8, 2, -9]) A.set_row(2, [-4, 4, 4, 1]) A.set_row(3, [-6, 5, -1, 1]) B = matrices.Matrix(4, 4) B.set_row(0, [8, 2, 2, 2]) B.set_row(1, [3, -1, 7,...
[ "def is_inverse(matrix, other):\n # TODO\n return matrix_multiplication(matrix,other) == unit_matrix(matrix.row_num) and \\\n matrix_multiplication(other,matrix) == unit_matrix(other.row_num)", "def test_classic_2x2(self):\r\n # problem\r\n A = [[0, 1], [1, 0]]\r\n B = [[2, 3]...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Download file from s3
def download(self, s3_key, path): local_file = s3_key.split('/')[-1] local_file = path + "/" + local_file try: self.s3.Bucket(self.BUCKET_NAME).download_file(s3_key, local_file) except botocore.exceptions.ClientError as e: if e.response['Error']['Code'] == "404": ...
[ "def download_file(key):\n return s3_bucket.Object(key).get()", "def download_file_from_bucket(self):\n self.s3_client.download_file(BUCKET_NAME, FILENAME, DOWNLOAD_FILENAME)\n print(\"File downloaded to : %s/%s\" % (os.getcwd(), DOWNLOAD_FILENAME))", "def download_from_s3():\n s3 = boto3.re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return true if line matches footnote pattern.
def is_footnote(line: str) -> bool: # Tested: Actually only removes the footnote lines. # Here we explicitly DO want to use 'match' and not 'search', as we need # the match to occur at the start of the line. return re.match(r'[0-9]+\.\s*', line) # OLD: return re.match(r'[0-9]+ {2,3}\w+....
[ "def _is_mxp_footer(line):\n return line.strip().startswith('- - - - - - - - - - - - - - - - - -')", "def istodo(self, line):\n\t\treturn any((\n\t\t\tre.search(r'\\s+%s\\s+' % self.marker, line),\n\t\t\tre.search(r'^%s\\s+' % self.marker, line)\n\t\t))", "def testFootnotes(self, b, u):\n rx = re.comp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
retrieve individuals that need to be created (that only exist in the database so far)
def getHNtodos(self): self.cur.execute("SELECT * FROM " + self.tablePrefix + "_individuals AS i " + "WHERE i.hyperneated = 0 AND born < '" + str(self.maxSimTime) + "'") results = self.cur.fetchall() return self.onlyGetIDs(results)
[ "def test_retrieve_ingredients_assigned_unique(self):\n ingredient = Ingredient.objects.create(\n user=self.user,\n name='ingredient 1'\n )\n Ingredient.objects.create(user=self.user, name='ingredient 2')\n recipe1 = Recipe.objects.create(\n title='recipe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
retrieve individuals that need to be voxelyzed
def getVoxTodos(self, resubmit=False): searchString = "SELECT * FROM " + self.tablePrefix + "_individuals AS i " + \ "WHERE i.hyperneated = 1" if (resubmit): searchString += " AND i.vox_submitted = 1 AND i.voxelyzed = 0" else: searchString += " AND ...
[ "def select(self) -> None:\n\n # Calculate the fitness of each individual in the population\n self.fitness_values = {}\n for individual in self.population:\n self.fitness_values[individual] = self.fitness_calculator(individual)\n\n # This can be improved, but for now, we will ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
marks the individual as been submitted to Lisa
def markAsVoxSubmitted(self, indiv): self.cur.execute( "UPDATE " + self.tablePrefix + "_individuals SET vox_submitted = 1 WHERE id = " + str(indiv) + ";") self.flush()
[ "def Mark(self, user, title_or_id):\n uid = user['id']\n name = user['first_name']\n #Add user if unknown\n if uid not in self.users:\n self.users[uid] = {}\n self.userNameMap[uid] = name\n if title_or_id not in self.problems:\n raise Except...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
reenable all individuals for resubmission to the cluster by removing the submitted flag
def unmarkAsVoxSubmitted(self): self.cur.execute( "UPDATE " + self.tablePrefix + "_individuals SET vox_submitted = 0 WHERE postprocessed = 0;") self.flush()
[ "def remove_clusterd_rei(self):\n for rei in [REI_VREQ_PLACEMENT_BLOCK_ON_VS_UPDATE, REI_VREQ_SIZE_BLOCK_ON_START]:\n try:\n print(\"Clearing clusterd REI\", rei)\n self.kubectl_helper.rei_clear(rei, DEF_CLUSTERD_POD, container_name=DEF_CLUSTERD_CONTAINER)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
marks the individual as having the trace file inserted in the database
def markAsTraced(self, indiv): self.cur.execute( "UPDATE " + self.tablePrefix + "_individuals SET traced = 1 WHERE id = " + str(indiv) + ";") self.flush()
[ "def mark_alert_processed(self, uuid):\n try:\n with sqlite3.connect(self.alert_uuid_cache_path) as db:\n c = db.cursor()\n c.execute(\"INSERT INTO uuid_tracking ( uuid, insert_date ) VALUES ( ?, ? )\",\n (uuid, datetime.datetime.now().timestam...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert MPI datatype to NumPy.
def tonumpy(datatype): # pylint: disable=too-many-locals # pylint: disable=too-many-branches # pylint: disable=too-many-statements # pylint: disable=too-many-return-statements # try: # from numpy import dtype # except ImportError: # dtype = lambda arg: arg dtype = lambda arg...
[ "def to_numpy(data):\n if isinstance(data, (int, float)):\n return np.array(data)\n if isinstance(data, np.ndarray):\n return data\n if isinstance(data, torch.Tensor):\n return data.detach().cpu().numpy()\n raise TypeError(f'Not supported data type `{type...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
read the STEP file and returns a compound
def read_step_file(filename): step_reader = STEPControl_Reader() logging.info("### Read Step File ###") status = step_reader.ReadFile(filename) if status == IFSelect_RetDone: # check status # failsonly = True # step_reader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity) # step...
[ "def read_step_file(filename):\n step_reader = STEPControl_Reader()\n status = step_reader.ReadFile(filename)\n\n if status == IFSelect_RetDone: # check status\n failsonly = False\n step_reader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity)\n step_reader.PrintCheckTransfer(failsonl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is the function called every time an edge is clicked in the 3d view
def click_edge(self, edge_click, *kwargs): # shp = A list of TopoDS_Shape; type=Face, if click a place without model, it is null # kwargs xy coordinate in 2D where mouse is clicked print("\nClicked - edge select mode !!") print('===============================================') f...
[ "def drawScene(self, event):", "def mouse_click(self):\n global selected_edge\n selected_edge = None\n\n if (self.mouse_inside() and self.active and not self.is_neighbour()): # and self.face1 not in visitedfaces):\n self.active = False\n self.faceid = self.get_a_faceid(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is the function called every time a face is clicked in the 3d view
def click_face(self, face_click, *kwargs): # shp = A list of TopoDS_Shape; type=Face, if click a place without model, it is null # kwargs xy coordinate in 2D where mouse is clicked print("\nClicked - face select Mode!!") print('===============================================') ...
[ "def face_callback(self,value):", "def on_3D(self, event):\n if self.currentview == wx.ID_NO:\n # Hide 2D view\n self.canv_feed_sizer.Hide(0)\n # Show 3D view\n self.canv_feed_sizer.Show(1)\n # Reload\n self.main_sizer.Layout()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns a text str of legal charss in val that is the same length as fmt
def _clean_val_(self, val): if val is None: val = '' else: val = ''.join([x for x in val.upper() if x in ArbBitField.legalValChars]) val = val[:len(self.fmt)] # truncate to fmt length val = val + '0'*(len(self.fmt)-len(val)) # pad t...
[ "def vformat(self,val):\n if type(val)==int and self.vtype== schema.TYPE_CHAR:\n \"\"\"An integer is being formatted as a fixed with character. Be sure it is 0-filled\"\"\"\n return str(val).zfill(self.width)\n if type(val)==str and self.vtype== schema.TYPE_CHAR:\n \"\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
support lists but still return a single int if that's what's passed field may be a slice. Internal use.
def _to_int_(field): if len(field) == 1: ret = ArbBitField._field_to_int_(field) else: ret = [ArbBitField._field_to_int_(x) for x in field] return ret
[ "def _to_slice( item ):\n if isinstance( item, int ):\n return slice( item, item+1 )\n if isinstance( item, slice ):\n return item\n else:\n raise TypeError(\"Input must be Int or Slice\")", "def get_first_of_dicom_field_as_int(x):\n\n import pydicom\n\n if type(x) == pydicom.m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns a list of bools; Options to reverse bitwise and fieldwise. Normal order is left to right fields and MSB to LSB bits
def bool(self, rev_bits=False, rev_fields=False): if rev_fields: tmp_fmt, tmp_val = self.fmt[::-1], self.val[::-1] else: tmp_fmt, tmp_val = self.fmt[::], self.val[::] ret = [] for fmt_idx, fmt_c in enumerate(tmp_fmt): count = ArbBitField._to_int...
[ "def set_bool(self, b_lst, rev_bits=False, rev_fields=False):\r\n if rev_fields:\r\n tmp_fmt = self.fmt[::-1]\r\n else:\r\n tmp_fmt = self.fmt[::]\r\n vstr = ''\r\n tmp_val = ['%s'%('1' if x else '0') for x in b_lst] # convert bools to chars, if needed\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
sets val from a list of bools (read from the hardware, e.g.) Normal input order is left to right fields and MSB to LSB bits
def set_bool(self, b_lst, rev_bits=False, rev_fields=False): if rev_fields: tmp_fmt = self.fmt[::-1] else: tmp_fmt = self.fmt[::] vstr = '' tmp_val = ['%s'%('1' if x else '0') for x in b_lst] # convert bools to chars, if needed offset = 0 ...
[ "def set(self, ind, val):\n\n # Calculate the physical position of the bit in the Boolarray\n real_ind = ind // 8\n bitvec_ind = ind % 8\n\n # Enlarge the array if necessary\n self._expand(real_ind)\n\n # Set the bit\n if val == True:\n self.intarray[rea...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handy formatter from list of bools to text
def bool_to_str(b_lst, zero_val=' '): return ''.join(['%s'%('1' if b_val else zero_val) for b_val in b_lst])
[ "def format_bool(value):\n return 'true' if value else 'false'", "def _map_boolean_to_human_readable(boolean, resource, token):\n if boolean:\n return 'Yes'\n else:\n return 'No'", "def boolToStr(val):\n\tif val == True:\n\t\treturn \"ON\"\n\telif val == False:\n\t\treturn \"OFF\"", "def ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test auxiliar function, bracket_to_index
def test_bracket_to_index(self): true = [-1,-1,65,64,63,-1,-1,-1,59,58,57,-1,-1,-1,24,23,22,21,-1,-1,-1,17,16,15,14,-1,-1,51, 50,49,48,-1,-1,-1,44,43,42,-1,-1,-1,-1,-1,36,35,34,-1,-1,-1,30,29,28,27,-1,-1,-1,-1, -1,10,9,8,-1,-1,-1,4,3,2,-1,-1,-1] index = stc.bracket_to_ind...
[ "def parse_index(*args, **kwargs): # real signature unknown\n pass", "def test_getitem_root(self):\n x = IndexedVariable(name='x', index=1)\n self.assertIs(x[()], x)", "def index(self, x, start = 0, end=None):", "def getSubOperandIndex(self) -> int:\n ...", "def __getindex__(self, to...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make a list of which source column index maps to which destination column index and readd keys
def _make_shortcuts_readd_keys(_mappings, _source_dataset, _destination_dataset): _shortcuts = [] _key_fields = [] # Make mapping for _curr_mapping in _mappings: if _curr_mapping.src_reference is not None and _curr_mapping.src_reference != "": _src_idx = _sou...
[ "def _remap(_shortcuts, _key_fields, _source_dataset, _destination_dataset):\n\n _mapped_source = []\n # Loop all rows in the source data set\n for _curr_row in _source_dataset.data_table:\n # Create an empty row with None-values to fill later\n _curr_mapped = []\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a remapped source data set that has the same data in the same columns as the destination data set. Also and remaps keys.
def _remap(_shortcuts, _key_fields, _source_dataset, _destination_dataset): _mapped_source = [] # Loop all rows in the source data set for _curr_row in _source_dataset.data_table: # Create an empty row with None-values to fill later _curr_mapped = [] # Create...
[ "def remap_dataset(src_data, target_data, weights):\n\n src_data = _try_open(src_data)\n target_data = _try_open(target_data)\n weights = _try_open(weights)\n\n snlon, snlat = len(src_data.lon), len(src_data.lat)\n tnlon, tnlat = len(target_data.lon), len(target_data.lat)\n\n # Stack the source da...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test getting an icon using the helper function.
def test_get_icon(app, icon_workbench): assert get_icon(icon_workbench, 'folder-open')
[ "def test_set_icon(self):\n # XXX: figure this out\n pass", "def test_render_icon(self):\n icon = self.block.meta.icon\n self.assertEqual(icon, 'fa-hand-o-up', 'The icons did not match')", "def test_render_icon(self):\n icon = self.block.meta.icon\n self.assertEqual(ico...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method to add a value to the set of notpossible solutions.
def remove_from_possible(self, value): self.not_possible.add(value)
[ "def add_to_set(value, values):\n if value:\n values.add(value)\n return values", "def add_possible_answer(self, answer):\n self.possible_answers.append(answer)", "def add(self, value):\n if value:\n self.values.add(value)", "def add_solution(self, remaining=0):\n new_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given the path to the ModelNet10 dataset, samples the models and creates point clouds
def create_point_cloud_dataset(data_dir, num_points_per_cloud=1024): train_pc = [] # array of training point clouds test_pc = [] # array of test point clouds train_labels = [] # array of corresponding training labels test_labels = [] # array of corresponding test labels class_ids = {} # list...
[ "def load_model(self, checkpoint_dir):\n self.NoiseAmp = np.load(checkpoint_dir + '/NoiseAmp.npy')\n dir = os.walk(checkpoint_dir)\n for path, dir_list, _ in dir:\n for dir_name in dir_list:\n network = dir_name[0]\n scale = int(dir_name[1])\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Utility function to visualize a point cloud
def visualize_cloud(point_cloud, true_label='', predicted_label=''): if true_label=='': fig = plt.figure() ax = Axes3D(fig) ax.scatter(point_cloud[:, 0], point_cloud[:, 1], point_cloud[:, 2]) plt.show() else: fig = plt.figure() ax = Axes3D(fig) ax.scatter(...
[ "def show_palpation_point_cloud(data_file):\n\n coords = np.array([])\n\n with open(data_file, 'r') as csvfile:\n reader = csv.DictReader(csvfile)\n for row in reader:\n coord = np.array([\n float(row[\"arm_position_x\"]),\n float(row[\"arm_position_y\"])...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds noise to a point cloud and shuffles it
def add_noise_and_shuffle(point_cloud, label): dev_in_metres = 0.05 # <- change this value to change amount of noise # add noise to the points point_cloud += tf.random.uniform(point_cloud.shape, -dev_in_metres, dev_in_metres, dtype=tf.float64) # shuffle points # point_cloud = tf.random.shuffle(poin...
[ "def add_noise(self):\n for i in range(self.num_neurons):\n spike_train = deepcopy(self.spike_trains[i, :])\n\n # Get indices without spikes.\n indices = [j for j, dt in enumerate(spike_train) if dt == 0]\n\n # Add spikes to indices randomly with given probability....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Pickles a list writes it out in Python's pickle format at the specified location.
def write_pkl(list_to_pickle, write_location): with open(write_location, "wb") as f: pickle.dump(list_to_pickle, f)
[ "def pickle_list(list_to_pickle, write_location):\n with open(write_location, \"wb\") as f:\n pickle.dump(list_to_pickle, f)", "def main():\r\n # Annotate variables\r\n file_out: io.BufferedWriter\r\n file_in: io.BufferedReader\r\n numbers_out: list = [1, 2, 3, 4, 5]\r\n numbers_in: list\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This will test supported Flow Size
def test_flow_sizes(serializer, api, tx_port, rx_port, b2b_ipv4_devices): port_endpoint = PortTxRx(tx_port_name=tx_port.name, rx_port_name=rx_port.name) pause = Header( PfcPause(dst=Pattern('01:80:C2:00:00:01'), class_enable_vector=Pattern('1'), ...
[ "def test_partition_sizes(self):\n assert self.state.partition_sizes == (3, 4, 5, 6, 7, 8, 9)", "def test_isc_utils_size_spec_passing(self):\n test_data = [\n 'unlimited',\n 'default',\n '1',\n '0',\n '100',\n '1K',\n '2k',...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the next site id to retrieve. This tweak is required as Somfy does not allow to call the /site entrypoint more than once per minute.
def _site_id(self): self.last_site_index = (self.last_site_index + 1) % len(self.site_device) return list(self.site_device.keys())[self.last_site_index]
[ "def _generate_static_tunnel_id(self) -> int:\n if self._static_tunnels:\n return max(self._static_tunnels.keys()) + 1\n return 1", "def get_site(self):\n try:\n return self.get_sites()[0]\n except IndexError:\n return None", "def _getNextID(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a matplotlib figure containing the plotted confusion matrix.
def plot_confusion_matrix(cm, class_names): figure = plt.figure(figsize=(8, 8)) plt.imshow(cm, interpolation='nearest', cmap=plt.cm.Blues) plt.title("Confusion matrix") plt.colorbar() tick_marks = np.arange(len(class_names)) plt.xticks(tick_marks, class_names, rotation=45) plt.yticks(tick_ma...
[ "def plot_confusion_matrix(cm, class_names):\n figure = plt.figure(figsize=(8, 8))\n plt.imshow(cm, interpolation='nearest', cmap=plt.cm.Blues)\n plt.title(\"Confusion matrix\")\n plt.colorbar()\n tick_marks = np.arange(len(class_names))\n plt.xticks(tick_marks, class_names, rotation=45)\n plt....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test all configuration file edit methods on an active db
def test_config_methods(dbutils, local_db): # test the happy path and ensure all configuration file edit methods # successfully execute when given correct key-value pairs configs = dbutils.get_db_configs() for setting, value in configs.items(): config_set_method = dbutils.get_config_edit_method...
[ "def test_config_methods_inactive(wlmutils, dbutils):\n db = wlmutils.get_orchestrator()\n configs = dbutils.get_db_configs()\n for setting, value in configs.items():\n config_set_method = dbutils.get_config_edit_method(db, setting)\n with pytest.raises(SmartSimError):\n config_set...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ensure a SmartSimError is raised when trying to set configurations on an inactive database
def test_config_methods_inactive(wlmutils, dbutils): db = wlmutils.get_orchestrator() configs = dbutils.get_db_configs() for setting, value in configs.items(): config_set_method = dbutils.get_config_edit_method(db, setting) with pytest.raises(SmartSimError): config_set_method(val...
[ "def test_setup_missing_config(self):\n self.configuration.scality_sofs_config = 'nonexistent.conf'\n self.assertRaises(exception.VolumeBackendAPIException,\n self._driver.do_setup, None)", "def test_systemcheck_db_fail(self):\n\n # Corrupt db name, i.e. simulate DB f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert a pandas dataframe to a dokuwiki table (which you can copypaste onto the XENON wiki)
def dataframe_to_wiki(df, float_digits=5, title='Awesome table'): table = '^ %s ' % title + '^' * (len(df.columns) - 1) + '^\n' table += '^ ' + ' ^ '.join(df.columns) + ' ^\n' def do_round(x): if isinstance(x, float): return round(x, float_digits) return x for _, row in df....
[ "def pandas_df_to_markdown_table(df: pd.DataFrame) -> str:\n\n fmt = ['---' for i in range(len(df.columns))]\n df_fmt = pd.DataFrame([fmt], columns=df.columns)\n df_formatted = pd.concat([df_fmt, df])\n return Markdown(df_formatted.to_csv(sep=\"|\", index=False)).data", "def do_wiki(table):\n\n def...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make a button in the jupyter notebook to hide all code
def code_hider(): # Stolen from stackoverflow... forget which question # I would really like these buttons for every individual cell.. but I don't know how from IPython.display import HTML # Please keep here, don't want hax to depend on ipython! return HTML(dedent(''' <script> ...
[ "def notebook_visible_toggle_action(self):\n\n self.notebook.Show(not self.notebook.IsShown())\n self.viewmenu.Check(406, self.notebook.IsShown())\n self.SendSizeEvent()", "def hide(self):\n self.is_visible = False", "def _hide_metadata_status_buttons(self):\n self.__log.call(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update grand total each time a line item is added, accounting for discounts
def update_total(self): self.order_total = self.lineitems.aggregate( Sum('lineitem_total'))['lineitem_total__sum'] or 0 self.grand_total = self.order_total self.save()
[ "def update_total(self):\n self.total = self.lineitems.aggregate(Sum('lineitem_total'))['lineitem_total__sum'] or 0\n self.save()", "def update_total(self):\n self.order_total = (\n self.lineitems.aggregate(Sum(\"lineitem_total\"))[\n \"lineitem_total__sum\"\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load Project Dashboard to display Latest Cost Estimate and List of Changes
def get_dashboard(request, project_id): project = get_object_or_404(Project, id=project_id) # required to determine permission of user, # if not a project user then project owner try: project_user = ProjectUser.objects.get( project=project, project_user=request.user) except Proj...
[ "def projects_internal_summary(request: HttpRequest) -> HttpResponse:\n\n # Dict for view\n view_dict = {} # type: Dict[str, object]\n\n # Construct q query and check the project filter form\n q = Q()\n from_date = Project.min_start_date()\n until_date = Project.max_end_date()\n if request.met...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete an attachment a Change whilst in the Edit Change mode
def delete_file(request, change_id, file_id): attachment = get_object_or_404(ChangeAttachments, pk=file_id) attachment.delete() return redirect(reverse('edit_change', args=[change_id]))
[ "def _delete_attachment(self, task):\n for each in self.cleaned_data.get('delete_attachment', []):\n each.delete()", "def delete_my_attachment(request, ticket_id, attachment):\n ticket = get_object_or_404(Ticket, code=ticket_id)\n json_dict = json.loads(ticket.modulo_compilato)\n ticket...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Nurses' home page allowing to see all the office's nurses and their information, to edit them or add a new one
def home(): if request.method == "POST": research = request.form['research'] error = None if not research: error = 'Please enter the name of our nurse.' if error is not None: flash(error) else: return redirect(url_for('nurses.search_nurs...
[ "def homepage():\n standings_data = fetch_standings()\n return render_template('index.html',\n standings=standings_data['data'],\n gameweek=standings_data['gameweek'],\n status=standings_data['status'],\n g...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function allowing to search for a precise nurse's information
def search_nurses(research): if request.method == "POST": new_research = request.form['research'] error = None if not new_research: error = 'Please enter the name of a nurse.' if error is not None: flash(error) else: return redirect(url_...
[ "def search_employee(self):", "def search(self):\n #Take in input\n gpa = input(\"Please input GPA. If you do not wish to search by GPA enter \\\"?\\\"\\n\").strip()\n major = input(\"Please input student's Major. If you do not wish to search by Major enter \\\"?\\\"\\n\").strip()\n fa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a new nurse in the database
def add_nurse(): if request.method == 'POST': last_name = request.form['last_name'] first_name = request.form['first_name'] email = request.form['email'] password = request.form['password'] phone = request.form['phone_number'] address = request.form['address'] ...
[ "def add_discipline(self):\n\n name = str(self.le_name.text())\n if not name:\n required_field_empty_warning(self)\n else:\n db.insert_objects(Discipline(name=name))", "def add_student(self):\n print(\"You have chosen to add a student\")\n #Collect input\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Edit nurse information in database
def edit_nurse(nurse_id): if request.method == "POST": last_name = request.form['last_name'] first_name = request.form['first_name'] email = request.form['email'] phone = request.form['phone_number'] address = request.form['address'] cares = Care.query.all() ...
[ "def edit_isp(isp_id):\n isp = db_session.query(ISP).filter_by(id=isp_id).one()\n\n if request.method == \"POST\":\n if request.form[\"choice\"] == \"edit\":\n isp.name = request.form[\"name\"]\n db_session.add(isp)\n db_session.commit()\n flash(\"ISP Success...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete nurse from database
def delete_nurse(nurse_id): nurse = Nurse.query.get(nurse_id) db.session.delete(nurse) db.session.commit() flash("The nurse was successfully deleted.") return redirect(url_for('nurses.home'))
[ "def delete_survey(self,iSurveyID):", "def test_eliminacion(self):\n S2 = Sprint.objects.get(nombre= 'Sprint 2')\n S2.delete()\n\n print('Eliminacion de Sprints ejecutada correctamente.')", "def delete(self, sql):", "def delete_record():", "def deleteStudent(self, request):\n\t\tif 'dtu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Replace newline symbols in .cfg with a space
def reformat_prairie_cfg(cfg_filepath): for line in fileinput.input(cfg_filepath, inplace=1): if '&#x1;' in line: line = line.replace('&#x1;', ' ') sys.stdout.write(line)
[ "def test_get_configdict_from_configfile_with_lines_commented_out(tmp_path):\n os.chdir(tmp_path)\n configfile_content = \"verbose: False\\n\" \"# htmlify: True\\n\"\n Path(CONFIGFILE_NAME).write_text(configfile_content)\n expected = {\"verbose\": False}\n assert get_configdict() == expected", "def...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read in a list of input filenames and write out as a multipage TIFF
def save_multipage_TIFF(input_filenames, output_filename): raise NotImplemented("Need to update for multiple planes") from libtiff import TIFF f = TIFF.open(input_filenames[0], 'r') first_img = f.read_image() f.close() output_array = np.empty( [first_img.shape[0], first_img.shape[1], le...
[ "def _multipage_tif(self):\n cmd = ['convert'] # ImageMagick command `convert` can merge individual tifs into a multipage tif file\n tifs = sorted(glob.glob(self.indiv_page_prefix + '*.tif'), key=os.path.getmtime)\n cmd.extend(tifs) # add all individual tifs as arguments\n multitif_nam...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to convert all found TIFF files to HDF5. Based on Prairie's naming convention, parses their xml file to extract filenames. Arguments directory path to walk down to find data overwrite If True, overwrites h5 file if tiffs are still there no_action If True, do nothing, just report messages delete If True, delete...
def convert_to_HDF5( directory=os.curdir, overwrite=False, no_action=False, delete=False, temp_dir=None, move_dir=None, debug=False, force=False, compression=None, skip_bad_files=False): group = '/' key = 'imaging' file_check_regex = re.compile('\S_Cycle.*Ch[12]_0+\d+.*tif') # ...
[ "def convert_to_hdf5(result_folder):\n\t# process only files with these muscle names\n\tfor muscle in [\"MN_E\", \"MN_F\"]:\n\t\tlogger.info(f\"converting {muscle} dat files to hdf5\")\n\t\tis_datfile = lambda f: f.endswith(f\"{muscle}.dat\")\n\t\tdatfiles = filter(is_datfile, os.listdir(result_folder))\n\t\t# prep...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
TextDocument are identified using URI
def TextDocumentIdentifier(): return {"uri": DocumentUri()}
[ "def read_text(cls, uri):\n return cls.read_text_method(uri)", "def main(\n project_id=\"YOUR_PROJECT_ID\",\n input_uri=\"gs://cloud-samples-data/documentai/invoice.pdf\",\n):\n\n client = documentai.DocumentUnderstandingServiceClient()\n\n gcs_source = documentai.types.GcsSource(uri=input_uri)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A parameter literal used in requests to pass a text document and a position inside that document
def TextDocumentPositionParams(): return {"textDocument": TextDocumentIdentifier(), "position": Position()}
[ "def paramline(name, atype, doc):\n return \":param {1} {0}: {2}\".format(name, atype.__name__, doc)", "def input_parameter_name(name, var_pos):\n return \"para-%s-%s\" % (name, var_pos)", "def paramLocator(object, position=bool):\n pass", "def pointAtParm(*args, **kwargs):\n \n pas...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Normalize a value as (value lo)/(hi lo)
def norm(self, value): return (value - self.lo) / (self.hi - self.lo)
[ "def normalized_value(value, average, stdDesv):\n return float(value - average) / stdDesv", "def normalize(self, value: np.ndarray) -> np.ndarray:\n std = np.sqrt(self.var)\n if self.count == 0 or np.equal(std, 0).any():\n return value\n return (value - self.mean) / (std + self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Denormalizes a value as (hilo)value _ lo
def denorm(self, value): return (self.hi - self.lo)*value + self.lo
[ "def denormalize(self,value):\r\n\t\tif type(value) is ListType:\r\n\t\t\tvalue=np.array(value)\r\n\t\treturn value*(self.max-self.min)+self.min", "def _normalize_reading(self, value):\n return value / float(self.max_sensor_val)", "def normalize(self, value):\r\n\t\tif type(value) is ListType:\r\n\t\t\tv...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute the objectives for an array of decisions
def get_objectives(decisions): f1 = -(25*(decisions[0] - 2)**2 + (decisions[1] - 2)**2 + (decisions[2] - 1)**2 * (decisions[3]-4)**2 + (decisions[4] - 1)**2) f2 = sum([d**2 for d in decisions]) return f1, f2
[ "def _compute_predictions(self, X, y, objectives):\n y_predicted = None\n y_predicted_proba = None\n if any(o.score_needs_proba for o in objectives):\n y_predicted_proba = self.predict_proba(X)\n if any(not o.score_needs_proba for o in objectives):\n y_predicted = s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if the constraints are satisfied for a set of decisions
def check_constraints(decisions): #g1(x) status = decisions[0] + decisions[1] - 2 >= 0 #g2(x) status = status and (6 - decisions[0] - decisions[1] >= 0) #g3(x) status = status and (2 - decisions[1] + decisions[0] >= 0) #g4(x) status = status and (2 - decisions[0] + 3*decisions[1] >= 0) ...
[ "def _checkConstraints(self, point, optVar, lower, upper, constraints, info):\n allOkay = lower < point[optVar] < upper\n if allOkay:\n for constraint in constraints:\n info.update(point)\n okay = constraint.evaluate('constrain', info)\n allOkay &= okay\n\n return allOkay", "def...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Modify an index in a solution that leads to the best solution range in that index
def change_for_best(soln, index): t_evals = 0 lo = model.decisions[index].lo hi = model.decisions[index].hi delta = (hi - lo) / settings.get('steps') best_soln, best_score = soln, -sys.maxint for val in np.arange(lo, hi+delta, delta): cloned = list(soln) cloned[index] = val t_s...
[ "def mutate(x):\n global bounds\n p = 0.1\n new_bounds = []\n for i in xrange(6):\n mn = min(x[i]-p*bounds[i][0], bounds[i][0])\n mx = max(x[i]+p*bounds[i][1], bounds[i][1])\n bound = (mn,mx)\n new_bounds.append(bound)\n \n return generate_solution(new_bounds)", "def ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Dummy Test method. 1) Random runs osyczka2 to get the extremes for objectives 2) Once objectives are obtained its fed back into another instance of osyczka2. 3) Max Walk Sat is used on this model
def _test(): dec_hi = [10, 10, 5, 6, 6, 10] dec_lo = [0, 0, 1, 0, 1, 0] dummy = Osyczka2(dec_hi, dec_lo) obj_hi, obj_lo = dummy.get_objective_extremes() model = Osyczka2(dec_hi, dec_lo, obj_hi, obj_lo) evals, best = max_walk_sat(model) print("\n") print("Evals : ", evals) print("Best : ", best) f1...
[ "def perform_ko(self, model):\n\n cfg = self.cfg\n\n \"load data\"\n if cfg.run_tal and cfg.hnisz_region == \"tal1\":\n self.cfg.get_tal1_only = True\n data_loader = self.prepare_tal1_lmo2()\n elif cfg.run_tal and cfg.hnisz_region == \"lmo2\":\n self.cfg....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return index of stat of genotype array
def get_first_genotype_index(self): return self.first_genotype_idx
[ "def gen2ind(genotype):\r\n # For example, gen2ind([1,1,1,1,1,1,1,1]) = 255\r\n i = 0\r\n index = 0\r\n mg = len(genotype)\r\n while i < mg:\r\n index += genotype[i] * (2 ** (mg - i - 1))\r\n i += 1\r\n return int(index)", "def get_gene_index(self, query):\n if len(query) > ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Varid (rsid) getter, for UKB bgen generated VCFs
def get_varid_ukb(self): varid = self.data_array[self.rsid_idx] return (varid.split(',')[0])
[ "def identifier(self):\n return self.nvd_cve['cve']['CVE_data_meta']['ID']", "def GetRNIdV(self, *args):\n return _snap.TBPGraph_GetRNIdV(self, *args)", "def getVarnode(self) -> ghidra.program.model.pcode.Varnode:\n ...", "def vios_id(self):\n return self._get_val_int(_VADPT_LOCAL_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Posn as int getter
def get_posn_as_int(self): return (int(self.data_array[self.posn_idx]))
[ "def getInt(self, columnIndex):\n pass", "def PosToInt(pos):\n if pos not in posToIntMap:\n raise Exception(\"Unrecognized part of word: \" + pos)\n return posToIntMap[pos]", "def number(self):\n if hasattr(self, 'number'):\n return self.number\n else:\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
getter for a particular value from the INFO field
def get_info_value(self, key): info = self.parse_info(self.get_info()) if key in info: return info[key] else: return None
[ "def getInformation(self, key):\n try:\n return self.information[key]\n except:\n return None", "def get_info(self, member_data):", "def get(self, field):\n return self.track[field]", "def get_company_info():\n return _get(\"info\")", "def infoInstance(self, key...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Does this VCF rec have this fmt?
def has_fmt(self, req_fmt): if req_fmt in self.get_fmts(): return True return False
[ "def is_format(part, format):\n types = ''\n for char in part:\n types += get_type(char)\n return (types == format)", "def has_format(self, format):\n for f in self.formats:\n if f==format:\n return True\n return False", "def __validate_format(format):\n\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prfx, sfx getter in other words split the data array into prefix and genotypes components
def get_prfx_sfx(self): return (self.data_array[:self.first_genotype_idx], self.data_array[self.first_genotype_idx:])
[ "def genenames_from10x(genelist):\n genesymbol=[]\n #ensemblid=[]\n for i in range(len(genelist)):\n curgene=genelist[i]\n starts=[]\n for x in re.finditer('_',curgene):\n starts.append(x.start()+1)\n genesymbol.append(curgene[starts[-1]:])\n \n return genes...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructor of measure. measurements is a collection of Measurement objects.
def __init__(self, measurements): self.measurements = measurements
[ "def measurements(self, **kwargs):", "def test_add_measure_multiple(self):\n measure_42_results = {\n 'performance_met': 0,\n 'performance_not_met': 1,\n 'eligible_population_exclusion': 2,\n 'eligible_population_exception': 0,\n 'eligible_population':...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Measure the operations done by func with a collection of measurements.
def measure(self, func, id): # Enable GC, force GC and disable GC before running test in order to reduce # the interference from GC. gc.enable() gc.collect() gc.disable() for m in self.measurements: m.start(id) func() for m in self.measureme...
[ "def timing_analysis(func, start, stop, inc, runs):\n\n for n in range(start, stop, inc): # for every input size n\n acc = 0.0 # initialize accumulator\n\n for i in range(runs): # repeat runs times:\n acc += timing(func, n) ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
plot the statistics result on raw rating data.
def plot_raw_data(ratings): # do statistics. num_items_per_user = np.array((ratings != 0).sum(axis=0)).flatten() num_users_per_item = np.array((ratings != 0).sum(axis=1).T).flatten() sorted_num_movies_per_user = np.sort(num_items_per_user)[::-1] sorted_num_users_per_movie = np.sort(num_users_per_ite...
[ "def plot_raw_data(ratings):\n # do statistics.\n num_items_per_user = np.array((ratings != 0).sum(axis=0)).flatten()\n num_users_per_item = np.array((ratings != 0).sum(axis=1).T).flatten()\n sorted_num_movies_per_user = np.sort(num_items_per_user)[::-1]\n sorted_num_users_per_movie = np.sort(num_use...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate a lower/upper lexicographic bound for the FSM.
def bound(self, lower_bound: bool, max_length: int) -> Optional[str]: bound = "" minmax = min if lower_bound else max states = self.expand_epsilons({self.start}) while (not lower_bound or self.end not in states) and len(bound) < max_length: least_char = None next_...
[ "def get_upperbound(self) -> int:", "def bounds(self, reverse):\n return self.lower, self.upper", "def get_initial_bound(self) -> int:\n return self.initialBound", "def lower_bound(self):\n return self.__lower_bound", "def constrain(amt: float, low: float, high: float) -> float:\n re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate a character class description of the given characters
def char_class(chars: str, negated: bool = False) -> str: if len(chars) == 0 and negated: return "." elif len(chars) == 1: if negated or chars in Pattern.literal_exclude: return f"[{'^'*negated}{chars}]" return chars # find runs of length 4+ ordered = sorted(set(char...
[ "def charDescriptions(self):\n \n return [self.characters[0].description(), self.characters[1].description()]", "def __initCharacterSelectors(self):\n self.__characterCategories = (\n # display name code\n (self.tr(\"Letter, Any\"), \"L\"),\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return functions for generating new state names using the given labels. Note that names are sorted alphabetically when generating FSM descriptions.
def new_states(*names: str) -> List[Callable[..., State]]: generators = [] for name in names: generators.append((lambda name: (lambda *args: (name, *args) if args else name))(name)) return generators
[ "def label_names(boys_names, girls_names, func):\n seed(2) \n labeled_names = [(name, 'male') for name in boys_names] + \\\n [(name, 'female') for name in girls_names]\n\n featuresets = [(func(x), g) for (x, g) in labeled_names]\n shuffle(featuresets) \n train_set = featuresets[...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Minimum match length (inf for no match).
def min_length(self) -> float:
[ "def _find_min(self, phrase, string):\n min_index = len(string)\n regex = self._make_re_from_phrase(phrase)\n matches = regex.finditer(string)\n for match in matches:\n min_index = min(match.start(), min_index)\n return min_index", "def set_min_len(self, l):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Maximum match length (inf for no match, inf for infinite).
def max_length(self) -> float:
[ "def longest(string, matches):\n try :return max([m for m in matches if fnmatch(string, m)], key=len)\n except: return None", "def max_length():\r\n #Finding the longest string\r\n strings\r\n global maximum\r\n maximum=0\r\n for i in strings:\r\n if len(i)>maximum:\r\n maxi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A Regex describing the first (or last) matching character.
def first_character(self, from_end: bool = False) -> "Regex":
[ "def get_first_group (match):\n return match.group(1)", "def test_returns_first_recurring_char_short_string(self):\n result = find_first_recurring_char(\"abcdagtf\")\n self.assertEqual(result, \"a\")", "def test_returns_none_if_no_recurring_chars(self):\n result = find_first_recurring_ch...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Whether one regex implies the other.
def regex_implies(a: Regex, b: Regex) -> bool: # A < B if a == b: return True # [ab] < [abc] if isinstance(a, RegexChars) and isinstance(b, RegexChars): return set(a.chars) <= set(b.chars) # [ab] < [^cd] elif isinstance(a, RegexChars) and isinstance(b, RegexNegatedChars): ...
[ "def is_regex(self):\n return True", "def is_regex(self):\n return False", "def ambiguousWith(self, other):\r\n return self.text == other.text or self.matchingAmbiguityGroup(other)", "def like(s1, s2):\n s1_normed = normalise(s1)\n for s in s2:\n if s in s1_normed:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Equivalent weight exponent value.
def weight_exp(self): return torch.ceil(torch.log2(torch.sqrt(self.running_var + self.eps)))
[ "def getWeightedValue():\n\t\tweight*value", "def power(self):\n return self.curr * self.emf", "def get_exponent(self, rbv):\n return (rbv >> self.mant_bw) & (2**self.exp_bw - 1)", "def AlbiniExponentA(self) :\n self.exponentA = 133. * math.pow(self.sigma, -0.7913)", "def exponentiate(self, b...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a new class by the given name with the given attributes and subclasses. This will validate the body and params schemas declared on a resource and raise a ValidationError if the schema is invalid.
def __new__(mcs, cls_name, superclasses, attributes): if hasattr(attributes, '__body__'): # Check that the body schema is valid try: Draft4Validator.check_schema(attributes['__body__']) except jsonschema.ValidationError: raise jsonschema.Valida...
[ "def dynamic_class_creation(name, base=object):\n # Protected name in the schema\n if name in [\n \"__schema^2__\",\n ]:\n return None\n schema_entry = aapi_schema[\"AAPI_schema\"][name]\n helper_string = _construct_docstring(schema_entry)\n atype, ptype, delimiter = _determine_type(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Replaces string based environment values with Python booleans
def bool_env(val): return True if environ.get(val, False) == 'True' else False
[ "def format_true_false(env, default=\"\"):\n content = os.environ.get(env, default)\n if content.upper() in [\"T\", \"TRUE\"]:\n os.environ[env] = \"True\"\n return True\n else:\n os.environ[env] = \"False\"\n return False", "def env_str_to_bool(var...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the values of the coordinates.
def updatePoints(self, x, y):
[ "def updateCoordinate(self, newCoord):\n self.trueBallPos = newCoord", "def update_position(self, x, y):\n self.x = x\n self.y = y", "def update_xyz(self):\n # Take the values from the corresponding spinBoxes\n goal = list()\n goal.append(self.spinx.value())\n go...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draw the rectangle for the box on the canvas.
def drawRectangle(self, canvas):
[ "def draw(self):\n #There is only one turtle, so it needs updated to display each object's stored color\n self._turtle.setColor(self._color[0],self._color[1],self._color[2])\n #Filled in rectangle\n #For all y coordinates in a square, draw a horizontal line that goes across the square\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete the box rectangle from the canvas.
def deleteRectangle(self, canvas):
[ "def del_box(self,n):\n#\t\tprint \"del \",n\n\t\tif n<0 or n>=len(self.boxes): return\n\n\t\tif self.boxviewer.get_data(): self.boxviewer.set_data(None)\n\t\tself.curbox=-1\n\t\tself.do_deletion([n])", "def _clear_canvas(self):\n self.canvas.delete(ALL)", "def remove_rectangle(self, i):\n if len(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the values of the control point coordinates.
def updatePoints(self, x, y):
[ "def update(val):\n # Determine new positions\n self.pos = self._ViewportPosition(x=x_slider_pos.val,\n y=y_slider_pos.val)\n self._set_axes_limits()\n self._redraw()", "def UpdateGrid(self):\r\n self.xx = np.outer(sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draw the rectangle for the box on the canvas.
def drawRectangle(self, canvas):
[ "def draw(self):\n #There is only one turtle, so it needs updated to display each object's stored color\n self._turtle.setColor(self._color[0],self._color[1],self._color[2])\n #Filled in rectangle\n #For all y coordinates in a square, draw a horizontal line that goes across the square\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete the box rectangle from the canvas.
def deleteRectangle(self, canvas):
[ "def del_box(self,n):\n#\t\tprint \"del \",n\n\t\tif n<0 or n>=len(self.boxes): return\n\n\t\tif self.boxviewer.get_data(): self.boxviewer.set_data(None)\n\t\tself.curbox=-1\n\t\tself.do_deletion([n])", "def _clear_canvas(self):\n self.canvas.delete(ALL)", "def remove_rectangle(self, i):\n if len(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate task callback function. It loop over internal fields, e.g. dataset, file, etc., build DAS query and requests its expiration timestamp. For scheduled queries it yields QueryMaintainer task.
def generate_task(self, item, count, epoch_start, epoch_end): only_before = epoch_end + self.interval for field in self.fields: query = {'fields': [field], 'spec':[{'key':self.key, 'value': item}], 'instance':self.instance} dasquery = DAS...
[ "def main():\n task_init(authorization_action='runinveniogc',\n authorization_msg=\"InvenioGC Task Submission\",\n help_specific_usage=\" -l, --logs\\t\\tClean old logs.\\n\" \\\n \" -p, --tempfiles\\t\\tClean old temporary files.\\n\" \\\n \" -g, --guests\\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
For multiple keys, try and identify an existing queries for wildcard supersets of the keys, and reduce the keylist appropriately. Important to note, this only uses existing queries (won't try and make new ones).
def get_superset_keys(self, keys): superset_cache = {} keys = set(keys) change_made = True while change_made: change_made = False for key in list(keys): if key in superset_cache: superset_keys = superset_cache[key] ...
[ "def matched_keys(key_path: Any, all_keys: Sequence, case_ignored: bool, space_trimmed: bool = False) -> List:\n normalized = normalize(key_path, case_ignored, space_trimmed)\n keys = [k for k in all_keys if key_matches(k, normalized, case_ignored)]\n\n if len(keys) > 1:\n logger.warning(f\"Multiple...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extract analytics apicall the expire timestamp for given query. If query is not found in DAS cache, it invokes DAS call.
def get_query_expiry(self, dasquery): err_return = time.time() + (2*self.preempt) try: if not self.das.rawcache.incache(dasquery): try: self.das.call(dasquery, add_to_analytics=False) except Exception as err: print "\n##...
[ "def _build_cache(self):\r\n self.gsuite = GsuiteQuery(self.activity, max='50')\r\n events = self.gsuite.execute()\r\n if len(events) > 0:\r\n for cnt, event in enumerate(events, 1):\r\n self.cache.update({event['id']['uniqueQualifier']:event['id']['time']})\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Basically, we confirm that a class inheriting from one of our interfaces does not inherit the property of actually being an interface.
def test_interface_typecheck_doesnt_inherit(self): class Zeroable(metaclass=TypeCheckableMeta): """In most cases, this indicates a container that can be 'empty'.""" @abstractclassmethod def zero(cls): return NotImplemented @classmethod ...
[ "def checkExpectedInterfaces(objects,expectedInterface):\r\n for obj in objects:\r\n if not expectedInterface.providedBy(obj):\r\n raise RuntimeError(\"Object %s does not implement %s interface\" % (obj,expectedInterface))", "def testInterfaceMethodRemoval(self):\n self.assertNotBackwardCo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructor for FastMTCNN class.
def __init__(self, resize=1, *args, **kwargs): self.resize = resize self.mtcnn = MTCNN(*args, **kwargs)
[ "def __init__(self, nb_classes, n_snip, opt_flow_len, image_shape = (224, 224), saved_weights=None):\n self.nb_classes = nb_classes\n self.n_snip = n_snip\n self.opt_flow_len = opt_flow_len\n self.image_shape = image_shape\n self.saved_weights = saved_weights\n\n self.input...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plot a 2d gaussian with given mean and covariance.
def plotGaussian(mean, covariance, c): import matplotlib.pyplot as plt t = numpy.arange(-numpy.pi, numpy.pi, 0.01) k = len(t) x = numpy.sin(t)[:, numpy.newaxis] y = numpy.cos(t)[:, numpy.newaxis] D, V = numpy.linalg.eigh(covariance) A = numpy.real(numpy.dot(V, numpy.diag(numpy.sqrt(D))).T)...
[ "def plot_gaussian(mean, covariance, color, zorder=0):\n plt.plot(mean[0], mean[1], color[0] + \".\", zorder=zorder)\n\n if covariance.ndim == 1:\n covariance = np.diag(covariance)\n\n radius = np.sqrt(5.991)\n eigvals, eigvecs = np.linalg.eig(covariance)\n axis = np.sqrt(eigvals) * radius\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
splits array into n_splits of potentially unequal sizes
def _split(array, n_splits): assert array.ndim == 1 n_elements = array.shape[0] remainder = n_elements % n_splits split_sizes = [] for i in range(n_splits): if i < remainder: split_sizes.append(n_elements // n_splits + 1) else: split_sizes.append(n_elements ...
[ "def split(array):\n\n split_array = []\n num = 3\n\n array.sort()\n size = int(round(len(array)/num))\n\n for i in range(0, len(array), size):\n split_array.append(array[i:i + size])\n return split_array", "def split_arr(arr):\r\n return np.split(arr, np.arange(16000, len(arr), 16000)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Perform the actual import action (after the user has confirmed he wishes to import)
def process_import(self, request, *args, **kwargs): opts = self.model._meta resource = self.get_import_resource_class()(**self.get_import_resource_kwargs(request, *args, **kwargs)) confirm_form = ConfirmImportFormWithSamples(request.POST) if confirm_form.is_valid(): import_f...
[ "def post_import(self):", "def test_do_import(self):\n user = get_user_model().objects.get(email='instructor01@bogus.com')\n wflow = Workflow.objects.get(name=self.wflow_name)\n\n with open(os.path.join(\n settings.BASE_DIR(),\n 'ontask',\n 'fixtures',\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Marks all crrently open orders as sent, unless they have no books in which case they're deleted.
def cleanup_orders(): for order in models.Order.objects.filter(status__exact='OPEN'): # Mark orders with books as sent if order.books.count(): print('Cleaning up', order) order.status = 'SENT' order.date_closed = datetime.datetime.now() order.save() # Delete orders without books ...
[ "def cancel_all_open_order(self):", "def cancel_all_open_orders(self) -> None:\n raise NotImplementedError(\"Should implement cancel_all_open_orders()\")", "def ensureOrders(self):\n if self.getFSM() == \"waiting\":\n ticker = self.dex.returnTicker()\n openOrders = self.dex.r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Lit le fichier choisi et le convertit en instance de la classe Carte
def lire_carte(self): chemin = os.path.join("cartes", self.nom_fichier_carte + "txt") with open(chemin, "r") as fichier: carte_str = fichier.read() self.carte.charger_txt_en_carte(carte_str)
[ "def __init__(self, tipo='text', fichero='agenda.txt'):\n self.tipo = tipo\n self.fichero = os.path.join(os.getcwd(), fichero)\n if not os.path.exists(self.fichero):\n print(f'Fichero {self.fichero} no existe, se creará uno nuevo.')\n creado = self._create_file()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
remove edge is directive from node_name_0 to node_name_1
def rm_edge(self, node_name_0, node_name_1): if node_name_0 in self.graph_proto.edges_out: index = -1 for idx, node_name in enumerate(self.graph_proto.edges_out[node_name_0].val): if node_name == node_name_1: index = idx break ...
[ "def remove_edge(self, node1, node2):\n node1.remove_edges(node2)", "def disconnect_node(G,node1,node2,text_id,idx):\n\tedge = G[node1][node2]\n\tedge_idx_list = edge['paths'][text_id]['word_positions']\n\tidx_pos = edge_idx_list.index(idx)\n\tedge_idx_list.pop(idx_pos)\n\tedge['weight'] -=1\n\tif not len(edge...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
add_in_edge is directive from node_name_0 to node_name_1
def add_in_edge(self, node_name_0, node_name_1): if node_name_0 not in self.graph_proto.edges_in[node_name_1].val: self.graph_proto.edges_in[node_name_1].val.append(node_name_0)
[ "def add_edge(self, node1, node2):\n node1.add_edges(node2)", "def append_edge(self, edge):", "def add_edge(self, node1, node2):\n raise NotImplementedError", "def add_edge(self, v1, v2, weight):", "def add_edge(source, target, label):\n if target not in elements_set: return\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
add_out_edge is directive from node_name_0 to node_name_1
def add_out_edge(self, node_name_0, node_name_1): if node_name_1 not in self.graph_proto.edges_out[node_name_0].val: self.graph_proto.edges_out[node_name_0].val.append(node_name_1)
[ "def add_out(self, output_node_name, in_node_name):\n nodeIO = NodeProtoIO()\n nodeIO.set_name(output_node_name)\n nodeIO.add_in(in_node_name)\n opIO = OpsProtoIO()\n opIO.set_name(\"Output\")\n nodeIO.set_op(opIO())\n self.add_out_edge(in_node_name, output_node_name...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
add output node for graph
def add_out(self, output_node_name, in_node_name): nodeIO = NodeProtoIO() nodeIO.set_name(output_node_name) nodeIO.add_in(in_node_name) opIO = OpsProtoIO() opIO.set_name("Output") nodeIO.set_op(opIO()) self.add_out_edge(in_node_name, output_node_name) self...
[ "def _add_output(self, out):\n self._outputs += [out]\n out.node = self\n out._set_as_output_of(self)", "def register_output(self, output_node_name):\r\n self._registered_output_node_names.append(output_node_name)", "def set_output(self, output_node_name):\n self.output_node_n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Replaces all nans in the given tensor with 0s
def _zero_nans(tensor): with tf.name_scope("zero_nans"): return tf.compat.v1.where_v2(tf.math.is_nan(tensor), _tf_zero, tensor, name="zero_nans_where")
[ "def remove_nans(dataset):\n return dataset.fillna(0.0)", "def zero_out(self, tensor, mask_value=-1, scope=None):\n with tf.compat.v1.variable_scope(scope, default_name='zero_out'):\n in_vocab_indicator = tf.not_equal(tensor, mask_value)\n tensor *= tf.cast(in_vocab_indicator, tensor.dtype)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }