query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
GET THE Q GRID ============== This method gives back a list of q points given the reciprocal lattice vectors and the supercell size. The q points are returned in 2pi / a units. Where a is the unit of measure of the unit_cell (usually Angstrom).
def GetQGrid(unit_cell, supercell_size, enforce_gamma_first = True): bg = Methods.get_reciprocal_vectors(unit_cell) n_vects = int(np.prod(supercell_size)) q_final = np.zeros((3, n_vects), dtype = np.double, order = "F") q_final[:,:] = symph.get_q_grid(bg.T, supercell_size, n_vects) # Get the list ...
[ "def GetQGrid_old(unit_cell, supercell_size):\n \n q_list = []\n # Get the recirpocal lattice vectors\n bg = Methods.get_reciprocal_vectors(unit_cell)\n \n # Get the supercell\n supercell = np.tile(supercell_size, (3, 1)).transpose() * unit_cell\n \n # Get the lattice vectors of the super...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET THE Q GRID ============== This method gives back a list of q points given the reciprocal lattice vectors and the supercell size.
def GetQGrid_old(unit_cell, supercell_size): q_list = [] # Get the recirpocal lattice vectors bg = Methods.get_reciprocal_vectors(unit_cell) # Get the supercell supercell = np.tile(supercell_size, (3, 1)).transpose() * unit_cell # Get the lattice vectors of the supercell bg_s ...
[ "def GetQGrid(unit_cell, supercell_size, enforce_gamma_first = True):\n bg = Methods.get_reciprocal_vectors(unit_cell)\n\n n_vects = int(np.prod(supercell_size))\n q_final = np.zeros((3, n_vects), dtype = np.double, order = \"F\")\n q_final[:,:] = symph.get_q_grid(bg.T, supercell_size, n_vects)\n\n #...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
CHECK THE Q POINTS ================== This subroutine checks that the given q points of a dynamical matrix matches the desidered supercell. It is usefull to spot bugs like the wrong definitions of alat units, or error not spotted just by the number of q points (confusion between 1,2,2 or 2,1,2 supercell).
def CheckSupercellQ(unit_cell, supercell_size, q_list): # Get the q point list for the given supercell correct_q = GetQGrid(unit_cell, supercell_size) # Get the reciprocal lattice vectors bg = Methods.get_reciprocal_vectors(unit_cell) # Check if the vectors are equivalent or not for iq...
[ "def testQMatrix(self):\n # The data we have available is only accurate to the 4th decimal place. This should\n # be sufficient. kx and ky are given in the setup, fixed by our angles theta and phi.\n absoluteTolerance = 0.0001;\n relativeTolerance = 0.001;\n kx = 1.0006;\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET NEW Q POINTS AFTER A CELL STRAIN ==================================== This method returns the new q points after the unit cell is changed. Remember, when changing the cell to mantain the same kind (cubic, orthorombic, hexagonal...) otherwise the star identification will fail. The q point are passed (and returned) i...
def GetNewQFromUnitCell(old_cell, new_cell, old_qs): bg = Methods.get_reciprocal_vectors(old_cell) #/ (2 * np.pi) new_bg = Methods.get_reciprocal_vectors(new_cell)# / (2 * np.pi) new_qs = [] for iq, q in enumerate(old_qs): # Get the q point in crystal coordinates new_qprime = M...
[ "def GetQGrid_old(unit_cell, supercell_size):\n \n q_list = []\n # Get the recirpocal lattice vectors\n bg = Methods.get_reciprocal_vectors(unit_cell)\n \n # Get the supercell\n supercell = np.tile(supercell_size, (3, 1)).transpose() * unit_cell\n \n # Get the lattice vectors of the super...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET THE SUPERCELL FROM THE LIST OF Q POINTS =========================================== This method returns the supercell size from the list of q points and the unit cell of the structure.
def GetSupercellFromQlist(q_list, unit_cell): # Get the bravais lattice bg = Methods.get_reciprocal_vectors(unit_cell) # Convert the q points in crystalline units supercell = [1,1,1] for q in q_list: qprime = Methods.covariant_coordinates(bg, q) qprime -= np.floor(qprime) ...
[ "def GetQGrid_old(unit_cell, supercell_size):\n \n q_list = []\n # Get the recirpocal lattice vectors\n bg = Methods.get_reciprocal_vectors(unit_cell)\n \n # Get the supercell\n supercell = np.tile(supercell_size, (3, 1)).transpose() * unit_cell\n \n # Get the lattice vectors of the super...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET SYMMETRIES ON MODES ======================= This methods returns a set of symmetry matrices that explains how polarization vectors interacts between them through any symmetry operation.
def _GetSymmetriesOnModes(symmetries, structure, pol_vects): # Get the vector of the displacement in the polarization m = np.tile(structure.get_masses_array(), (3,1)).T.ravel() disp_v = np.einsum("im,i->mi", pol_vects, 1 / np.sqrt(m)) underdisp_v = np.einsum("im,i->mi", pol_vects, np.sq...
[ "def getSymmetryMatrix(*args, **kwargs):\n \n pass", "def get_diagonal_symmetry_polarization_vectors(pol_sc, w, pol_symmetries):\n raise NotImplementedError(\"Error, this subroutine has not been implemented.\")\n\n # First we must get the degeneracies\n deg_list = get_degeneracies(w) \n\n # ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET SYMMETRIES ON MODES ======================= This methods returns a set of symmetry matrices that explains how polarization vectors interacts between them through any symmetry operation. Differently from the previous subroutine GetSymmetriesOnModes, which returns a tensor of the size (n_sym, n_modes, n_modes), this ...
def GetSymmetriesOnModesDeg(symmetries, structure, pol_vects, w_freq, timer = None, debug = False): Ns = len(symmetries) # Now we can pull out the translations pols = pol_vects w = w_freq #trans_mask = Methods.get_translations(pol_vects, structure.get_masses_array()) ...
[ "def _GetSymmetriesOnModes(symmetries, structure, pol_vects):\n\n # Get the vector of the displacement in the polarization\n m = np.tile(structure.get_masses_array(), (3,1)).T.ravel()\n disp_v = np.einsum(\"im,i->mi\", pol_vects, 1 / np.sqrt(m))\n underdisp_v = np.einsum(\"im,i->mi\", po...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET THE SUBSPACES OF DEGENERACIES ================================= From the given frequencies, for each mode returns a list of the indices of the modes of degeneracies.
def get_degeneracies(w): n_modes = len(w) ret_list = [] for i in range(n_modes): deg_list = np.arange(n_modes)[np.abs(w - w[i]) < 1e-8] ret_list.append(deg_list) return ret_list
[ "def _mode_subset(signal, freq, rate, main_freq, samples, modes=[1], width=0.2):\r\n # Compute the FFT.\r\n amp = fft_amp(signal, samples=samples)\r\n\r\n # Calculate resolution in frequency domain.\r\n res = (freq[1] - freq[0])\r\n\r\n for mode in modes:\r\n m_name = f'm{mode}'\r\n\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET THE POLARIZATION VECTORS THAT DIAGONALIZES THE SYMMETRIES ============================================================= This function is very usefull to have a complex basis in which the application of symmetries is trivial. In this basis, each symmetry is diagonal. Indeed this forces the polarization vectors to be...
def get_diagonal_symmetry_polarization_vectors(pol_sc, w, pol_symmetries): raise NotImplementedError("Error, this subroutine has not been implemented.") # First we must get the degeneracies deg_list = get_degeneracies(w) # Now perform the diagonalization on each degeneracies final_vectors = np.ze...
[ "def _GetSymmetriesOnModes(symmetries, structure, pol_vects):\n\n # Get the vector of the displacement in the polarization\n m = np.tile(structure.get_masses_array(), (3,1)).T.ravel()\n disp_v = np.einsum(\"im,i->mi\", pol_vects, 1 / np.sqrt(m))\n underdisp_v = np.einsum(\"im,i->mi\", po...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET THE Q VECTOR ================ For each polarization mode in the supercell computes the corresponding q vector. Indeed the polarization vector will be a have components both at q and at q. If a polarization vector mixes two q an error will be raised.
def GetQForEachMode(pols_sc, unit_cell_structure, supercell_structure, \ supercell_size, crystal = True): # Check the supercell n_cell = np.prod(supercell_size) nat = unit_cell_structure.N_atoms nat_sc = np.shape(pols_sc)[0] / 3 n_modes = np.shape(pols_sc)[1] ERR_MSG = """ Error, the...
[ "def _compute_Q_vector(self):\n\n self.QVector = list(it.product([fsc.Q for fsc in self.fscs]))", "def GetNewQFromUnitCell(old_cell, new_cell, old_qs):\n \n bg = Methods.get_reciprocal_vectors(old_cell) #/ (2 * np.pi)\n new_bg = Methods.get_reciprocal_vectors(new_cell)# / (2 * np.pi)\n \n ne...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Impose the translational symmetry directly on the supercell matrix.
def ApplyTranslationsToSupercell(fc_matrix, super_cell_structure, supercell): natsc = super_cell_structure.N_atoms # Check the consistency of the passed options natsc3, _ = np.shape(fc_matrix) assert natsc == int(natsc3 / 3), "Error, wrong number of atoms in the supercell structure" assert natsc3 ...
[ "def superimpose_apply(atoms, transformation):\n trans1, rot, trans2 = transformation\n s_coord = coord(atoms).copy()\n s_coord += trans1\n s_coord = np.dot(rot, s_coord.T).T\n s_coord += trans2\n\n if isinstance(atoms, np.ndarray):\n return s_coord\n else:\n transformed = atoms.c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET THE SYMMETRY MATRIX ======================= This subroutine converts the 3x4 symmetry matrix to a 3N x 3N matrix. It also transform the symmetry to be used directly in cartesian space. However, take care, it could be a very big matrix, so it is preverred to work with the small matrix, and maybe use a fortran wrappe...
def GetSymmetryMatrix(sym, structure, crystal = False): # Get the IRT array irt = GetIRT(structure, sym) nat = structure.N_atoms sym_mat = np.zeros((3 * nat, 3*nat), dtype = np.double) # Comvert the symmetry matrix in cartesian if not crystal: sym_cryst = Methods.convert_matrix_cart_c...
[ "def getSymmetryMatrix(*args, **kwargs):\n \n pass", "def getRawSymmetryMatrix(*args, **kwargs):\n \n pass", "def force_symmetry(matrix, symmetry):\n symmetric_matrix = matrix.copy()\n\n if symmetry is None:\n return symmetric_matrix\n\n for index, x in np.ndenumerate(matrix)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET FORCE CONSTANTS GENERATORS ============================== Compute a minimal basis for the force constants matrix. It is very useful for the compression of the force constants matrix, and to reduce the number of independent displacements that need to be calculated. If it is for a supercell dynamical matrix, symmetri...
def get_force_constants_generators(symmetries, irts, structure, timer=None): displacements = [] generators = [] list_of_calculations = [] n_syms = len(symmetries) nat3 = structure.N_atoms * 3 if Settings.am_i_the_master(): for i in range(structure.N_atoms): for j in range(3)...
[ "def _build_basis(self, N, ms):\n states_spin = [combinations(range(m), n) for n, m in zip(N, ms)] #generate all possible indices for particles per component, combinations ensures no double occupacies\n Nstates_total = int(np.prod([int(binom(m, n)) for n, m in zip(N, ms)])) #compute total number of st...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Cancels the currently running training process. If training is not running, do nothing.
def cancel_training(self): raise NotImplementedError
[ "def training_rejected(self):\n # immediately stop writing to shared stoage\n self.logger.info(\"training_rejected: for AI:{}\".format(self.ai_id))\n self.controller.save_controller.forget_ai(self.ai_id)\n\n # queue a new coroutine to release the status lock\n asyncio.create_task(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns new workspace names with number prefix switched.
def _swap_numbers(ws1, ws2, all_workspaces): new_ws1_name = re.sub('^[0-9]+', str(ws2['num']), ws1['name']) new_ws2_name = re.sub('^[0-9]+', str(ws1['num']), ws2['name']) used_names = frozenset(ws['name'] for ws in all_workspaces) def _avoid_used(new_name): while new_name in used_names: new_name = '{}...
[ "def _add_number_to_workspace(workspace, all_workspaces):\n max_num = i3.max_workspace_number(all_workspaces)\n # If there are no numbered workspaces, start at 1.\n target_num = 1 if max_num is None else 1 + max_num\n i3.command('rename', 'workspace', workspace['name'], 'to',\n '{}:{}'.format(target...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds a number prefix to the workspace name.
def _add_number_to_workspace(workspace, all_workspaces): max_num = i3.max_workspace_number(all_workspaces) # If there are no numbered workspaces, start at 1. target_num = 1 if max_num is None else 1 + max_num i3.command('rename', 'workspace', workspace['name'], 'to', '{}:{}'.format(target_num, work...
[ "def __prefixNumber(num, leading):\n length = int(leading)+1\n num = str(num)\n while len(num) < length:\n num = '0' + num\n return num", "def _getPrefix(self) -> str:\n return 'CHAPTER' + ('0' if int(self.number) < 10 else '') + str(self.number)", "def prefixed(filename, i, digits):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reorders adjacent workspaces by renaming and swapping their numbers.
def _reorder_workspaces(prev, debug=False): all_ws = i3.get_workspaces() output_ws = i3.focused_output_workspaces(all_ws) focused = i3.focused_workspace(output_ws) if focused['num'] == -1: _add_number_to_workspace(focused, output_ws) return numbered_ws = [ws for ws in output_ws if ws['num'] != -1] ...
[ "def _swap_numbers(ws1, ws2, all_workspaces):\n new_ws1_name = re.sub('^[0-9]+', str(ws2['num']), ws1['name'])\n new_ws2_name = re.sub('^[0-9]+', str(ws1['num']), ws2['name'])\n used_names = frozenset(ws['name'] for ws in all_workspaces)\n def _avoid_used(new_name):\n while new_name in used_names:\n new...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Verifies the current block chain and return True if it's valid, False otherwise.
def verify_chain(cls, block_chain): for (index, block) in enumerate(block_chain): if index == 0: continue if block.previous_hash != Hasher.hash_block(block_chain[index - 1]): ConsoleLogger.write_log( 'warn', __name_...
[ "def valid_chain(self, chain):\n previous_block = chain[0]\n index = 1\n while index < len(chain):\n block = chain[index]\n if block['previous_hash'] != self.hash(previous_block):\n return False\n if not self.valid_proof(block['proof'], previous_b...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Verifies the signature of transaction.
def verify_tx_signature(tx): public_key = RSA.importKey( binascii.unhexlify(tx.sender) ) verifier = PKCS1_v1_5.new(public_key) data_hash = Hasher.create_data_hash_256( tx.sender, tx.recipient, tx.amount ) return verifier....
[ "def __verifySignature(self, transaction: Transaction) -> bool:\n senderPublicKey = self.getSenderAccount(transaction.getSender()).get('publicKey')\n publicKey = RSA.importKey(binascii.unhexlify(senderPublicKey))\n verifier = PKCS1_v1_5.new(publicKey)\n txString = str(transaction.getOrde...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a File vertex to the graph.
def _addFileNode(self, f: File): # Add a vertex for the file. self.vertices[str(f.inode)] = "file"
[ "def add_vertex(self, vertex):\r\n self.vertices.append(vertex)", "def add_vertex(self, v):\n pass", "def add_vertex(self, vertex):\n\n\t\tself.vertices.append(vertex)", "def add_vertex(self, vertex: str):\n Logger.log(Logger.LogLevel.VERBOSE,\n f\"Adding vertex {sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute the clusters for this graph.
def computeClusters(self): comm = self.g.community_fastgreedy(weights=self.g.es["weight"]) self.clusters = comm.as_clustering()
[ "def cluster_cal(self):\n self.Cluster = []\n for i in range(self.nodenum):\n neighborhood_node = self.neighbor_node(i)\n Node_num = len(neighborhood_node)\n Count = self.neighbor_edge(neighborhood_node)\n if(Node_num == 0 or Node_num == 1):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add an Application vertex to the graph.
def _addAppNode(self, app: Application): # Add a vertex for the app. self.vertices[app.uid()] = "app" # Remember instances of an app so we can connect them. inst = self.instances.get(app.desktopid) or [] inst.append(app.uid()) self.instances[app.desktopid] = inst ...
[ "def _addAppNode(self, app: Application):\n # Add a vertex for the app.\n self.vertices[app.uid()] = \"app\"\n\n # Remember instances of an app so we can connect them.\n inst = self.instances.get(app.desktopid) or []\n inst.append(app.uid())\n self.instances[app.desktopid] ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a FileAccess edge to the graph.
def _addAccess(self, f: File, acc: FileAccess): # Get the source and destination vertex ids. source = acc.actor.uid() dest = str(f.inode) # Add the edge, and count a single access (unweighted clustering). self.edges.add((source, dest)) self.weights[(source, dest)] = 1
[ "def _addAccess(self, f: File, acc: FileAccess):\n # Get the source and destination vertex ids.\n source = acc.actor.desktopid\n dest = str(f.inode)\n\n # Add the edge.\n self.edges.add((source, dest))\n\n # Calculate the number of individual instances who accessed the file...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Link application instance vertices together.
def _linkInstances(self): for (app, insts) in self.instances.items(): edges = list(itertools.combinations(insts, 2)) for edge in edges: self.edges.add(edge) self.weights[edge] = 1
[ "def _addAppNode(self, app: Application):\n # Add a vertex for the app.\n self.vertices[app.uid()] = \"app\"\n\n # Remember instances of an app so we can connect them.\n inst = self.instances.get(app.desktopid) or []\n inst.append(app.uid())\n self.instances[app.desktopid] ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a FileAccess edge to the graph.
def _addAccess(self, f: File, acc: FileAccess): # Get the source and destination vertex ids. source = acc.actor.desktopid dest = str(f.inode) # Add the edge. self.edges.add((source, dest)) # Calculate the number of individual instances who accessed the file. ins...
[ "def _addAccess(self, f: File, acc: FileAccess):\n # Get the source and destination vertex ids.\n source = acc.actor.uid()\n dest = str(f.inode)\n\n # Add the edge, and count a single access (unweighted clustering).\n self.edges.add((source, dest))\n self.weights[(source, d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add an Application vertex to the graph.
def _addAppNode(self, app: Application): # Add a vertex for the app. self.vertices[app.uid()] = "app" # Remember instances of an app so we can connect them. inst = self.instances.get(app.desktopid) or [] inst.append(app.uid()) self.instances[app.desktopid] = inst ...
[ "def _addAppNode(self, app: Application):\n # Add a vertex for the app.\n self.vertices[app.uid()] = \"app\"\n\n # Remember instances of an app so we can connect them.\n inst = self.instances.get(app.desktopid) or []\n inst.append(app.uid())\n self.instances[app.desktopid] ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Link file vertices of an instance together.
def _linkInstances(self): filePairs = dict() for (source, files) in self.filesPerInstance.items(): # We'll have duplicate edges in the edges set (e.g. 6->4 and 4->6) # if we don't sort inodes prior to listing inode pairs. edges = list(itertools.combinations(sorted(fi...
[ "def _addFileNode(self, f: File):\n # Add a vertex for the file.\n self.vertices[str(f.inode)] = \"file\"", "def _addAccess(self, f: File, acc: FileAccess):\n # Get the source and destination vertex ids.\n source = acc.actor.desktopid\n dest = str(f.inode)\n\n # Add the e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the GraphEngine for the entire application.
def get(): if GraphEngine.__engine is None: GraphEngine.__engine = GraphEngine() return GraphEngine.__engine
[ "def _get_engine(self, context=None):\n context = context or self.context\n engine = self.engine_class(context=context, stores=self.stores)\n return engine", "def get_engine():\n from nam.core import application\n return application.database_engine", "def get_engine() -> Engine:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write the value by returning it, instead of storing in a buffer.
def write(self, value): return value
[ "def write(self, value, destination=None):\n pass", "def _write_value(self, value):\n writer = self._writer\n writer.dataElement(u'value', value)\n writer.newline()", "def _write_ret(self, val):\n self._log.debug('writing deferred return value %d', val)\n ovpn.write_def...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the path to the plugin_description.xml associated with the server.
def plugin_description(self): return str(self._plugin_description[0])
[ "def getPluginDescription(self, pkg):\n import rospkg\n rp = rospkg.RosPack()\n man = rp.get_manifest(pkg)\n return man.get_export(pkg, 'plugin')", "def get_plugin_path(self):\n\t\tpath = os.path.join(self.get_path(), 'plugins')\n\t\tif os.path.isdir(path):\n\t\t\treturn path\n\t\telse...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Configure the server's ZMQ ports and ROS subscribers.
def configureServer(self): # TODO: add dynamic reconfigure to change subscriber topic # configure ROS subscriber for bootstrapping templates sub = rospy.Subscriber("/foo", Marker, self.markerSub) # init zmq to port 6789 context = zmq.Context() self.socket = context.sock...
[ "def setup(self):\n self.set_stream_listener()\n self.setup_mq()\n self.start_listener()", "def init_zmq_socket(self):\n # Socket to talk to server\n self.context = zmq.Context()\n self.socket = self.context.socket(zmq.SUB)\n self.logs_filter = ZMQ_FILTER\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Stop a template process and remove it from the server's map. class_type string class_type The class type e.g. "Wheel", "Car", etc. instance_id int instance_id The ID of this instance. bool True if process was stopped/removed.
def removeTemplate(self, class_type, instance_id): if class_type in self.class_map and instance_id in self.class_map[class_type]: self.class_map[class_type][instance_id].terminate() del self.class_map[class_type][instance_id]
[ "def stop_process(self, name_or_id):\n\n with self._lock:\n # stop all processes of the template name\n if isinstance(name_or_id, six.string_types):\n self._stop_processes(name_or_id)\n else:\n # stop a process by its internal pid\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Start a template process using subprocess.Popen. class_type string class_type The class type e.g. "Wheel", "Car", etc. instance_id int instance_id The ID of this instance. int The Popen object started by the server.
def addTemplate(self, class_type, instance_id): if class_type in self.class_map: filename = os.path.join(self.template_path, ''.join([class_type, '.py'])) if self.topic_arg is None: args = [filename, str(instance_id), "True"] else: args = [file...
[ "def spawn_process(self, proc):\n\n ofunc = None\n ifunc = None\n\n # def send_info(ref, cmdline, env, childpid):\n # info = {\n # \"host\": HOSTNAME.split(\".\")[0],\n # \"pid\": os.getpid(),\n # \"cmdline\": cmdline,\n # \...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the plugin_description.xml for a ROS package.
def getPluginDescription(self, pkg): import rospkg rp = rospkg.RosPack() man = rp.get_manifest(pkg) return man.get_export(pkg, 'plugin')
[ "def plugin_description(self):\n return str(self._plugin_description[0])", "def installable_description(self):", "def format_desc(self):\n return '\\nDescription:\\n{}\\n'.format(\n C(\n FormatBlock(get_pkg_description(self.package)).format(\n width=76,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse affordance_templates manifest for available classes.
def getAvailableTemplates(self, templates): # if os.path.exists(manifest): from xml.etree.ElementTree import ElementTree class_map = {} # parse manifest.xml tree = ElementTree() tree.parse(templates) # get all <class> tags for c in tree.findall('class'): ...
[ "def read_template (self):\r\n log.info(\"reading manifest template '%s'\", self.template)\r\n template = TextFile(self.template,\r\n strip_comments=1,\r\n skip_blanks=1,\r\n join_lines=1,\r\n l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the button state.
def state(self, val): if isinstance(self._state, Button.State): self._state = val
[ "def set_state(self, state: bool) -> None:\n # Send EasyRemote update_element event for this button\n # with the given state.\n self.er.s.sendto((f\"action=update_element&id={self.id}\"\n f\"&page={self.page}&value={int(state)}\"\n \"&type=btn&e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Signal when button is released.
def released(self): self.state = Button.State.OFF
[ "def release(self, button, port=0):", "def mouseReleased(self, button, mouseX, mouseY):\n pass", "def on_release(self, global_state, widgets):\n logging.info('Button released, now turning off LED')\n\n widgets.led_berry.on()", "def on_button_down_event(self):\n raise NotImplementedError()"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Toggle the button state.
def toggle(self): if self._active == Button.State.ON: self._active = Button.State.OFF else: self._active = Button.State.ON
[ "def toggle(self):", "def toggle_state(self):\n if self.__is_enabled:\n self.get_widget().configure(state='disabled')\n else:\n self.get_widget().configure(state='enabled`')\n self.__is_enabled = not self.__is_enabled", "def toggle_buttons(self):\n buttons = (se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructor for a general simulation object.
def __init__(self, name, verbose=False): if verbose: print "Simulation base class constructor called" if isinstance(name, str): self.simulationName = name # String name of simulation code (eg GaussianJuly21) else: print "1st arg should be string name for th...
[ "def initialise_simulation(self):\n my_Simulator = Simulator(logger_=log)\n trace_files_dir = os.path.join('Tests','TraceFiles')\n trace_file_path = os.path.join(trace_files_dir,'trace_2_tst.txt')\n my_Simulator.parse_traceFile(trace_file_path)\n return my_Simulator", "def __ini...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Print out name of simulation object (for logging/status)
def __str__(self): return self.simulationName
[ "def __str__(self):\r\n \r\n for att in self.__dict__:\r\n print('%s: %r' % (att, getattr(self, att)))\r\n \r\n return 'Survey Simulation class object attributes'", "def __str__(self):\r\n\r\n for att in self.__dict__:\r\n print(\"%s: %r\" % (att, getattr(s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set template directory location
def setTemplateDir(self, tdir): if not os.path.exists(tdir): print "Template directory does not exist... check full path \n" sys.exit(0) self.templateDir = tdir
[ "def set_views_folder(self, *path):\n\t\tglobal template_dir\n\t\ttemplate_dir = os.path.join(os.path.dirname(__file__), *path)\n\t\tself.set_jinja2_options()", "def get_template_dir(self) -> str:", "def template_path(self):\n\n return super().template_path+[os.path.join(os.path.dirname(__file__), \"temp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Setter for the structure container.
def setStructureContainer(self, strucC): self.strucC = strucC self.isStrucSet = True
[ "def setContainer(self, cont: 'SoFieldContainer') -> \"void\":\n return _coin.SoField_setContainer(self, cont)", "def ModifyContainer(self, container):", "def setContainer(self, container: 'ScXMLObject') -> \"void\":\n return _coin.ScXMLDataObj_setContainer(self, container)", "def setContainer(s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the structure container. Deep copy performed, so that external changes to structure container are not reflected here.
def copyStructureContainerInto(self, strucC): self.strucC = copy.deepcopy(strucC) self.isStrucSet = True
[ "def setStructureContainer(self, strucC):\n self.strucC = strucC\n self.isStrucSet = True", "def setContainer(self, container: 'ScXMLObject') -> \"void\":\n return _coin.ScXMLDataObj_setContainer(self, container)", "def ModifyContainer(self, container):", "def setContainer(self, cont: 'So...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is the 'effective' base class interface for a method that writes an input file based on the internal attributes of an instance of the Simulation object This method should be redefined for each kind of file types (typically defined by simulation version eg LAMMPS, Gaussian etc)
def writeInput(self, fileName): print "No Simulation:writeInput method defined for pure base class" sys.exit(0)
[ "def create_simulation_file(self):\n\t\t# create and open the simulation file\n\t\tlines_to_write = []\n\t\t# In function of the model selected copy and past the contents of the template\n\t\t# in this new file\n\t\t# Select the template\n\t\tpath_template = self.templatePath + '/templates_models/' + \\\n\t\t self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks for existence of a top level simulation directory and writes out all files needed for running a simulation. Files copied/output are contained in the attribute 'inputFileNames'. In principle many input files/scripts could be copied to this location. If directory not found, then directory is created. Directory is ...
def createSimulation(self): # Check for run directory if (not os.path.exists(self.simDir)): print self.simDir, "does not exist... creating" os.mkdir(self.simDir) # For all simulation files, move into run directory for inFile in self.inputFileNames: ...
[ "def check_or_create_output_dir(self):\n if not os.path.exists(self.output_dir):\n os.makedirs(self.output_dir)", "def _make_output_dirs_if_needed(self):\n output_dir = os.path.dirname(self.output_path)\n if output_dir and not os.path.exists(output_dir):\n os.makedirs(ou...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reads the list of section and port assignment file and returns two dictionaries, one for the section > port assignment, and the other with the port > section assignment.
def read_section_ports_list( path: Optional[str] = None, ) -> Tuple[Dict[int, str], Dict[str, int]]: if path is None: path = SECTION_PORT_LIST_FILE if DBUTIL_SECTION_PORTS_TEST_DATA_ENV in os.environ: tmpfile = tempfile.NamedTemporaryFile() tmpfile.write(SECTION_PORTS_TES...
[ "def create_assay_assignment_dict(assay_file):\n assay_assignment_dict = {}\n for line in assay_file:\n line = line.rstrip()\n line_item = line.split(\"=\")\n assignment_group = line_item[0]\n assay_list = line_item[1].split(\",\")\n assay_assignment_dict[assignment_group] =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the port integer corresponding to the given section name. If the section is None, or an unrecognized one, return the default one (3306).
def get_port_from_section(section: str) -> int: _, sec2port = read_section_ports_list() return sec2port.get(section, 3306)
[ "def get_section_from_port(port: int) -> Optional[str]:\n port2sec, _ = read_section_ports_list()\n return port2sec.get(port, None)", "def port_num(name):\n for num in self.port_map:\n if self.port_map[num] == name:\n return num\n return -1", "def get_port_number(se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the section name corresponding to the given port. If the port is the default one (3306) or an unknown one, return a null value.
def get_section_from_port(port: int) -> Optional[str]: port2sec, _ = read_section_ports_list() return port2sec.get(port, None)
[ "def get_port_from_section(section: str) -> int:\n _, sec2port = read_section_ports_list()\n return sec2port.get(section, 3306)", "def port_name(self):\n return self.get_attr_string('port_name')", "def port_name(num):\n return self.port_map.get(num, 'Unknown')", "def port_id(self) -> Optio...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Translates port number to expected datadir path
def get_datadir_from_port(port: int) -> str: section = get_section_from_port(port) if section is None: return "/srv/sqldata" else: return "/srv/sqldata." + section
[ "def make_host_port_path(uds_path, port):\n return \"{}_{}\".format(uds_path, port)", "def portdir(argv):\n\tprint portage.settings[\"PORTDIR\"]", "def get_file_name(self, port):\n \n port_file_name = \"%s_%s_%d\" %(self.file_prefix, self.system_manager.cur_user, port )\n return os.path.jo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Split address into (host, port).
def addr_split(addr: str, def_port: int = 3306) -> Tuple[str, int]: port = def_port if addr.count(":") > 1: # IPv6 if addr[0] == "[": # [ipv6]:port addr_port_rx = re.compile(r"^\[(?P<host>[^]]+)\](?::(?P<port>\w+))?$") m = addr_port_rx.match(addr) ...
[ "def split_inet_addr(addr):\n split = addr.split(\":\")\n if len(split) < 2:\n return None\n ip = split[0]\n port = toInt(split[1])\n if port is None:\n return None\n return (ip, port)", "def parse_address(addr):\n if ':' in addr:\n try:\n host, port = addr.spl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Is n a perfect number?
def is_perfect(n): return sod(n) == 2*n and n > 0
[ "def perfect( n ):\n return sum(divisorsr(n,1)) == n", "def perfect_number(n):\n divisors = find_divisors(n)\n divisors.remove(n)\n sum_divisors = sum(divisors)\n return sum_divisors == n", "def is_perfect(n):\n # 1 is a factor of every number so the variable can be initialized with\n # thi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Is n an abundant number?
def is_abundant(n): return sod(n) > 2*n and n > 0
[ "def is_abundant(n):\n return n < get_sum_divisors(n)", "def isabundant(n:Integral) -> bool:\r\n return n > sigma(factors(n))", "def is_abundant_number(number: int) -> bool:\n return get_sum_of_divisors(number) > number", "def abundant(n):\r\n \"*** YOUR CODE HERE ***\"\r\n val = 1\r\n su = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Is n a defecient number?
def is_defecient(n): return sod(n) < 2*n and n > 0
[ "def is_deficient_number(number: int) -> bool:\n return get_sum_of_divisors(number) < number", "def is_factor(n, f):\n return n % f == 0", "def is_powerful(self,n):\n if n <= 1:\n return True\n ex = [e for _,e in arith.factor(n)]\n for e in ex:\n if e < 2:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Increases service capacity for every booking
def cap_inrease(self,number): if number == 1: self.current_capacity += 1 elif number == 2: self.service_two_capacity += 1 elif number == 3: self.service_three_capacity += 1 elif number == 4: self.service_four_capacity += 1 ...
[ "def updateOneService(self, reservation):\n # Adds information to the new service\n self.setServiceClient(reservation.getReservClient())\n\n # checks if it's going to be a delay, that is, if the driver/vehicle is not available at the requested time\n self.calculateDepartAndArrivalHour(re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Church admnistrators can access user data here
def church_admin(self):
[ "def user(ctx):\n pass", "def get_single_user():", "def principalForUser(user):", "def get_user_info(user):\n\n return user", "def author_info(self):\n return User.objects.get(pk=self.user_id)", "def test_get_user_level_access(self):\n pass", "def get_user_data(self):\n # We g...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find all tags in RSS_FEED. Replace dash with whitespace.
def get_tags(): tags1 = TAG_HTML.findall(rssread) tags1 = [w.replace('-', ' ') for w in tags1] return tags1
[ "def get_tags():\n tags = []\n with open(RSS_FEED) as file:\n for line in file.readlines():\n for tag in TAG_HTML.findall(line):\n tags.append(tag.replace('-', ' ').lower())\n return tags", "def tags_rss(request, tags):\n c = RequestContext(request)\n c['entries'] =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find set of tags pairs with similarity ratio of > SIMILAR
def get_similarities(tags): simtags3 = {} for i in tags: prodtags3 = list(product([i,''], tags)) for j in prodtags3: seqtags3 = SequenceMatcher(None, j[0].lower(), j[1].lower()) if seqtags3.ratio() != 0.0 and seqtags3.ratio() >= SIMILAR and seqtags3.ratio() != 1.0: ...
[ "def get_similarities(tags):\n similar_tags = []\n s_tags = set(tags)\n for tag in s_tags:\n for compare_tag in s_tags:\n if tag == compare_tag:\n continue\n else:\n compare = SequenceMatcher(None, tag, compare_tag).ratio()\n if comp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
moves to point location and draws a dot
def draw(self): super().draw() dot(self.prop['dotSize'], self.prop['dotColor'])
[ "def draw_to_point(self, x, y):\n if self.last == (x, y):\n return\n\n if self.drawing == False:\n self.start()\n\n # self.codes.append('G1 X%0.2f Y%0.2f F%0.2f' % (x, y+self.config['y_offset'], self.config['xy_feedrate']))\n\n # self.codes.append('G1 X{0:.2f} Y{1:....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Apply decorrelation stretch to image
def decorrstretch(self,A, tol=None): # save the original shape orig_shape = A.shape # reshape the image # B G R # pixel 1 . # pixel 2 . # . . . . A = A.reshape((-1,3)).astype(np.float) # covariance matrix of A cov = np....
[ "def applyNormalisation(image):\n #clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))\n #image[:,:,3] = clahe.apply(image[:,:,3])\n return image / 255.", "def corr_image(resting_image, aparc_aseg_file,fwhm, seed_region):\n import numpy as np\n import nibabel as nb\n import matplotlib.pyp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run a league play event by running round robins for half the divisions. When done, a new ladder file is created.
def run_league_play(working_dir: WorkingDir, odd_week: bool, replay_preference: ReplayPreference, team_size): bots = load_all_bots(working_dir) ladder = Ladder.read(working_dir.ladder) # We need the result of every match to create the next ladder. For each match in each round robin, if a result # exis...
[ "def playGolf(playerFullName): \n numberRounds = getValidInteger(NUMBER_ROUNDS_MIN, NUMBER_ROUNDS_MAX, \n \"How many rounds would you like to play? (1-9) \",\n \"Invalid number of rounds.\")\n for roundNumber in range(numberRounds): \...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
check image if it has longitude and latitude before upload to media file
def clean(self): if self.image: try: get_data = ImageMetaData(self.image) except AttributeError: raise ValidationError(_("This image type does not support" )) lat, lon = get_data.get_lat_lng() if not lat and not lon: ...
[ "def has_gps(img):\n imagen = open(img, 'rb')\n losTags = exifread.process_file(imagen)\n\n return True if 'GPS GPSLongitude' in losTags.keys() else False", "def imagecheck(tweet):\n\tpass", "def is_spatial_image(image: Any) -> bool:\n if not isinstance(image, xr.DataArray):\n ret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function creating the trade_dec_model model's graph.
def trade_dec_model(input_shape): ### START CODE HERE ### # Define sentence_indices as the input of the graph, it should be of shape input_shape and dtype 'int32' (as it contains indices). features = Input(shape = input_shape, dtype = 'float32') # Propagate features through your batch_la...
[ "def _create_graph(self, model: dict) -> Graph:\n\n\t\tgraph = Graph()\n\n\t\tkeys = list(model.keys())\n\n\t\tfor idx, pos in enumerate(keys):\n\t\t\tnode = Node(str(pos), name = str(pos), mlayout = pos[0], nlayout = pos[1])\n\t\t\tgraph.add_node(node)\n\n\t\tfor idx1, pos1 in enumerate(keys):\n\t\t\tnode1 = graph...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build query to request journey data.
def build_journey_query( self, station_id: str, direction_id: Optional[str] = None, max_journeys: int = 20, products: Optional[List[str]] = None, ) -> str: self.station_id = station_id self.direction_id = direction_id self.max_journeys = max_journeys ...
[ "def __build_query(self, user: str = None) -> None:\n # Optional params: start_time,end_time,since_id,until_id,max_results,next_token,\n # expansions,tweet.fields,media.fields,poll.fields,place.fields,user.fields\n self.__query = {'query': \"\"}\n\n if self.__twitter_keyword:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fetch suggestions for the given station name from the backend.
async def _fetch_sugestions( self, name: str, max_results: int ) -> List[Optional[Dict]]: params: Dict[str, Union[str, int]] = { "getstop": 1, "REQ0JourneyStopsS0A": max_results, "REQ0JourneyStopsS0G": name, } url = base_url(GETSTOP_PATH) + urllib...
[ "def _get_suggestions (self, state):\n\t\treturn SATClient().doSuggestStandards (self.nses_id, state, self.band)", "def google_suggestion(band_name):\r\n\r\n try:\r\n google_suggestion_url = (\r\n \"http://suggestqueries.google.com/complete/search?client=chrome&q=\"\r\n + band_nam...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the product filter.
def product_filter(products) -> str: _filter = sum({PRODUCTS[p] for p in products}) return format(_filter, "b")[::-1]
[ "def processFilter(self, pInputData):\n return _almathswig.DigitalFilter_processFilter(self, pInputData)", "def get_all_filtered(self):\n products = self.__repository.get_all()\n if self.__name_filter != \"\":\n products = [product for product in products if self.__name_filter in ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Try to fix known issues in XML data.
def fix_xml(data: bytes, err: etree.XMLSyntaxError) -> Any: xml_issue = data.decode().split("\n")[err.lineno - 1] if xml_issue not in KNOWN_XML_ISSUES.keys(): _LOGGER.debug("Unknown xml issue in: %s", xml_issue) raise RMVtransportError() return data.decode().replace(xml_issue, KNOWN_XML_IS...
[ "def test_invalid_xml_handling(self):\n sample_invalid_xml = textwrap.dedent(\"\"\"\n <problem>\n </proble-oh no my finger broke and I can't close the problem tag properly...\n \"\"\")\n with pytest.raises(etree.XMLSyntaxError):\n self._create_descriptor(sample_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function creates the DropDowns for Function selection based ond the funcitonLib
def createFunctionDropwDowns(self): all_functions = inspect.getmembers(functionLib, inspect.isfunction) self.c_functions = [] self.i_functions = [] self.r_functions = [] self.v_functions = [] self.l_functions = [] for functionTupel in all_functions: ...
[ "def _create_fmat_dropdown(self):\n options_list = list(self.available_plots.keys())\n default_value = options_list[0] # default_value = \"line\"\n dropdown_default_params = dict(options=options_list,\n value=default_value,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function creates multile DropDowns for the GUI. Mostly used for the input of components
def createDropDowns(self): self.componentDropwDown = QtGui.QComboBox() self.componentDropwDown.addItem("Resistor") self.componentDropwDown.addItem("Coil") self.componentDropwDown.addItem("Capacitator") self.componentDropwDown.addItem("V-Source") self.componentDropwDown.a...
[ "def createFunctionDropwDowns(self):\n\n all_functions = inspect.getmembers(functionLib, inspect.isfunction) \n\n self.c_functions = []\n self.i_functions = []\n self.r_functions = []\n self.v_functions = []\n self.l_functions = []\n\n for functionTupel in all_functi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the choosen potencial for plotting graph when PotencialDropDown changed
def onPotencialChanged(self): self.potencial = self.potenzialDropDown.currentIndex()
[ "def setStartingValues(self):\n if self.choosen == 0:\n self.function = self.function_i_DropwDownNew.currentText()\n else:\n self.function = self.function_v_DropwDownNew.currentText()\n self.initParametersDialog.close()", "def on_vendor_parameter_changed(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets function when functiondropdowns changed. It has influence on the function for the starting element
def setStartingValues(self): if self.choosen == 0: self.function = self.function_i_DropwDownNew.currentText() else: self.function = self.function_v_DropwDownNew.currentText() self.initParametersDialog.close()
[ "def createFunctionDropwDowns(self):\n\n all_functions = inspect.getmembers(functionLib, inspect.isfunction) \n\n self.c_functions = []\n self.i_functions = []\n self.r_functions = []\n self.v_functions = []\n self.l_functions = []\n\n for functionTupel in all_functi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handels the adding of a new component to the circuit
def addComponentToCircuit(self): component = (str(self.componentDropwDown.currentText())) function = "0" if component == "Capacitator": function = self.function_c_DropwDown.currentText() if component == "I-Source": function = self.function_i_DropwDown.currentTe...
[ "def add_component(self, component):\n self.components.append(component)", "def add_component(self, component):\r\n self.subcomponents.append(component)", "def add_component(self, component):\n self.__components.append(copy.deepcopy(component))", "def add(self, cname, **kwargs):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Merge copy of iMIS data with a new updated iMIS file. The new updated file is assumed to be the more uptodate file, typically it will be a report generated by the Girl Guides iMIS system
def update_data(current_file_path=None, new_data_file_path=None, make_backup=True): imis_file = ImisFile(current_file_path) imis_file.merge(new_data_file_path) #print(" ACTIVE MEMBERS") #print("--------------------------------------------------------") #for member in imis_file.active_mem...
[ "def update_inp(read,write,n_imperv,n_perv,d_imperv,d_perv,Ks,H_i,IMD):\n\n fin = open(read,'r')\n filedata = fin.read()\n fin.close()\n \n newdata=filedata.replace('S1 0.01 0.1 0 0 0 OUTLET ', \n 'S1 ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Select a set of iMIS numbers from the given file.
def select_numbers(file_path=None, how_many=3, make_backup=False, use_all=False): # Read in the iMIS data imis_file = ImisFile(file_path) # Set-up the random number generator random.seed() random.randrange(0, len(imis_file.active_member_list)) # Select the desired number of iMIS numbers s...
[ "def read_ints(file_name):\n with open(file_name) as f:\n return [int(x) for x in f.readlines()]", "def read_rad_indsets(fname):\n\n try:\n f = open(fname, \"r\")\n except IOError:\n print(\"Could not open file:\" + fname)\n sys.exit()\n with f:\n risd = f.readlines(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transform list of gene symbols to entrez_ids and returns a tuple of dataframes with results
def genesymbols_2_entrezids(genelist): # should check that genelist input does not have 'na' values probes_file = pd.read_csv('./data/raw/allen_human_fetal_brain/lmd_matrix_12566/rows_metadata.csv', usecols=['gene_symbol', 'entrez_id']).drop_duplicates() has_entrez = probes_fil...
[ "def get_entrez_conversion(genes: Tuple[str, ...]) -> Dict[str, str]:\n # Query mapping from gene IDs to entrez IDs\n mg = mygene.MyGeneInfo()\n df = mg.getgenes(genes, fields=\"entrezgene\", as_dataframe=1, species=\"human\")\n df = df[~df.entrezgene.isna()] # only keep genes with entrez IDs\n\n # ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert embedding with probe_ids for index to gene symbols by averaging probes for same gene symbol.
def convert_probe_emb_to_gene_emb(probe_emb): all_genes = pd.read_csv('./data/raw/allen_human_fetal_brain/lmd_matrix_12566/rows_metadata.csv') probe2gene = all_genes[all_genes.probeset_name.isin(probe_emb.index)].loc[:, ['probeset_name', 'gene_symbol']] # remove probes for 'A_' and 'CUST_' gene_symbols ...
[ "def transform_sample(vfdb_tool_result, gene_names):\n out = {'rpkm': {}, 'rpkmg': {}}\n for gene_name in gene_names:\n try:\n vals = vfdb_tool_result['genes'][gene_name]\n rpkm, rpkmg = vals['rpkm'], vals['rpkmg']\n except KeyError:\n rpkm, rpkmg = 0, 0\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load a TOML file
def test_toml_load(toml_load: str) -> None: results = tomlio.load(toml_load) assert results == EXPECTED_TOML
[ "def load_toml(path):\n from toml import loads\n return loads(path.read_text(encoding='utf-8'))", "def _toml(self):\r\n data = {}\r\n with open(self._filename, 'rb') as f:\r\n data = pytoml.load(f)\r\n return self._wrap(data)", "def _toml(self):\r\n return KaoToml(se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save a toml and load to confirm
def test_save_and_load(toml_save: str) -> None: tomlio.save(toml_save, EXPECTED_TOML) result = tomlio.load(toml_save) assert result == EXPECTED_TOML
[ "def save(self):\n self.path.write_text(toml.dumps(self.tomldoc))", "def save(self):\r\n with open(self._filename, 'w') as f:\r\n pytoml.dump(f, self._collapse(self._toml))", "def save(wn):\n wordnet_yaml.save(wn)\n save_all_xml(wn)\n with codecs.open(\"wn.xml\",\"w\",\"utf-8\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a line function from two points
def func_from_line(a: tuple, b: tuple) -> Callable[[int], int]: def f(x): """ the line function y = f(x)""" return a[1] + (b[1]-a[1])/(b[0]-a[0])*x - (b[1]-a[1])/(b[0]-a[0])*a[0] return f
[ "def train_linear_two_points(point_1, point_2):\n\n points = [point_1, point_2]\n x_coords, y_coords = zip(*points)\n A = vstack([x_coords, ones(len(x_coords))]).T\n m, c = lstsq(A, y_coords)[0]\n\n output_dict = {\"slope\": m, \"intercept\": c}\n\n return output_dict", "def coefficients_of_line...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the point, tuple such as (x,y) from points_list with minimal x coordinate. When there are two points it returns the bottom left point
def return_left_point(points_list: List[tuple]) -> tuple: return min(points_list)
[ "def leftmost(pts):\n return withmin(xcoord, pts)", "def farthestPoint(pointList, p):\r\n return None", "def min_x(self):\n return min(point.x for point in self.points)", "def return_right_point(points_list: List[tuple]) -> tuple:\n return max(points_list)", "def GetMinPoint(self):\n ....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the point, tuple such as (x,y) from points_list with maximal x coordinate. When there are two points it returns the upper right point
def return_right_point(points_list: List[tuple]) -> tuple: return max(points_list)
[ "def farthestPoint(pointList, p):\r\n return None", "def rightmost(pts):\n return withmax(xcoord, pts)", "def max_x(self):\n return max(point.x for point in self.points)", "def return_left_point(points_list: List[tuple]) -> tuple:\n return min(points_list)", "def find_max(elevation_list):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
classifies a number as positive, negative or zero
def classify(number): p = 1 n = -1 z = 0 if number > 0: return p elif number < 0: return n else: return z
[ "def classify_number(number):\n #YOUR CODE HERE\n return", "def positive(x):\r\n return x > 0", "def is_positive(number):\n if number > 0:\n return True\n return None", "def signe(x):\n if x > 0 : return 1\n elif x < 0 : return -1\n else : return 0", "def print_pos...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Proposal distribution for modifying a single particle's Cartesian coordinates.
def move_particle(current_sample: Chem.rdchem.Mol, args: Args) -> Chem.rdchem.Mol: # Initialize proposed sample proposed_sample = copy.deepcopy(current_sample) proposed_conf = proposed_sample.GetConformer() # Select a particle at random num_atoms = proposed_sample.GetNumAtoms() particle_...
[ "def particle(upperRight=\"string\", particleId=int, perParticleDouble=bool, inherit=float, vectorValue=float, order=int, conserve=float, name=\"string\", numJitters=int, dynamicAttrList=bool, deleteCache=bool, jitterRadius=\"string\", shapeName=\"string\", attribute=\"string\", jitterBasePoint=\"string\", count=bo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
MetropolisHastings conformational search using RDKit.
def rdkit_metropolis(args: Args, logger: Logger) -> None: # Set up logger debug, info = logger.debug, logger.info # Define constants k_b = 3.297e-24 # Boltzmann constant in cal/K avogadro = 6.022e23 # Molecule conformation list # conformation_molecules = [] all_conformation_...
[ "def PHOENIX_model_search(s_met, s_grav, s_teff, s_vturb):\n\n if not os.path.exists(rootdir + '/phoenix_models'):\n os.mkdir(rootdir + '/phoenix_models')\n os.mkdir(rootdir + '/phoenix_models/raw_models')\n\n # Path to the PHOENIX models\n model_path = rootdir + '/phoenix_models/raw_models/'\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates count error statistics for buckets of userobserved counts (postfiltering). Outputs the files preservation_by_length and preservation_by_count tsv and svg files.
def generateStatsAndGraphics(output_dir, max_syn_count, count_length_preservation, prefix): sorted_counts = sorted(count_length_preservation, key=lambda x: x[0], reverse=False) buckets = [] next_bucket = 10 while next_bucket < max_syn_count: buckets.append(next_bucket) next_bucket *= 2 ...
[ "def summary(path_to_GARUDATA, cycle):\n count = 0\n\n vis_directory, file_path_list = visibility_update(path_to_GARUDATA, cycle)\n\n for file_path in file_path_list:\n current_visibility = vis_directory[file_path]\n with open(file_path) as file:\n lines = file.readlines()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Assure the columns classes constructor work
def test_all_columns_classes_initialize(self): t = Text() b = Bool() i = Integer() f = Float() i_d = Id() self.assertIsInstance(t, Text) self.assertIsInstance(b, Bool) self.assertIsInstance(i, Integer) self.assertIsInstance(f, Float) self....
[ "def test_column_attributes_handled_correctly(self):\n\n class TestModel(Model):\n\n id = columns.UUID(primary_key=True, default=lambda:uuid4())\n text = columns.Text()\n\n #check class attibutes\n self.assertHasAttr(TestModel, '_columns')\n self.assertHasAttr(Test...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialization from the 9 components of the orientation matrix.
def __init__(self, matrix): g = np.array(matrix, dtype=np.float64).reshape((3, 3)) self._matrix = g self.euler = Orientation.OrientationMatrix2Euler(g) self.rod = Orientation.OrientationMatrix2Rodrigues(g) self.quat = Orientation.OrientationMatrix2Quaternion(g, P=1)
[ "def __initialize_from_mat3(self, mat):\n for i in range(0,8):\n self.data[i] = mat[i]", "def initialize_quaternions(self):\n # initialize as s = (0,0,0,0) and r = (0,0,0,1)\n N, M = self.M.num_reactants, self.M.num_products\n # only use three elements and enforce constraints in the f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the orientation matrix in the form of a 3x3 numpy array.
def orientation_matrix(self): return self._matrix
[ "def rotation_matrix(self):\n return np.array([self.axis_u, self.axis_v, self.axis_w])", "def get_rotationMatrix(self):\n rot_mat = quat2mat(self.quat)\n try:\n [U, s, V] = np.linalg.svd(rot_mat)\n return np.dot(U, V)\n except:\n return np.eye(3)", "d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create the particular crystal orientation called Cube and which corresponds to euler angle (0, 0, 0).
def cube(): return Orientation.from_euler((0., 0., 0.))
[ "def write_cube(data):\n\ttext = ''\n\tcenter = np.array(data['center'])\n\theight = data['height']\n\te1 = np.array([1,0,0]); e2 = np.array([0,1,0]); e3 = np.array([0,0,1])\n\tdata = {'corner': center-height/2*(e1+e2), 'v1': height*e1, 'v2': height*e2, 'v3': height*e3}\n\ttext = write_prism(data)\n\treturn text", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create the particular crystal orientation called Brass and which corresponds to euler angle (35.264, 45, 0).
def brass(): return Orientation.from_euler((35.264, 45., 0.))
[ "def solid_angle(angle):\n return (pi/4)*angle**2", "def zenith_angle(self):\n\t\treturn 90 - self.altitude_angle()", "def get_zenith_angle(self):\n theta = self.get_sph()[2]\n return np.pi/2. - theta", "def plot_sb_rotation():\n\n # Load CB offsets in HA, Dec\n cb_offsets = np.loadtxt('s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create the particular crystal orientation called Copper and which corresponds to euler angle (90, 35.264, 45).
def copper(): return Orientation.from_euler((90., 35.264, 45.))
[ "def sector(ix,iy,iz):\n\n if eecrystalphi(ix,iy,iz) ==999 : return 999\n \n deg = ( eecrystalphi(ix,iy,iz)+ pi ) * 180/pi\n return int(deg/5)", "def orientation(p, q, r):\n # use the slope to get orientation\n val = (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1])\n\n if val ==...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create the particular crystal orientation called Goss and which corresponds to euler angle (0, 45, 0).
def goss(): return Orientation.from_euler((0., 45., 0.))
[ "def zenith_angle(self):\n\t\treturn 90 - self.altitude_angle()", "def get_zenith_angle(self):\n theta = self.get_sph()[2]\n return np.pi/2. - theta", "def __str__(self):\n return \"{0:.4f}\".format(self.GetAngle('GON'))", "def declination_angle(self):\n\t\tinside_sin = math.radians((360 ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create the particular crystal orientation called shear and which corresponds to euler angle (45, 0, 0).
def shear(): return Orientation.from_euler((45., 0., 0.))
[ "def shear(self, shear, angle=0): \n if not isinstance(shear, (int,float)):\n raise TypeError('shear factor must be numeric')\n if not isinstance(angle, (int,float)):\n raise TypeError('angle must be numeric')\n \n angle = _math.pi*angle/180.\n p = self._localToGlobal(self._reference)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a random crystal orientation.
def random(): from random import random from math import acos phi1 = random() * 360. Phi = 180. * acos(2 * random() - 1) / np.pi phi2 = random() * 360. return Orientation.from_euler([phi1, Phi, phi2])
[ "def randomanglerotate(axis, xyz):\n angle = 2 * pi * rand()\n return rotate(axis, angle, xyz)", "def random_move(self):\n\t\toptions = [90, 180, 270]\n\t\tang = randint(0,2)\n\t\tn = randint(2, self.length - 1)\n\t\tself.rotate(n, radians(options[ang]))", "def pickDirection():\n turtle.right(random.ra...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute the IPF (inverse pole figure) colour for this orientation. Given a particular axis expressed in the laboratory coordinate system, one can compute the so called IPF colour based on that direction
def get_ipf_colour(self, axis=np.array([0., 0., 1.]), symmetry=Symmetry.cubic): axis /= np.linalg.norm(axis) # find the axis lying in the fundamental zone for sym in symmetry.symmetry_operators(): Osym = np.dot(sym, self.orientation_matrix()) Vc = np.dot(Osym, axis) ...
[ "def inverse(im):\n return 255 - im", "def color_pais ( self , pais ) :\n\n return self . _paises [ pais ] [ 0 ]\n if 58 - 58: i11iIiiIii % I1Ii111\n if 54 - 54: OOooOOo % O0 + I1IiiI - iII111i / I11i", "def colorizer(x, y):\n r = min(1, 1 - y/3)\n g = min(1, 1 + y/3)\n b = 1/4 + x/16...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute the misorientation axis from the misorientation matrix.
def misorientation_axis_from_delta(delta): n = np.array([delta[1, 2] - delta[2, 1], delta[2, 0] - delta[0, 2], delta[0, 1] - delta[1, 0]]) n /= np.sqrt( (delta[1, 2] - delta[2, 1]) ** 2 + (delta[2, 0] - delta[0, 2]) ** 2 + (delta[0, 1] - delta[1, 0]) ** 2) return n
[ "def _get_unit_axis(self, axis):\n r = self._get_column_d()\n if axis == 1:\n d = np.asarray([0, r], dtype=np.double)\n elif axis == 2:\n d = np.asarray([r*0.5*np.sqrt(3), r*0.5], dtype=np.double)\n elif axis == 3:\n d = np.asarray([r*0.5*np.sqrt(3), -r*0...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute the misorientation axis with another crystal orientation. This vector is by definition common to both crystalline orientations.
def misorientation_axis(self, orientation): delta = np.dot(self.orientation_matrix(), orientation.orientation_matrix().T) return Orientation.misorientation_axis_from_delta(delta)
[ "def compute_misorientation(euler_angle1, euler_angle2):\n\n # Assemble orientation matrices\n M1 = orientation_matrix(euler_angle1)\n M2 = orientation_matrix(euler_angle2)\n\n # Calculate misorientation\n M = np.dot(M1, np.linalg.inv(M2))\n\n # Get angle\n cosTheta = (M[0,0]+M[1,1]+M[2,2]-1.)/...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute the disorientation another crystal orientation. Considering all the possible crystal symmetries, the disorientation is defined as the combination of the minimum misorientation angle and the misorientation axis lying in the fundamental zone, which can be used to bring the two lattices into coincidence.
def disorientation(self, orientation, crystal_structure=Symmetry.triclinic): the_angle = np.pi symmetries = crystal_structure.symmetry_operators() (gA, gB) = (self.orientation_matrix(), orientation.orientation_matrix()) # nicknames for (g1, g2) in [(gA, gB), (gB, gA)]: for j...
[ "def compute_misorientation(euler1, euler2, symlist=None):\r\n quat1 = euler2quat(euler1)\r\n quat2 = euler2quat(euler2)\r\n\r\n if symlist is None:\r\n symlist = symeq('cubic')\r\n misori=disori(quat1,quat2,symlist)\r\n eps = 1e-6\r\n if 1-eps < misori < 1+eps:\r\n misori = 1\r\n\r\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute the two omega angles which satisfy the Bragg condition. For a given crystal orientation sitting on a vertical rotation axis,
def dct_omega_angles(self, hkl, lambda_keV, verbose=False): (h, k, l) = hkl.miller_indices() theta = hkl.bragg_angle(lambda_keV, verbose=verbose) lambda_nm = 1.2398 / lambda_keV gt = self.orientation_matrix().T # gt = g^{-1} in Poulsen 2004 Gc = hkl.scattering_vector() A...
[ "def compute_omega( g, tilt ): \n kz = g[2] # component along the rotation axis\n modg2 = (g*g).sum(axis=0)\n num = -modg2 - 2*tilt*kz\n den = 2*np.sqrt(1 - tilt*tilt)\n kx = num / den\n arg = modg2 - kx*kx - kz*kz\n mask = arg >= 0\n ky = np.sqrt( arg * mask ) # positive\n omegaplus = an...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute the instrument transformation matrix for given rotation offset. This function compute a 3x3 rotation matrix (passive convention) that transform the sample coordinate system
def compute_instrument_transformation_matrix(rx_offset, ry_offset, rz_offset): angle_zr = np.radians(rz_offset) angle_yr = np.radians(ry_offset) angle_xr = np.radians(rx_offset) Rz = np.array([[np.cos(angle_zr), -np.sin(angle_zr), 0], [np.sin(angle_zr), np.cos(angle_zr), 0], [0, 0, 1]]) ...
[ "def rotation_matrix(self) -> Tensor:\n return self.extrinsics[..., :3, :3]", "def getRotationMatrix(pitch, yaw):\n\trotationPitch = getRotationPitch(pitch)\n\trotationYaw = getRotationYaw(yaw)\n\treturn rotationYaw * rotationPitch", "def getRotationAndTranslationMatrix(rotation, translation):\n retur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute the tilts for topotomography alignment.
def topotomo_tilts(self, hkl, T=None, verbose=False): if T is None: T = np.eye(3) # identity be default gt = self.orientation_matrix().transpose() Gc = hkl.scattering_vector() Gs = gt.dot(Gc) # in the cartesian sample CS # apply instrument specific settings ...
[ "def toe_positions(self):\n torso_frame = self.data.xmat['torso'].reshape(3, 3)\n torso_pos = self.data.xpos['torso']\n torso_to_toe = self.data.xpos[_TOES] - torso_pos\n return torso_to_toe.dot(torso_frame)", "def OToL_unmapped_tips(self):\n debug(\"OTOL unmapped\")\n if...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }