query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Set the xmin for the mapping.
def set_xmin(self, xmin): self.__xmin = xmin
[ "def xmin(self, xmin):\n\n self._xmin = xmin", "def xmin(self):\n return self.bbox[0][0]", "def xmin(self):\n\n return self.bbox[1]", "def get_xmin(self):\n return self.__xmin", "def min_x(self, min_x):\n\n self._min_x = min_x", "def set_min(self, min):\n self.set...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the xmax for the mapping.
def set_xmax(self, xmax): self.__xmax = xmax
[ "def xmax(self, xmax):\n\n self._xmax = xmax", "def setXmax(self,x):\n #print \"setting xmax to\", x\n for i in self.l:\n i.setXmax(x)\n return self", "def setXmax(self,x):\n if sometrue(x>array(self.c.shape)-1):\n raise \"xmax is too small\"\n sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the ymin for the mapping.
def set_ymin(self, ymin): self.__ymin = ymin
[ "def ymin(self, ymin):\n\n self._ymin = ymin", "def ymin(self):\n\n return self.bbox[0]", "def get_ymin(self):\n return self.__ymin", "def set_ymax(self, ymax):\n self.__ymax = ymax", "def ymax(self, ymax):\n\n self._ymax = ymax", "def _setBound(self, value):\n if...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the ymax for the mapping.
def set_ymax(self, ymax): self.__ymax = ymax
[ "def ymax(self, ymax):\n\n self._ymax = ymax", "def ymax(self):\n\n return self.bbox[2]", "def set_ymin(self, ymin):\n self.__ymin = ymin", "def setGraphYLimits(self, ymin, ymax, axis):\n self.__yLimits[axis] = ymin, ymax", "def get_ymax(self):\n return self.__ymax", "de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the height for the mapping.
def __set_height(self, height): self._height = height
[ "def set_height(self, height: int):\n self.height = height", "def height(self, value):\n self._desired_height = value", "def set_height(height):\n resize.transforms[1].size = height", "def setHeightMap(self, x: int, z: int, value: int):\n\t\tself.heightMap[(z << 4) | x] = value", "def setHe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the xmin of the mapping.
def get_xmin(self): return self.__xmin
[ "def xmin(self):\n return self.bbox[0][0]", "def xmin(self):\n\n return self.bbox[1]", "def minX(self):\n self._updateExtents()\n return self._mMinX", "def min(self):\n return self._min_coords", "def x_min(self) -> ir.FloatingValue:\n return ops.GeoXMin(self).to_exp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the ymin of the mapping.
def get_ymin(self): return self.__ymin
[ "def ymin(self):\n\n return self.bbox[0]", "def ymax(self):\n\n return self.bbox[2]", "def ymin(self, ymin):\n\n self._ymin = ymin", "def xmin(self):\n\n return self.bbox[1]", "def xmin(self):\n return self.bbox[0][0]", "def set_ymin(self, ymin):\n self.__ymin = y...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the ymax of the mapping.
def get_ymax(self): return self.__ymax
[ "def ymax(self):\n\n return self.bbox[2]", "def ymax(self, ymax):\n\n self._ymax = ymax", "def get_ymin(self):\n return self.__ymin", "def get_y_max(self):\n if len(self._statDict) == 0:\n return -1E10\n\n line_id_list = self._statDict.keys()\n max_y = self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Map a tkinter i coordinate to an x coordinate in math scale.
def get_x(self, i): scale = (self.__xmax - self.__xmin) / (self.__width - 1) return scale * i + self.__xmin
[ "def transform_x(self,x):\n return x+self.window.width/2.0", "def unit2px(self, i, dim):\n\t\treturn (1.0/self.UNITS_PER_PIXEL_x)*i if dim=='x' else (1.0/self.UNITS_PER_PIXEL_y)*i", "def val_to_canvasx(self, val):\n canvas_x1 = self.border # left edge of rectangle\n canvas_x2 = self.width -...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Map a tkinter j coordinate to a y coordinate in math scale.
def get_y(self, j): scale = (self.__ymin - self.__ymax) / (self.__height - 1) return scale * j + self.__ymax
[ "def transform_y(self,y):\n return y+self.window.height/2.0", "def yposition(self):\n return self.zoomlevels[0].yposition", "def y(self, value: Number):\n self._translation[1, 0] = value", "def widget2imgcoords(self, x,y):\n\t\tif self._w2i_matrix is None: self._calc_matrix()\n\t\treturn self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Concatenate features tables from many results.db files.
def combine_features_tables(*paths_to_dbs): con = None con = sql.connect('combined_results.db') cur = con.cursor() # Create a table matching the schema of the 'features' tables cur.execute("CREATE TABLE combined_features(id INT PRIMARY KEY, \ resname TEXT, short_name TEXT, cc REAL, d_ref REAL, d_mid REAL...
[ "def merge_db(self, db_files, output_db, config):", "def features_to_db(db, training_dir, test_dir, label_file):\n logger.debug(\"Getting Labels\")\n labels = get_labels(label_file)\n logger.debug(\"Extracting training features\")\n train_features = extract_from_dir(training_dir)\n logger.debug(\"S...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Used to ensure a conditional operation is supported by this type. By default, uses a hardcoded table of operations that maps to each backing DynamoDB type. You can override this method to implement your own conditional operators, or to dynamically adjust which operations your type supports.
def supports_operation(self, operation: str) -> bool: return operation in OPERATION_SUPPORT_BY_TYPE[self.backing_type]
[ "def test_unsupported_op(self):\n\n NIE = NotImplementedError\n self.assertRaises(NIE, self.table.where, 'c_complex128 > 0j')\n self.assertRaises(NIE, self.table.where, 'c_string + b\"a\" > b\"abc\"')", "def optable(self,opcol_name,op,op_name) :\n opcol = self.namemap[opcol_name]\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the DynamoDB backing type from a given wire dict
def extract_backing_type(value: dict) -> str: return next(iter(value.keys()))
[ "def field_to_dynamo_type(field):\n if isinstance(field, fields.Raw):\n return 'B'\n if isinstance(field, fields.Number):\n return 'N'\n return 'S'", "def wire_type(self):\n if hasattr(self, '_m_wire_type'):\n return self._m_wire_type if hasattr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the DynamoDB backing type for a given python value's type
def backing_type_for(value): if isinstance(value, str): vtype = "S" elif isinstance(value, bytes): vtype = "B" # NOTE: numbers.Number check must come **AFTER** bool check since isinstance(True, numbers.Number) elif isinstance(value, bool): vtype = "BOO...
[ "def field_to_dynamo_type(field):\n if isinstance(field, fields.Raw):\n return 'B'\n if isinstance(field, fields.Number):\n return 'N'\n return 'S'", "def extract_backing_type(value: dict) -> str:\n return next(iter(value.keys()))", "def value_type(self) -> glob...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function inserts particles, and assigns particle velocities if requested by the user. If species is 'all', all components specified in SS are inserted. Otherwise, species must be the id of the component to be inserted.
def insert(self, species, value, **args): if not self.pddName: print('Probability distribution not set for particle insertion. Exiting ...') sys.exit() if 'region' in args: region = args['region'] else: # Default region is sim box if 'cylinder' in self.pargs: region = ...
[ "def generate_particles( self, species, dz, time ) :\n # Shortcut for the number of integer quantities\n n_int = species.n_integer_quantities\n n_float = species.n_float_quantities\n\n # Create new particle cells\n if (self.nz_inject > 0) and (species.continuous_injection == True)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Control how a mesh (specified by name) moves in time
def moveMesh(self, name, **args): randName = 'moveMesh' + str(np.random.randint(10**5,10**8)) args = dictToTuple(**args) self.lmp.command('fix {} all move/mesh mesh {} '.format(randName, name) + ('{} ' * len(args)).format(*args)) return randName
[ "def move_mesh(self, dt):\r\n # get the displacement vector from dt*u\r\n move = project(Constant(dt)*self.u, self.V)\r\n\r\n # use ALE to move the mesh.\r\n # this updates all functions defined on the mesh\r\n ALE.move(self.mesh, move)", "def mesh_change(attrname, old, new):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Imports all meshes and sets them up as walls. Can import only one mesh specified by the 'name' keyword.
def importMeshes(self, name=None): wall = False if 'mesh' in self.pargs: for mesh in self.pargs['mesh'].keys(): if 'file' in self.pargs['mesh'][mesh]: if name: if mesh == name: self.pargs['mesh'][mesh]['import'] = True self.importMesh(mes...
[ "def importMesh(self, name, file, mtype, material, **args):\n args = dictToTuple(**args)\n\n if not self.rank:\n logging.info('Importing mesh from {}'.format(file))\n\n self.lmp.command('fix {} all {} file {} type {} '.format(name, mtype, file, material) + ('{} ' * len(args)).format(*args))", "def l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Imports a specific surface mesh requested by the user
def importMesh(self, name, file, mtype, material, **args): args = dictToTuple(**args) if not self.rank: logging.info('Importing mesh from {}'.format(file)) self.lmp.command('fix {} all {} file {} type {} '.format(name, mtype, file, material) + ('{} ' * len(args)).format(*args))
[ "def import_mesh(self, scenegroup):\n logger.debug((\"mesh\", scenegroup[\"asset\"]))\n if scenegroup[\"asset\"] in self._imported_assets:\n return self._imported_assets[scenegroup[\"asset\"]]\n asset = self.gridinfo.getAsset(scenegroup[\"asset\"])\n if not asset[\"type\"] == ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Deletes a specified fix. If the fix is for a mesh, we must unfix it and reimport all meshes again and setup them up as walls. Very tedious!
def remove(self, name): # Remove any DUMP-IDS 1st in case the user wants to move a mesh if 'mesh' in self.pargs: if name in self.pargs['mesh']: # must delete all meshes / dumps in order to re-import remaining meshes for dump in self.pargs['traj']['dump_mname']: self.lmp.command('...
[ "def delete_fixed(self):\n for i, line in enumerate(self.lines):\n if line.startswith(\"fix\"):\n self.lines[i] = ''\n self._update_code_from_lines()", "def delete_bug(self,id):\n self.execute(TABELLE['bugs']['delete'],(id,))", "def removeRefsById(self,objIds,safeC...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create groups of atoms. If group is empty, groups{i} are created for every i species.
def createGroup(self, *group): if not self.rank: logging.info('Creating atom group {}'.format(group)) if not len(group): for idSS in self.pargs['idSS']: self.lmp.command('group group{} type {}'.format(idSS, idSS)) else: self.lmp.command('group ' + ('{} ' * len(group)).format(*grou...
[ "def create_groups ():\n group_list = ['Cores', 'Coords', 'Vols',]\n for group_name in group_list:\n create_group (group_name)", "def set_groups_as_molecules(self):\n molecules = list(set(self.__moleculesIndexes))\n moleculesIndexes = {}\n for idx in range(len(self.__moleculesInd...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates particles of type 'type' (1,2, ...) using style 'style' (box or region or single or random)
def createParticles(self, type, style, *args): if not self.rank: logging.info('Creating particles {} with args'.format(type) + (' {}' * len(args)).format(*args)) self.lmp.command('create_atoms {} {}'.format(type, style) + (' {}' * len(args)).format(*args))
[ "def addParticles( screen, number, color ):\n\t\n\tparticles = []\n\t\n\tfor i in range( number ):\n\t\n\t\tradius = 5\n\t\tmass = 1\n\t\t\n\t\t#random position and velocity\n\t\tx, y = randint(-WINDOW_X + radius, 1), randint(-WINDOW_Y + radius, WINDOW_Y - radius)\n\t\tvx, vy = randrange(-1, 2, 2) * 100, randrange(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This creates dumps for particles and meshes in the system. In LIGGGHTS, all meshes must be declared once, so if a mesh is removed during the simulation, this function has to be called again, usually with only_mesh=True to keep the particle dump intact.
def writeSetup(self, only_mesh=False, name=None): if not self.rank: logging.info('Setting up trajectory i/o') # Make sure the user did not request no particles be saved to a traj file, or we're not just re-initializing the meshes if not only_mesh and self.pargs['traj']['pfile']: if hasattr(sel...
[ "def create_file_empty_particles( self, fullpath, iteration,\n time, dt, select_nglobal_dict=None ):\n # Create the file (can be done by one proc or in parallel)\n f = self.open_file( fullpath,\n parallel_open=self.write_metadata_parallel )\n\n # Set...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extracts atomic positions from a certian frame and adds it to coords
def extractCoords(self): if not self.rank: logging.info('Extracting atomic poitions') # Extract coordinates from liggghts self.lmp.command('variable x atom x') x = Rxn.lmp.extract_variable("x", "group1", 1) self.lmp.command('variable y atom y') y = Rxn.lmp.extract_variable("y", "group1",...
[ "def translate_to_genomic_coords(start, end, frame, genome_size):\n nucleic_start = start * 3\n nucleic_end = end * 3\n if frame == 1:\n genomic_start = nucleic_start - 2\n genomic_end = nucleic_end - 2\n if frame == 2:\n genomic_start = nucleic_start - 1\n genomic_end = nucl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Passes a specific command to LIGGGHTS
def command(self, cmd): self.lmp.command(cmd)
[ "def command():\n pass", "def mlflow_commands():\n pass", "def on_command(server, user, command, args):", "def normal_command(self, command):\r\n\t\tself.command('normal ' + command)", "def Reply(self, command):", "def add(self, name, command):", "def _mod_command_handler(self, cmd, args):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fill Matrix with numbers in ascending order. On clock direction.
def on_clock_spirral_matrix(Matrix, size): x, y = 0, 0 dx, dy = 1, 0 nx, ny = 0, 0 for i in range(1, size ** 2 + 1): Matrix[x][y] = i nx, ny = x + dx, y + dy if (0 <= nx < size and 0 <= ny < size and not Matrix[nx][ny]): x, y = nx, ny else: dx, dy = -dy, dx x, y = x + dx, y + dy
[ "def fillMatrix(self, data):\r\n i = 0\r\n length = len(data)\r\n for r in range(self.rows):\r\n for c in range(self.columns):\r\n if i >= length:\r\n num = 0\r\n else:\r\n num = data[i]\r\n self.mat[r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Testing snail func that returns a snail list from matrix. (nonclock direction)
def test_snail(): print(test_snail.__doc__) size = 3 matrix = init_matrix(size) non_clock_spirral_matrix(matrix, size) print_matrix(matrix) print("Result:", *new_way_snail(matrix))
[ "def snail(array):\n a = []\n # while there are still elements in the array\n while array:\n # get the entire first row\n a.extend(list(array.pop(0)))\n # match the nested list with its counterparts, meaning [[1,2], becomes [[1,3],\n # ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
List other available variants for given config/datataset >>> pidgen = PidGen ( ... ) >>> variants = pidgen.variants ()
def variants ( self ) : vars = [] items = [ 'distrib' , 'default' ] items += [ 'stat_%s' % d for d in range ( 10 ) ] items += [ 'syst_%s' % d for d in range ( 10 ) ] from ostap.core.core import rootError from ostap.logger.logger import logFatal ...
[ "def get_variants(self):\n return self.cfg.variants.copy()", "def variants(self):\n url = '/api/v1/variants?filter[product_version_id]=%s' % self.id\n result = self._get(url)['data']\n variants = []\n for variant in result:\n variant_name = variant['attributes...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The function to add resampled variable into TTree/TChain `tree` input `ROOT.TTree/TChain` to be updated `pidgen` configured `PidGen` object `newpid` the name of new resampled PID variable `seed` the seed for `ROOT.gRandom` `silent` silent processing? >>> pidgen = PidGen ( ... ) configure PidGenObject >>> tree = .... >>...
def runPidGen ( tree , ## initial tree/chain to be updated pidgen , ## PidGen object newpid , ## name of new PID variable seed = None , ## random seed silent = False , ## silent ? variants...
[ "def set_seed(seed):\n return _graph_sampler.set_seed(seed)", "def update_generation(self, new_p=None, new_q=None):\n if new_p is not None:\n self.net.gen.p_kw = new_p\n if new_q is not None:\n self.net.gen.q_kvar = new_q", "def RandomModify(digraph): \n nodes = set(dig...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
" Method which adds a squad to the army via the GUI
def AddSquad(self): if self.squad.squad_type == "Troop": self.parent._army.AddTroop(self.squad) if self.squad.squad_type == "HQ": self.parent._army.AddHq(self.squad) if self.squad.squad_type == "Elite": self.parent._army.AddElite(self.squad) if self...
[ "def FillSquad(self):\n unitName = \"\"\n if isinstance(self.squad, squad.Squad):\n unitName = list(self.squad.additional_units.keys())[0]\n while self.squad.current_size < self.squad.max_size:\n self.squad.addUnit(unitName)\n self.addButton\n self.exportButt...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
" Method where the squad is filled with units that are possible to add to the squad
def FillSquad(self): unitName = "" if isinstance(self.squad, squad.Squad): unitName = list(self.squad.additional_units.keys())[0] while self.squad.current_size < self.squad.max_size: self.squad.addUnit(unitName) self.addButton self.exportButton sel...
[ "def AddUnit(self):\n unitName = \"\"\n if isinstance(self.squad, squad.Squad):\n unitName = list(self.squad.additional_units.keys())[0]\n self.squad.addUnit(unitName)\n self.addButton\n self.exportButton\n self.pointLabel['text'] = self.squad.point_cost\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
" Method which adds unit to the squad via GUI
def AddUnit(self): unitName = "" if isinstance(self.squad, squad.Squad): unitName = list(self.squad.additional_units.keys())[0] self.squad.addUnit(unitName) self.addButton self.exportButton self.pointLabel['text'] = self.squad.point_cost self.sizeLabel...
[ "def FillSquad(self):\n unitName = \"\"\n if isinstance(self.squad, squad.Squad):\n unitName = list(self.squad.additional_units.keys())[0]\n while self.squad.current_size < self.squad.max_size:\n self.squad.addUnit(unitName)\n self.addButton\n self.exportButt...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
" Method to upgrade the ranged weapons of a squad
def UpgradeWeapon(self): label = self.wepSpin.get() for index in range(min(self.squad.current_size, self.unitToWeap[label][1])): upgradedUnit = next(x for x in self.squad.units if x.name == self.unitToWeap[label][3]) upgradedUnit.armRangedWeapon(weapon.ranged_weapons[self.unitToW...
[ "def update_weapon(self, weapon):\n self.weapon = weapon\n self.weapon_strength = strength_dictionary[self.weapon]\n self.attack_power = round(float(self.weapon_strength * (1 + (self.level - 1) / 10)), 1)", "def updateWeapons(self):\n self.readyWeapons = []\n self.setWeaponStatu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that Client object fails properly
def test_vogeler_client_failure(self): with self.assertRaises(Exception): VogelerClient(callback_function=self.echo, role='client', dsn=self.bad_amqp_dsn)
[ "def test_call_with_unsupported_client(self):\n with self.assertRaises(ValueError):\n client('Non existing client')", "def test_client_connection_fail(self):\n with pilight_daemon.PilightDaemon():\n with self.assertRaises(IOError):\n pilight.Client(host='8.8.8.8'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that client can send durable messages
def test_client_message_durable(self): test_message = 'this is a test' c = VogelerClient(callback_function=self.echo, role='client', dsn=self.good_amqp_dsn) self.assertIsNone(c.message(test_message)) c.close()
[ "def test_client_message_nondurable(self):\n test_message = 'this is a test'\n c = VogelerClient(callback_function=self.echo, role='client', dsn=self.good_amqp_dsn)\n self.assertIsNone(c.message(test_message, durable=False))\n c.close()", "def test_runner_message_durable(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that client can send nondurable messages
def test_client_message_nondurable(self): test_message = 'this is a test' c = VogelerClient(callback_function=self.echo, role='client', dsn=self.good_amqp_dsn) self.assertIsNone(c.message(test_message, durable=False)) c.close()
[ "def test_client_message_durable(self):\n test_message = 'this is a test'\n c = VogelerClient(callback_function=self.echo, role='client', dsn=self.good_amqp_dsn)\n self.assertIsNone(c.message(test_message))\n c.close()", "def test_runner_message_nondurable(self):\n test_message ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that client callbacks work
def test_client_callback(self): sample_text = 'this is a test' message_body = json.dumps(sample_text) test_message = message.SampleMessage(message_body) c = VogelerClient(callback_function=None, role='client', host='localhost', ...
[ "def test_callbacks_are_invoked_with_connections(self):\n client_calls = []\n server_calls = []\n\n def client_callback(conn, *args, **kwargs):\n client_calls.append(conn)\n return True\n\n def server_callback(conn, *args, **kwargs):\n server_calls.append...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test set of protocol ids updated.
def test_protocols_updated(self): assert self.agent_config.protocols == {self.new_protocol_id}
[ "def test_protocols_updated(self):\n assert self.skill_config.protocols == {self.new_protocol_id}", "def test_restricted_to_protocols_updated(self):\n assert self.connection_config.restricted_to_protocols == {self.new_protocol_id}", "def test_excluded_protocols_updated(self):\n assert self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test set of contract ids updated.
def test_contracts_updated(self): assert self.agent_config.contracts == {self.new_contract_id}
[ "def test_contracts_updated(self):\n assert self.skill_config.contracts == {self.new_contract_id}", "def test_update_contract_status(self):\n pass", "def test_update_list(self):\n pass", "def test_recalculate_contract_prices(self):\n inv_item = fake_inventory_item()\n price_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test set of connection ids updated.
def test_connections_updated(self): assert self.agent_config.connections == {self.new_connection_id}
[ "def test_connections_updated(self):\n assert self.connection_config.connections == {self.new_connection_id}", "def test_connections(self) -> None:\n for server in self.servers:\n server.verify_connected()", "def test_default_connection_updated(self):\n assert self.agent_config.d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test set of skill ids updated.
def test_skills_updated(self): assert self.agent_config.skills == {self.new_skill_id}
[ "def test_skills_updated(self):\n assert self.skill_config.skills == {self.new_skill_id}", "def update_emp_skill(self):\n new_skill = {'skill_ids': [(4, 10), (4, 20)]}\n self.write(new_skill)", "def skills(self, new_skills):\n self._skills = new_skills", "def test_multiple_skill_re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test default connection updated.
def test_default_connection_updated(self): assert self.agent_config.default_connection == self.new_connection_id
[ "def test_connections_updated(self):\n assert self.connection_config.connections == {self.new_connection_id}", "def test_connections_updated(self):\n assert self.agent_config.connections == {self.new_connection_id}", "def test_update_connector(self):\n pass", "def test_update_bank_connect...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test default routing updated.
def test_default_routing_updated(self): assert self.agent_config.default_routing == { self.new_protocol_id: self.new_connection_id }
[ "def test_update_route(self):\n pass", "def test_set_route(self):\n pass", "def test_default_routing_updated_correctly(self):\n result = self.run_cli_command(\n \"--skip-consistency-check\",\n \"config\",\n \"get\",\n \"agent.default_routing\",\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test set of connection ids updated.
def test_connections_updated(self): assert self.connection_config.connections == {self.new_connection_id}
[ "def test_connections_updated(self):\n assert self.agent_config.connections == {self.new_connection_id}", "def test_connections(self) -> None:\n for server in self.servers:\n server.verify_connected()", "def test_default_connection_updated(self):\n assert self.agent_config.defaul...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test restricted to protocols updated.
def test_restricted_to_protocols_updated(self): assert self.connection_config.restricted_to_protocols == {self.new_protocol_id}
[ "def test_protocols_updated(self):\n assert self.agent_config.protocols == {self.new_protocol_id}", "def test_protocols_updated(self):\n assert self.skill_config.protocols == {self.new_protocol_id}", "def test_excluded_protocols_updated(self):\n assert self.connection_config.excluded_protoc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test excluded protocols updated.
def test_excluded_protocols_updated(self): assert self.connection_config.excluded_protocols == {self.new_protocol_id}
[ "def test_restricted_to_protocols_updated(self):\n assert self.connection_config.restricted_to_protocols == {self.new_protocol_id}", "def test_protocols_updated(self):\n assert self.agent_config.protocols == {self.new_protocol_id}", "def test_protocols_updated(self):\n assert self.skill_con...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test set of protocol ids updated.
def test_protocols_updated(self): assert self.skill_config.protocols == {self.new_protocol_id}
[ "def test_protocols_updated(self):\n assert self.agent_config.protocols == {self.new_protocol_id}", "def test_restricted_to_protocols_updated(self):\n assert self.connection_config.restricted_to_protocols == {self.new_protocol_id}", "def test_excluded_protocols_updated(self):\n assert self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test set of contract ids updated.
def test_contracts_updated(self): assert self.skill_config.contracts == {self.new_contract_id}
[ "def test_contracts_updated(self):\n assert self.agent_config.contracts == {self.new_contract_id}", "def test_update_contract_status(self):\n pass", "def test_update_list(self):\n pass", "def test_recalculate_contract_prices(self):\n inv_item = fake_inventory_item()\n price_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test set of skill ids updated.
def test_skills_updated(self): assert self.skill_config.skills == {self.new_skill_id}
[ "def test_skills_updated(self):\n assert self.agent_config.skills == {self.new_skill_id}", "def update_emp_skill(self):\n new_skill = {'skill_ids': [(4, 10), (4, 20)]}\n self.write(new_skill)", "def skills(self, new_skills):\n self._skills = new_skills", "def test_multiple_skill_re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Project CRUD check for signed in account. Check if a signed in account has a specified action for a given project. action, valid values ["list", "administer", "create", "read", "update", "delete"] project (optional) bool Call as app.access('project', action='update', project=PROJECT)
def permission_project(action=None, project=None, account=None): from models.project import Project from helpers.project import ProjectHelper if not action: raise Exception('Project CRUD permission: action missing') if not account or not account.id: account=g.account if not project and not ac...
[ "def test_returns_all_projects_that_user_is_permitted_if_action_set_to_any(self):\n # Arrange\n self.test_project_2.private = False\n # Since test_author is BEGINNER, they can only map projects with mapping permission ANY.\n self.test_project_1.mapping_permission = MappingPermission.ANY....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Accounts' membership check for signed in account. Check if a signed in account is permitted to see the given account's membership projects. account bool Call as app.access('membership', account=ACCOUNT)
def permission_membership(account=None): if not account: raise Exception('Membership permission: account missing') if account.id == g.account.id: return app.access('profile', action='read', account=account) else: return app.access('profile', action='read', account=account) and app.access('project',...
[ "def has_permission(self, request, view):\n\n try:\n Membership.objects.get(\n user = request.user,\n circle = view.circle,\n is_active = True\n )\n except Membership.DoesNotExist:\n return False\n return True", "de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the internal module list to reflect the state of files on disk
def refresh(self): self.modules.clear() module_files = [] module_paths = os.environ['MAYA_MODULE_PATH'].split(os.pathsep) for p in module_paths: try: module_files += [os.path.join(p, x).replace(os.sep, os.altsep or os.sep) for x in os.listdir(p) if ...
[ "def _update_mod_list(self):\n # Build the simplified object for json output\n mod_list_output = {}\n mod_list_output['mods'] = []\n for mod, data in self.mods.items():\n mod_entry = {}\n mod_entry['name'] = mod\n mod_entry['enabled'] = True\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Yields a modtuple describing the supplied .mod file
def parse_mod(self, modfile): with open(modfile, 'rt') as filehandle: for line in filehandle: if line.startswith(("+", "-")): enable, name, version, path = self.parse_mod_entry(line) yield ModTuple(enable == "+", name, version, path, modfile)
[ "def get_package_module_pairs():\n sets = []\n for filepath in glob.iglob('app/mod_cmd/commands/**/*.py'):\n pair = __yield_from_filepath(filepath)\n if pair is not None:\n yield pair", "def get_base_package_module_pairs():\n sets = []\n for filepath in glob.iglob('app/mod_cmd...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parses a line from a mod file describing a given mod
def parse_mod_entry(self, line): split_line = line.split(' ') enable = split_line.pop(0) path = split_line.pop() version = split_line.pop() name = split_line.pop() return enable, name, version, path
[ "def parse_mod(self, modfile):\n with open(modfile, 'rt') as filehandle:\n for line in filehandle:\n if line.startswith((\"+\", \"-\")):\n enable, name, version, path = self.parse_mod_entry(line)\n yield ModTuple(enable == \"+\", name, version, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a CartOriginator object and instantiate the class data fields.
def __init__(self): self._state: CartState = None
[ "def __init__(self, cart, pricing_service):\n self.cart = cart\n self.pricing_service = pricing_service", "def __init__(self, request):\n # storage of current session making it accessible to other method of cart class\n self.session = request.session\n\n # getting cart from curr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a CartMemento object using the current state.
def create_memento(self) -> CartMemento: memento = CartMemento() memento.set_state(self._state) return memento
[ "def create_from_cart(self, cart, request):\n cart.update(request)\n order = self.model(customer=cart.customer, currency=cart.total.currency,\n _subtotal=Decimal(0), _total=Decimal(0), stored_request=self.stored_request(request))\n order.get_or_assign_number()\n order.save()\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write BGF ATOM/HETATM line and CONECT info. Returns
def writeline(self): if self.record == 'ATOM' and not self.atom.startswith('H') and len(self.atom) < 4: atom = ' {0}'.format(self.atom) else: atom = self.atom aline = ( "{0:6s} {1:5d} {2:5s} {3} {4}{5:5d} {6:10.5f}{7:10.5f}" "{8:10.5f} {9:5s}{10:3d...
[ "def writeHeader(cls, f):\n s = []\n s.append(\"# global color=green dashlist=8 3 width=1 font=\\\"helvetica 8 normal roman\\\" select=1 highlite=1 dash=0 fixed=0 edit=1 move=1 delete=1 include=1 source=1\")\n s.append(\"fk5\")\n f.write('\\n'.join(s) + \"\\n\")", "def writerc(self):\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a new BGFFile object from a file. Parses BGF file header and RECORD lines. Parameter
def from_file(cls, filename): biogrf = '' ff = '' descrp = '' atoms = {} with open(filename) as f: for line in f: if line.startswith('BIOGRF'): biogrf = line.strip().split()[1] elif line.startswith('DESCRP'): ...
[ "def load(cls, file: str):\n\n bfh = cls()\n\n with open(file, 'br') as sgy:\n # get the endian\n endian = gfunc.grab_endiannes(sgy)\n\n # skip the TFH, read the BFH bytes\n sgy.seek(3200)\n raw = sgy.read(400)\n\n # unpack and store the va...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create PDBFile object. Returns
def to_pdb(self): pdb_atoms = [] for _atom in self.atoms: record = _atom.record natom = _atom.natom atom = _atom.atom altloc = '' res = _atom.res chain = _atom.chain nres = _atom.nres icode = '' x...
[ "def to_pdb(self, output_file=None):\n from csb.bio.io.wwpdb import PDBFileBuilder\n \n temp = csb.io.MemoryStream()\n builder = PDBFileBuilder(temp)\n \n builder.add_header(self)\n builder.add_structure(self)\n builder.finalize()\n \n da...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write object contents as a PDB file.
def write_pdb(self, filename): pdb = self.to_pdb() pdb.write_pdb(filename)
[ "def to_pdb_file(self, pdb_path: str) -> None:\n with open(pdb_path, \"w\", encoding=\"utf-8\") as pdb_file:\n pdb_file.write(self.to_pdb_block())", "def writePDB(self, path):\n self.pdb.writePDB(path)", "def writepdb(self,fname):\n pdbfile = open(fname + \".pdb\", \"w\")\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Instanties the appropriate GNN message passing model from the provided configuration.
def gnn_model_construct(cfg, model_name='gnn_model', **kwargs): models = gnn_model_dict() model_cfg = cfg[model_name] name = model_cfg.get('name', 'meta') if not name in models: raise Exception("Unknown GNN message passing model name provided:", name) return models[name](model_cfg, **kwargs...
[ "def new_model_from_config(cfg: omegaconf.DictConfig):\n\n dict_cfg = omegaconf.OmegaConf.to_container(cfg, resolve=True)\n args = {\n \"batch_size\": cfg.training.batch_size,\n \"learning_rate\": cfg.training.learning_rate,\n **dict_cfg[\"model\"],\n **dict_cfg[\"data\"],\n }\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Instanties the appropriate node encoder from the provided configuration.
def node_encoder_construct(cfg, model_name='node_encoder', **kwargs): encoders = node_encoder_dict() encoder_cfg = cfg[model_name] name = encoder_cfg.get('name', 'geo') if not name in encoders: raise Exception("Unknown node encoder name provided:", name) return encoders[name](encoder_cfg, *...
[ "def register_node_encoder(key, module):\n register(key, module, node_encoder_dict)", "def registerEncoder (encoder):\n assert False, \"TODO:\"", "def register_edge_encoder(key, module):\n register(key, module, edge_encoder_dict)", "def node_encoder_dict():\n\n from .encoders import geometric, mix...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Instanties the appropriate edge encoder from the provided configuration.
def edge_encoder_construct(cfg, model_name='edge_encoder', **kwargs): encoders = edge_encoder_dict() encoder_cfg = cfg[model_name] name = encoder_cfg.get('name', 'geo') if not name in encoders: raise Exception("Unknown edge encoder name provided:", name) return encoders[name](encoder_cfg, *...
[ "def edge_encoder_dict():\n\n from .encoders import geometric, mixed\n from mlreco.models.layers.gnn.encoders.cnn import ClustCNNMinkEdgeEncoder\n # from mlreco.models.scn.gnn.encoders.cnn import ClustCNNEdgeEncoder\n\n encoders = {\n \"geo\" : geometric.ClustGeoEdgeEncoder,\n \"mix_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Instanties the appropriate node loss from the provided configuration.
def node_loss_construct(cfg, model_name='node_loss', **kwargs): losses = node_loss_dict() loss_cfg = cfg[model_name] name = loss_cfg.get('name', 'type') if not name in losses: raise Exception("Unknown node loss name provided:", name) return losses[name](loss_cfg, **kwargs)
[ "def from_config(cls, loss_config: AttrDict):\n return cls(loss_config)", "def loss_creator(config):\n return torch.nn.BCELoss()", "def build_loss(loss_type: str, hyper_params: DictConfig, use_cuda: bool) -> Loss:\n loss_cfg = DictConfig(dict())\n loss_cfg[\"class\"] = loss_type\n loss_cfg[\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Instanties the appropriate edge loss from the provided configuration.
def edge_loss_construct(cfg, model_name='edge_loss', **kwargs): losses = edge_loss_dict() loss_cfg = cfg[model_name] name = loss_cfg.get('name', 'channel') if not name in losses: raise Exception("Unknown edge loss name provided:", name) return losses[name](loss_cfg, **kwargs)
[ "def from_config(cls, loss_config: AttrDict):\n return cls(loss_config)", "def node_loss_construct(cfg, model_name='node_loss', **kwargs):\n losses = node_loss_dict()\n loss_cfg = cfg[model_name]\n name = loss_cfg.get('name', 'type')\n if not name in losses:\n raise Exception(\"Unknown n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Imports and returns dictionary of valid GNN message passing models.
def gnn_model_dict(): from .message_passing import agnnconv, econv, gatconv, meta, nnconv, nnconv_elu, nnconv_old models = { "agnnconv" : agnnconv.AGNNConvModel, "econv" : econv.EConvModel, "gatconv" : gatconv.GATConvModel, "nnconv" : nnconv.NNConvMode...
[ "def gnn_model_construct(cfg, model_name='gnn_model', **kwargs):\n models = gnn_model_dict()\n model_cfg = cfg[model_name]\n name = model_cfg.get('name', 'meta')\n if not name in models:\n raise Exception(\"Unknown GNN message passing model name provided:\", name)\n\n return models[name](model...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Imports and returns dictionary of valid node encoders.
def node_encoder_dict(): from .encoders import geometric, mixed from mlreco.models.layers.gnn.encoders.cnn import ClustCNNMinkNodeEncoder # from mlreco.models.scn.gnn.encoders.cnn import ClustCNNNodeEncoder encoders = { "geo" : geometric.ClustGeoNodeEncoder, "mix_debug" : mixed.C...
[ "def load_encoders():\n\n encoders = {}\n\n # Pclass\n pclass_encoder = LabelBinarizer()\n\n with open(os.path.join('encoders', 'pclass_encoder.json'),\n 'r', encoding='utf8', errors='ignore') as infile:\n pclass_encoder.classes_ = json.load(infile)\n encoders['pclass_encoder'] = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Imports and returns dictionary of valid edge encoders.
def edge_encoder_dict(): from .encoders import geometric, mixed from mlreco.models.layers.gnn.encoders.cnn import ClustCNNMinkEdgeEncoder # from mlreco.models.scn.gnn.encoders.cnn import ClustCNNEdgeEncoder encoders = { "geo" : geometric.ClustGeoEdgeEncoder, "mix_debug" : mixed.C...
[ "def load_encoders():\n\n encoders = {}\n\n # Unnamed: 0\n unnamed_0_encoder = LabelBinarizer()\n unnamed_0_encoder.classes_ = list(range(4))\n\n with open(os.path.join('encoders', 'unnamed_0_bins.json'),\n 'r', encoding='utf8', errors='ignore') as infile:\n unnamed_0_bins = json....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Imports and returns dictionary of valid node losses.
def node_loss_dict(): from .losses import node_kinematics, node_primary, node_type losses = { "kinematics" : node_kinematics.NodeKinematicsLoss, "kinematics_edl" : node_kinematics.NodeEvidentialKinematicsLoss, "kinematics_attn": node_kinematics.NodeTransformerLoss, "primary...
[ "def _get_losses(self):\n # Fast-path already loaded\n if self.__losses is not None:\n return self.__losses\n # Initialize the dictionary\n self.__losses = dict()\n # Simply populate this dictionary\n for name in dir(torch.nn.modules.loss):\n if len(name) < 5 or name[0] == \"_\" or name[...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Imports and returns dictionary of valid edge losses.
def edge_loss_dict(): from .losses import edge_channel losses = { "channel" : edge_channel.EdgeChannelLoss } return losses
[ "def node_loss_dict():\n\n from .losses import node_kinematics, node_primary, node_type\n\n losses = {\n \"kinematics\" : node_kinematics.NodeKinematicsLoss,\n \"kinematics_edl\" : node_kinematics.NodeEvidentialKinematicsLoss,\n \"kinematics_attn\": node_kinematics.NodeTransformerLoss...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests if the default login works.
def default_login_works(self): return True if self.default_login_auth_header else False
[ "def test_authenticate_non_existing_user(self):\n self.assertFalse(self.client.login(username=\"non\", password=\"existing\"))", "def is_correct_user(self, login, password):\n pass", "def test_user_can_login(self):\n user = authenticate(username='Marry', password='secret')\n self.ass...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test if the configured admin account can authenticate. If not create it. Also test if the default bootstrap user exists and if so delete it.
def check_login(self): admin_exists = self.set_auth_header() if self.default_login_works: self.log.info("default login worked, removing it") if admin_exists: self.log.info("admin user exists, only deleting default user") else: # Since ...
[ "def test_create_if_not_exists(self, db):\n admin = User.query.filter(User.username=='admin%local').first()\n if admin:\n db.session.delete(admin)\n db.session.commit()\n # no admin user exists anymore\n\n establish_admin_defaults()\n admin = User.query.filte...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return all next states
def get_next_states(self): return self.__next_state
[ "def get_next_states(self, state, action):\n pass", "def findLegalNextStates(self):\n raise Exception(\"Must be implemented\")", "def next_state(self):\n\n\t\tfor s in self._STATE:\n\t\t\tif self._DEBUG >= 4:\n\t\t\t\tprint(s)\n\t\t\tyield s", "def generate_states(self, current_state, no=10):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Download and install libgit2 which is required for pygit2 to successfully install.
def install_libgit2(project, logger): logger.info('Installing libgit2') cmd = """cd {0} export LIBGIT2=$VIRTUAL_ENV wget --no-clobber https://github.com/libgit2/libgit2/archive/v0.27.0.tar.gz tar xzf v0.27.0.tar.gz cd libgit2-0.27.0/ cmake . -DCMAKE_INSTALL_PREFIX=$LIBGIT...
[ "def install_pygit2(project, logger):\n logger.info('Installing pygit2')\n run(project, logger, 'install_pygit2',\n \"\"\"export LDFLAGS=\"-Wl,-rpath=$VIRTUAL_ENV/lib,--enable-new-dtags $LDFLAGS\"\n pip install pygit2\n \"\"\")", "def install_git():\n git_version = sudo(GET_GIT_VERSI...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Install the pygit2 library using pip and setting installation environment variables.
def install_pygit2(project, logger): logger.info('Installing pygit2') run(project, logger, 'install_pygit2', """export LDFLAGS="-Wl,-rpath=$VIRTUAL_ENV/lib,--enable-new-dtags $LDFLAGS" pip install pygit2 """)
[ "def install_git():\n git_version = sudo(GET_GIT_VERSION)\n if git_version != GIT_VERSION:\n git_file = 'git-%s' % GIT_VERSION\n sudo('apt-get -y -qq install build-essential')\n sudo('apt-get -y -qq install git-core')\n sudo('apt-get -y -qq install libcurl4-gnutls-dev')\n su...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run a command in a shell during a PyBuilder task saving the stdout and stderr to log files. If the command has a nonzero return code then this method raises an exception.
def run(project, logger, cmd_name, command): dir_logs = project.expand('$dir_logs') pybuilder.utils.mkdir(dir_logs) out_file = os.path.join(dir_logs, '{0}.log'.format(cmd_name)) err_file = os.path.join(dir_logs, '{0}.err'.format(cmd_name)) with open(out_file, 'w') as out: with open(err_file,...
[ "def run_cmd(cmd_str, output_log_file = 'output.log',\n error_log_file = 'error.log'):\n print \"-\"*100\n print \"Running Shell Command: \\n\"\n print cmd_str\n o_log = open(output_log_file, 'w')\n e_log = open(error_log_file, 'w')\n process_returncode = subprocess.call(cmd_str, stdout...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create one hot encording for col with categorical values
def one_hot_encode(df, col): return pd.get_dummies(df, columns=[col], drop_first=True)
[ "def one_hot_encode(df, col):\n\n df_final = pd.get_dummies(data=df, columns=col, drop_first=True)\n\n return(df_final)", "def one_hot(df, cols):\n for each in cols:\n dummies = pd.get_dummies(df[each], prefix=each, drop_first=False)\n df = pd.concat([df, dummies], axis=1)\n return df", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prepare message for sending.
def prepare_message(self, message_data, delivery_mode, content_type, content_encoding, **kwargs): return (message_data, content_type, content_encoding)
[ "def prepare_message(self, message_data, delivery_mode, **kwargs):\r\n return message_data", "def __save_prep_msg(self, prep):\n msg = PreprocessedMessage()\n msg.msg_id = prep['id']\n msg.threadId = prep['threadId']\n for recipient in prep['to']:\n msg.to.append(reci...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Testing make_readable function Write a function, which takes a nonnegative integer (seconds) as input and returns the time in a humanreadable
def test_make_readable(self): allure.dynamic.title("Testing make_readable function") allure.dynamic.severity(allure.severity_level.NORMAL) allure.dynamic.description_html('<h3>Codewars badge:</h3>' '<img src="https://www.codewars.com/users/myFirstCode' ...
[ "def test_get_human_readable_duration():\n\n human_readable = common.get_human_readable_duration(-1)\n assert human_readable == '0 seconds'\n\n human_readable = common.get_human_readable_duration(10)\n assert human_readable == '10 seconds'\n\n human_readable = common.get_human_readable_duration(1000)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compare two SIAF files and write a difference file. Generate comparison figures showing the apertures if specified.
def compare_siaf(comparison_siaf_input, fractional_tolerance=1e-4, reference_siaf_input=None, report_file=None, report_dir=None, verbose=True, make_figures=False, selected_aperture_name=None, ignore_attributes=None, tags=None): if verbose: print(comparison_siaf_input) c...
[ "def f_compare(file1, file2, pair_report, language_par = 'xx'):\n compfilename = os.path.basename(file1.name)\n\n text1 = file1.readlines()\n text2 = file2.readlines()\n outputfile = open(pair_report, 'wb')\n filecounter1, filecounter2, linecounter, qmcounter, qmcounter2, diffcounter = 0, 0, 0, 0, 0,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compare two dictionaries and return keys of the differing items.
def dict_compare(dictionary_1, dictionary_2): d1_keys = set(dictionary_1.keys()) d2_keys = set(dictionary_2.keys()) intersect_keys = d1_keys.intersection(d2_keys) added = d1_keys - d2_keys removed = d2_keys - d1_keys modified = {o: (dictionary_1[o], dictionary_2[o]) for o in intersect_keys ...
[ "def compare_dicts(first: Dict[str, str], second: Dict[str, str]) -> Diff:\n diff: Diff = []\n for key, _ in sorted(first.items()):\n if key not in second:\n diff.append((key, first[key], None))\n\n for key, _ in sorted(second.items()):\n if key not in first:\n diff.appe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Configures a new cloud connector and authenticates the cloud user.
def configure_connector(provider): logging.getLogger("root").info("Configuring the cloud connector") if provider['name'] == "~okeanos" or provider['name'] == "okeanos": connector = OkeanosConnector() connector.configure(provider) return connector else: raise NotImplemented("T...
[ "def configure_cloud(self):\n \n # if API check fails, log error output - actually probably not since we have interactivity here\n again = True\n while again:\n # print info\n print(\"Welcome to the cloud configuration center.\\n\")\n print(\"Here you can...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method loads the state file and create a deployment object and a cloud connector.
def load_state_file(statefile_path): logging.getLogger("root").info("Loading state file") f = open(statefile_path, 'r') json_content = f.read() f.close() state = json.loads(json_content) cloud_connector = configure_connector(state['provider']) deployment = Deployment() deployment.deseria...
[ "def deploy(statemachine_file):\n try:\n sm = StateMachine.string(json.loads(statemachine_file.read()))\n except Exception as e:\n click.echo(click.style(\"Error: \", fg='red', bold=True) + \"{}\".format(repr(e)))\n return\n\n click.echo(click.style(\"Ok: \", fg='green', bold=True) + \...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save the statefile of the deployment to the specified path
def save_state_file(deployment, description, statefile_path, indent=2): logging.getLogger("root").info("Saving state file") dictionary = dict() dictionary['deployment'] = deployment.serialize() dictionary['provider'] = description['provider'] json_content = json.dumps(dictionary, indent=indent) ...
[ "def save_state(self):\n state_dir = path.dirname(self.state_filename)\n\n if not path.isdir(state_dir):\n os.makedirs(state_dir)\n\n with open(self.state_filename, 'w') as df:\n log.debug(\"Saving state of program %s to %s\" % (self.name, self.state_filename))\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
HTTP POST request to the specified resource and return the dictionary data. Exit if there is an error.
def post_resource(**kwargs) -> dict: response = requests.post(**kwargs) print(f"HTTP {response.request.method}: {response.url}") print(f'HTTP Status code: {response.status_code}') # Raise an exception if the response is not OK if not response.ok: print(response.text) response.raise...
[ "def post(self):\n data = request.json\n create_entry(data)\n return None, 201", "def post_resource_index():\n\n content_type = 'application/octet-stream'\n if request.headers.get('Content-type'):\n content_type, _ = parse_header(request.headers['Content-type'])\n\n # First, s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
check that other subscriber using the same s_tag don't have the same c_tag
def _test_validate_c_tag_on_same_s_tag(self): s = Mock() s.id = 123 s.c_tag = 111 s.s_tag = 222 s.onu_device = "BRCM1234" with self.assertRaises(Exception) as e: self.rcord_subscriber.save() self.assertEqual(e.exception.message, "The c_tag you specif...
[ "def test_no_duplicate_tag(driver):\n for i,rs in enumerate(driver.find_elements_by_class_name('receipt')):\n l = list(get_tags(rs))\n if len(l) != len(set(l)):\n print(\"There are duplicate tags in the {}-th receipt line\"\\\n .format(i))\n print(\"Found tag:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates a dojo datagrid for a given app's model. i.e. {% simple_datagrid myapp mymodel %}
def simple_datagrid(parser, token): bits = token.split_contents() if len(bits) < 3: raise TemplateSyntaxError("You have to pass app- and model-name to {% simple_datagrid app model %}") return DatagridNode(bits[1],bits[2],None)
[ "def datagrid(parser, token):\n bits = token.split_contents()\n nodelist = parser.parse(('enddatagrid',))\n parser.delete_first_token()\n app, model = None, None\n if len(bits) == 3:\n app = bits[1]\n model = bits[2]\n return DatagridNode(app, model,nodelist)", "def DataModel():\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates a dojo datagrid for a given app's model. renders the contents until {% enddatagrid %} and takes options in the form of option=value per line.
def datagrid(parser, token): bits = token.split_contents() nodelist = parser.parse(('enddatagrid',)) parser.delete_first_token() app, model = None, None if len(bits) == 3: app = bits[1] model = bits[2] return DatagridNode(app, model,nodelist)
[ "def simple_datagrid(parser, token):\n bits = token.split_contents()\n if len(bits) < 3:\n raise TemplateSyntaxError(\"You have to pass app- and model-name to {% simple_datagrid app model %}\")\n return DatagridNode(bits[1],bits[2],None)", "def generate_dataset_jtable(request, option):\n\n obj_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This will output determine the intersection of a target bed file and the breakpoints of a cell type. Done as part of the Shuffle Permutation Analysis.
def target_intersection(self, runid): def targeting(shuffledict, seg_copy_array, cell_name): bedstring = "" seg_counts_dict = defaultdict(int) breakpoint_counts = 0 sum_counts = 0 for cell in shuffledict: with suppress(IndexError): ...
[ "def intersection_iteration(selection_space, intersect_space, self, cell):\n\n target_bed_map_array = self.target_bed_map_array\n\n iteration_count = 0\n tmp_intersection_list = []\n\n log = self.log\n\n # Get the number of unique breakpoints.\n self.seg_analyzer.break_poin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize our Segment_Analyzer class to get segment copy array, targeting array, breakpoint counts ect.
def segment_analyzer(self): sa = Segment_Analyzer.SegmentAnalyzer(self.log, self.args) sa.chromosome_ploidy(permutation=True) return sa
[ "def __init__(self, search_space=None):\n super(SegmentationNas, self).__init__(search_space)\n self.search_space = search_space\n self.max_sample_random = self.config.max_sample_random\n self.max_sample_mutate = self.config.max_sample_mutate\n self.sample_count = 0\n self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Do a permutation analysis based on the cells. Uses chromosome ploidy and breakpoint modules in Segment_Analyzer
def cell_permutation(self): self.log.info("Begin Sample Permutation Analysis.") # Initialize some variables. self.seg_analyzer.break_points(permutation=True) permutation_list = self.seg_analyzer.sample_names # cell_permutation_data_dict = defaultdict(lambda: defaultdict(list)) ...
[ "def permute_data(self):\n\n if not eval(self.args.Segment_Permutation_File):\n \"\"\"\n User has selected no permutation outputs and should not be here so kick them out.\n \"\"\"\n self.log.error(\"--Segment_Permutation_File must be set True\")\n return...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This will rebin the genome space to be consistent with the breakpoint definition or any other bin resampling desired.
def bin_sizing(self): self.log.info("Begin Re-Binning the Genome Space.") new_list = [] seg_num = 0 for chrom in natsort.natsorted(self.seg_analyzer.chrom_list): self.log.debug("Binning Chromosome {0}".format(chrom)) # Some chromosomes have no segments. ...
[ "def rebin(self, new_bin_bounds=None, show_warnings=True):\n # when no new_bin_bounds, returns raw binning (integer bins)\n if new_bin_bounds is None:\n self.bin_bounds = copy.deepcopy(self.raw_hist_bins)\n self.hist = copy.deepcopy(self.raw_hist)\n self.bins = self.hi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method maps the target coordinates onto the genome space coordinates. Also prints a file of the map coordinates if the user so desires. Returns a numpy array of the map.
def target_mapping(self): map_list = [] self.bin_tracking_array = self.seg_analyzer.bin_tracking_array self.log.info("Spawning {0} jobs to begin building Target_Bed_Map_Array for permutation analysis." .format(self.args.Spawn)) p = pathos.multiprocessing.Pool(int(...
[ "def Map(self, targetArray):\n # print \"Map: ({0}, {1}) -> {2}, {3}\".format(len(targetArray), len(targetArray[0]), self.x, self.y)\n\n for ii in range(self.ysize):\n #row\n for jj in range(self.xsize):\n #col\n # print \"Mapping: target({0},{1})={2...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Permutations based on random selection of segments. Group_Size is derived from actual number of breakpoints for cell type.
def permute_data(self): if not eval(self.args.Segment_Permutation_File): """ User has selected no permutation outputs and should not be here so kick them out. """ self.log.error("--Segment_Permutation_File must be set True") return cell_list ...
[ "def cell_permutation(self):\n\n self.log.info(\"Begin Sample Permutation Analysis.\")\n\n # Initialize some variables.\n self.seg_analyzer.break_points(permutation=True)\n permutation_list = self.seg_analyzer.sample_names\n # cell_permutation_data_dict = defaultdict(lambda: defau...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Controls the number of iterations and collects the data returned from the intersection function.
def intersection_iteration(selection_space, intersect_space, self, cell): target_bed_map_array = self.target_bed_map_array iteration_count = 0 tmp_intersection_list = [] log = self.log # Get the number of unique breakpoints. self.seg_analyzer.break_points(cell=cell, p...
[ "def create_intersection_report(self, data=None):\n\n if not data:\n data = self.build_dict_of_sets(self.data_dict)\n\n self.intersection_report_data = []\n finished = []\n\n for part in data:\n for union_part in data:\n if part != union_part and unio...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initializes this layer for fast inference, if in ``'predict'`` mode.
def init_weights_and_state(self, input_signature): if self._mode == 'predict': cache_signature = input_signature[4:6] self.state = self._fast_inference_init_state(cache_signature)
[ "def _init_layers(self):\n self._init_predictor()\n if self.use_edge_fusion:\n self._init_edge_module()", "def __setup_model(self, **kwargs):\n self.model_architecture = kwargs['model_architecture'].upper()\n self.model = Classifier.IMAGENET_MODELS[self.model_architecture](\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates state of a causal attention layer for fast inference. The layer state stores arrays with cached values of keys and values, as well as an index. To make shapes static, keys and values in the state are long, and the index indicates where the new keys and values from inputs need to be appended. During update, we a...
def _fast_inference_update_state(self, inputs, state): # Fast inference: run step-by-step, storing the sequence # of keys and values calculated so far in state. new_k, new_v = inputs length = new_k.shape[1] (ks, vs, idx) = state # We cannot generate more than one token because it contradicts ...
[ "def update_input_states(self, input_values):", "def _flatten_incr_state(\n self, structured_incr_state: Dict[int, Dict[str, Dict[str, torch.Tensor]]]\n ) -> Dict[str, torch.Tensor]:\n flat_incr_state = {}\n for layer_idx, dict1 in structured_incr_state.items():\n for attn_type,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sinusoidal Embeddings. Computes out of 1D integer absolute position vector the sinusoidal embeddings defined like in paper Attention is all you need (2017). Embeddings are shaped (positions, d_feature).
def Sinusoidal_Embeddings(positions, d_feature): inv_freq = 1 / (10000**(jnp.arange(0.0, d_feature, 2.0) / d_feature)) sinusoid_freq = jnp.einsum('i,j->ij', positions, inv_freq) pos_emb = jnp.concatenate( [jnp.sin(sinusoid_freq), jnp.cos(sinusoid_freq)], axis=1) return pos_emb
[ "def sentence_block_embed(embed, x):\n batch, length = x.shape\n _, units = embed.W.shape\n e = embed(x.reshape((batch * length, )))\n assert(e.shape == (batch * length, units))\n e = F.transpose(F.stack(F.split_axis(e, batch, axis=0), axis=0), (0, 2, 1))\n assert(e.shape == (batch, units, length)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize Stripe for the provided app. this method conforms to the Flaskstyle standard of initializing modules that depend on the app they are running in.
def init_app(self, app): stripe.api_key = app.config['STRIPE_API_KEY']
[ "def init_app(self, app):\n if app.debug:\n app.register_blueprint(blueprint)\n app.before_request(ProfilerTool.before_request)\n app.after_request(ProfilerTool.after_request)", "def init_app(self, app):\n app.extensions['fastspring'] = self\n self.debug = app...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Cancel a subscription. cancels a customer's current subscription.
def cancel_subscription(self, customer=None, user=None): if not customer and not user: raise UnboundLocalError('customer or user required') if not customer: customer = self.get_customer(user) return customer.cancel_subscription(at_period_end=True)
[ "def cancel_subscription(self,\n subscription_id):\n\n return super().new_api_call_builder.request(\n RequestBuilder().server('default')\n .path('/v2/subscriptions/{subscription_id}/cancel')\n .http_method(HttpMethodEnum.POST)\n .template...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a new stripe customer for the given user. saves the customer id to the user instance.
def create_customer(self, user, card_token, plan): customer = stripe.Customer.create( card=card_token, plan=plan, email=user.email, ) user.stripe_customer_id = customer.id user.save() return customer
[ "def create_customer(sender, instance, created, **kwargs):\n if created:\n Customer.objects.create(user=instance)", "def createCustomer(sender, instance, **kwargs):\n Customer.objects.get_or_create(user=instance)", "def create_customer(cls, api, **data):\n return api.create_customer(**data)"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }