query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Returns the maze distance between any two points, using the search functions you have already built. The gameState can be any game state Pacman's position in that state is ignored.
def mazeDistance(point1, point2, gameState): x1, y1 = point1 x2, y2 = point2 walls = gameState.getWalls() assert not walls[x1][y1], 'point1 is a wall: ' + str(point1) assert not walls[x2][y2], 'point2 is a wall: ' + str(point2) prob = PositionSearchProblem(gameState, start=point1, goal=point2, w...
[ "def mazeDistance(point1, point2, gameState):\n print point1, point2\n x1, y1 = point1\n x2, y2 = point2\n x1 = int(x1)\n x2 = int(x2)\n y1 = int(y1)\n y2 = int(y2)\n\n walls = gameState.getWalls()\n assert not walls[x1][y1], 'point1 is a wall: ' + point1\n assert not walls[x2][y2], 'point2 is a wall: ' +...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Should create a new instance of the SEGYPlotter.
def test_init_SEGYPlotter(self): fig = plt.figure() ax = fig.add_subplot(111) splt = SEGYPlotter(ax, self.segy) # should inherit from SEGYPlotManager for member in inspect.getmembers(SEGYPlotManager): self.assertTrue(hasattr(splt, member[0])) # should *not* bu...
[ "def test_init_SEGYPickPlotter(self):\n fig = plt.figure()\n ax = fig.add_subplot(111)\n splt = SEGYPickPlotter(ax, self.segy, pickdb=self.pickdb)\n # should inherit from SEGYPlotter\n for member in inspect.getmembers(SEGYPlotter):\n self.assertTrue(hasattr(splt, member...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Should add negative wiggle fills to the axes.
def test_plot_negative_wiggle_fills(self): fig = plt.figure() ax = fig.add_subplot(111) splt = SEGYPlotter(ax, self.segy) # should add a single artist to the active patch dict. splt.plot_wiggles(negative_fills=True) self.assertEqual(len(splt.ACTIVE_PATCHES['negative_fills...
[ "def setAxisBackground(idx=-1):\n dislin.axsbgd(idx)", "def test_plot_positive_wiggle_fills(self):\n fig = plt.figure()\n ax = fig.add_subplot(111)\n splt = SEGYPlotter(ax, self.segy)\n # should add a single artist to the active patch dict.\n splt.plot_wiggles(positive_fills=...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Should add positive wiggle fills to the axes.
def test_plot_positive_wiggle_fills(self): fig = plt.figure() ax = fig.add_subplot(111) splt = SEGYPlotter(ax, self.segy) # should add a single artist to the active patch dict. splt.plot_wiggles(positive_fills=True) self.assertEqual(len(splt.ACTIVE_PATCHES['positive_fills...
[ "def test_plot_negative_wiggle_fills(self):\n fig = plt.figure()\n ax = fig.add_subplot(111)\n splt = SEGYPlotter(ax, self.segy)\n # should add a single artist to the active patch dict.\n splt.plot_wiggles(negative_fills=True)\n self.assertEqual(len(splt.ACTIVE_PATCHES['neg...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Should add wiggle traces to the axes.
def test_plot_wiggle_traces(self): fig = plt.figure() ax = fig.add_subplot(111) splt = SEGYPlotter(ax, self.segy) # should add a single artist to the active line dict. splt.plot_wiggles(wiggle_traces=True) self.assertEqual(len(splt.ACTIVE_LINES['wiggle_traces']),1) ...
[ "def make_figure(self, traces):\n pass", "def test_plot_positive_wiggle_fills(self):\n fig = plt.figure()\n ax = fig.add_subplot(111)\n splt = SEGYPlotter(ax, self.segy)\n # should add a single artist to the active patch dict.\n splt.plot_wiggles(positive_fills=True)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Should create a new instance of the SEGYPickPlotter.
def test_init_SEGYPickPlotter(self): fig = plt.figure() ax = fig.add_subplot(111) splt = SEGYPickPlotter(ax, self.segy, pickdb=self.pickdb) # should inherit from SEGYPlotter for member in inspect.getmembers(SEGYPlotter): self.assertTrue(hasattr(splt, member[0])) ...
[ "def test_init_SEGYPlotter(self):\n fig = plt.figure()\n ax = fig.add_subplot(111)\n splt = SEGYPlotter(ax, self.segy)\n # should inherit from SEGYPlotManager\n for member in inspect.getmembers(SEGYPlotManager):\n self.assertTrue(hasattr(splt, member[0]))\n # sho...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write out the FileEntry instances into a FINI manifest.
def write_fini_manifest( entries: Iterable['FileEntry'], file: TextIO) -> None: for entry in sorted(entries): dst = entry.destination src = entry.source file.write("{}={}\n".format(dst, src))
[ "def write_file_manifest(name_map, out_stream):\n\n out_stream.write(struct.pack(COUNT_FMT, len(name_map)))\n # Sort to make it easier for diff algos to find contiguous\n # changes.\n names = name_map.keys()\n names.sort()\n for name in names:\n length = MANIFEST_ENTRY_HDR_LEN + len(name)\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A wrapper around os and os.path fns to correctly copy a file using a hardlink.
def fast_copy(src: FilePath, dst: FilePath, **kwargs) -> None: real_src_path = os.path.realpath(src) try: os.link(real_src_path, dst, **kwargs) except OSError: shutil.copy2(real_src_path, dst, **kwargs)
[ "def link_file(source, target):\n try:\n os.symlink(source, target)\n except AttributeError:\n try:\n os.link(source, target)\n except AttributeError:\n copy_file(source, target)", "def copy(src, dst, link=1, touch=0):\n\n global bytes, lins, drs, syms, touchs, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a new array of given shape and type, without initializing entries.
def empty(shape, ctx=None, dtype=None, stype=None): if stype is None or stype == 'default': return _empty_ndarray(shape, ctx, dtype) else: return _empty_sparse_ndarray(stype, shape, ctx, dtype)
[ "def create_empty_array(shape, dtype):\n dtype_init_vals = {\n float: np.nan,\n int: 0,\n bool: False,\n }\n\n return np.full(shape, dtype_init_vals[dtype], dtype=dtype)", "def empty(shape, num=0):\n data = [num]*(shape[-1] if shape else 1)\n for dim in shape[-2::-1]:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loads an array dictionary or list from a buffer See more details in ``save``.
def load_frombuffer(buf): if not isinstance(buf, string_types + tuple([bytes])): raise TypeError('buf required to be a string or bytes') out_size = mx_uint() out_name_size = mx_uint() handles = ctypes.POINTER(NDArrayHandle)() names = ctypes.POINTER(ctypes.c_char_p)() check_call(_LIB.MXND...
[ "def load_from_buffer(self, buffer):\n loader = GazpachoObjectBuilder(buffer=buffer, app=self._app)\n self._read_from_loader(loader)", "def load_data(self, data):\n import numpy as np\n for key in data.keys():\n self.data[key] = []\n for i in range(len(self.buffer...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Saves a list of arrays or a dict of str>array to file.
def save(fname, data): from ..numpy import ndarray as np_ndarray if isinstance(data, NDArray): data = [data] handles = c_array(NDArrayHandle, []) if isinstance(data, dict): str_keys = data.keys() nd_vals = data.values() if any(not isinstance(k, string_types) for k in ...
[ "def save_arr(arr, filename, indent=None):\r\n with open(f'{DATA_DIR}{filename}', 'w') as f:\r\n lists = arr.tolist()\r\n json.dump(lists, f, indent=indent)", "def save_array(array, filename):\n np.save(filename, array)", "def save_to_file(cls, list_objs):\n li = []\n with open...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the sum of diagonal elements of matrix X.
def trace(X): return extract_diag(X).sum()
[ "def trace(X):\r\n return extract_diag(X).sum()", "def diag(self, X):\n\n\t\tn_samples_X, n_features = X.shape\n\t\tscale = self.scale_kernel.tril\n\n\t\tK_diag = np.zeros(shape=(n_samples_X,))\n\n\t\tstates_X = X[:,0].astype(int)\n\n\t\tfor n in range(len(self.state_kernels)):\n\t\t\t\"\"\" Diag = Sum_{k=0..n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function performs the SVD on CPU.
def svd(a, full_matrices=1, compute_uv=1): return SVD(full_matrices, compute_uv)(a)
[ "def svm():", "def update_svd_naive(self):\n print(\"Updating truncated SVD using naive method.\")\n start = time.perf_counter()\n self.Uk, self.sigmak, self.VHk = naive_update(\n self.A, self.Uk, self.sigmak, self.VHk, self.update_matrix\n )\n self.runtime += time.pe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
r"""Raise a square matrix, ``M``, to the (integer) power ``n``. This implementation uses exponentiation by squaring which is significantly faster than the naive implementation. The time complexity for exponentiation by squaring is
def matrix_power(M, n): if n < 0: M = pinv(M) n = abs(n) # Shortcuts when 0 < n <= 3 if n == 0: return at.eye(M.shape[-2]) elif n == 1: return M elif n == 2: return tm.dot(M, M) elif n == 3: return tm.dot(tm.dot(M, M), M) result = z = None...
[ "def matrix_power_impl(a, n):\n\n _check_linalg_matrix(a, \"matrix_power\")\n np_dtype = np_support.as_dtype(a.dtype)\n\n nt = getattr(n, 'dtype', n)\n if not isinstance(nt, types.Integer):\n raise NumbaTypeError(\"Exponent must be an integer.\")\n\n def matrix_power_impl(a, n):\n\n if ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Aesara utilization of numpy.linalg.tensorinv; Compute the 'inverse' of an Ndimensional array. The result is an inverse for `a` relative to the tensordot operation ``tensordot(a, b, ind)``, i. e., up to floatingpoint accuracy, ``tensordot(tensorinv(a), a, ind)`` is the "identity" tensor for the tensordot operation.
def tensorinv(a, ind=2): return TensorInv(ind)(a)
[ "def _vect_matrix_inverse(A):\n identity = np.identity(A.shape[2], dtype=A.dtype)\n return np.array([np.linalg.solve(x, identity) for x in A])", "def right_inverse(mat):\n return mat.T @ np.linalg.inv(mat @ mat.T)", "def inverse_matrice(T):\n a,b,c,d = T[0][0],T[0][1],T[1][0],T[1][1]\n de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Aesara utilization of numpy.linalg.tensorsolve. Solve the tensor equation ``a x = b`` for x. It is assumed that all indices of `x` are summed over in the product, together with the rightmost indices of `a`, as is done in, for example, ``tensordot(a, x, axes=len(b.shape))``.
def tensorsolve(a, b, axes=None): return TensorSolve(axes)(a, b)
[ "def _stable_solve(A, B):\n assert A.shape[:-2] == B.shape[:-2], (A.shape, B.shape)\n assert A.shape[-1] == B.shape[-2], (A.shape, B.shape)\n try:\n return np.linalg.solve(A, B)\n except np.linalg.linalg.LinAlgError:\n shape_A, shape_B = A.shape, B.shape\n assert shape_A[:-2] == sha...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Default initializer of the system. Requires number of layers as input. NL number of layers kS object of kSpace type
def __init__(self,NL,kS=None): assert isinstance(NL,int), "Wrong data type for number of layers.\n\n" assert NL>0, "At least one layer is needed.\n" self.NL=NL self.layers=[] # List self.layers will store object of type Layer for i in range(NL): self.layers+=[Layer...
[ "def __init__(self, layers):\n\n if len(layers) < 1:\n raise Exception('NN must have at least one layer.')\n\n self.layers = layers\n self.num_layers = len(layers)\n\n # Initialize layers from input props.\n self.init_layers()", "def init_dense(self, layer):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function updates parameters of all layers with the same values. If option randomly=True than small Gaussian noise (with sigma mean squared error) is added to each parameter.
def update_all_layers(self,t1=0.0,t2=0.0,phi=0.0,m=0.0,t31=0.0, t32=0.0, randomly=False,sigma=0.03): if randomly: for i in range(self.NL): self.layers[i].update_values( t1*(1.+np.random.randn(1)*sigma) ,t2*(1.+np.random.randn(1)*sigma) ,phi*(1.+np.random.randn(1)*sigma) ,m*(1.+np.ran...
[ "def update_parameters(self):\n # We update gamma, gamma0, lambda and nu in turn (Bottolo et al, 2011)\n self.update_gamma()\n self.update_gamma0()\n self.update_lambda()\n self.update_nu()\n if self.sample_xi:\n self.update_xi()", "def update_layer(self,LI=0,t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function updates all couplings with the same values. If option randomly=True than small Gaussian noise (with sigma mean squared error) is added to each parameter.
def update_all_couplings(self,r=0.0, randomly=False,sigma=0.03): assert self.NL>1, "At least one coupling is needed!\n" if randomly: for i in range(self.NL-1): self.couplings[i]=r*(1.+np.random.randn(1)*sigma) else: for i in range(self.NL-1): ...
[ "def update_coupling(self,IC=0,r=0.0, randomly=False,sigma=0.03):\n assert self.NL>1, \"At least one coupling is needed!\\n\"\n if randomly:\n self.couplings[IC]=r*(1.+np.random.randn(1)*sigma)\n else:\n self.couplings[IC]=r", "def _update_couplings(self):\n self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function updates parameters of a single layer with specified values. If option randomly=True than small Gaussian noise (with sigma mean squared error) is added to each parameter.
def update_layer(self,LI=0,t1=0.0,t2=0.0,phi=0.0,m=0.0,t31=0.0, t32=0.0, randomly=False,sigma=0.03): if randomly: self.layers[LI].update_values( t1*(1.+np.random.randn(1)*sigma) ,t2*(1.+np.random.randn(1)*sigma) ,phi*(1.+np.random.randn(1)*sigma) ,m*(1.+np.random.randn(1)*sigma) ,t31*(1.+np.random.r...
[ "def update_parameters(self):\n # We update gamma, gamma0, lambda and nu in turn (Bottolo et al, 2011)\n self.update_gamma()\n self.update_gamma0()\n self.update_lambda()\n self.update_nu()\n if self.sample_xi:\n self.update_xi()", "def update_params(self):\r\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function updates a single coupling with specified value. If option randomly=True than small Gaussian noise (with sigma mean squared error) is added to each parameter.
def update_coupling(self,IC=0,r=0.0, randomly=False,sigma=0.03): assert self.NL>1, "At least one coupling is needed!\n" if randomly: self.couplings[IC]=r*(1.+np.random.randn(1)*sigma) else: self.couplings[IC]=r
[ "def update_all_couplings(self,r=0.0, randomly=False,sigma=0.03):\n assert self.NL>1, \"At least one coupling is needed!\\n\"\n if randomly:\n for i in range(self.NL-1):\n self.couplings[i]=r*(1.+np.random.randn(1)*sigma)\n else:\n for i in range(self.NL-1):...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
See description of reset_kSpace in kSpace class.
def reset_kSpace(self,Nx=24,Ny=24,kx0=-pi/3.,ky0=0.,kxmax=pi,kymax=2.*pi/np.sqrt(3.)): self.kS.reset_kSpace(Nx,Ny,kx0,ky0,kxmax,kymax)
[ "def _reset_k_vec( self ):\n self._reset_v_vec( 'k' )", "def resetBoard(self):\n self.space1 = 0\n self.space2 = 0\n self.space3 = 0\n self.space4 = 0\n self.space5 = 0\n self.space6 = 0", "def process_kspace(self, kspace):\n return kspace", "def _reset_theta_k( self ):\n se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method allows to access just the eigenvalue of the Hamiltonian sorted in a list.
def Ham_eigvals(self,kx,ky): tHam=self.Ham_gen(kx,ky) eigval=np.linalg.eigvals(tHam) sidc=eigval.argsort() eigval=eigval[sidc] return eigval.real
[ "def calculate_eigenvalues(H):\n eigenvalues, eigenvectors = np.linalg.eigh(H)\n return eigenvalues, eigenvectors", "def test_eigvals_hermitian(self, tol):\n X = qml.PauliX(0)\n hamiltonian = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]])\n Herm = qml.Hermitian(hamil...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method diagonalizes the Hamiltonian for each point in the Brillouin zone and stores its eigenvalues and eigenvectors as well as density matrix assuming halffilling and T=0. These results are needed for calculation of various topological invariants. Updates class specific variables. Returns direct gap at the K and ...
def init_eigdata(self,LI=0): # For shorter notation we locally redefine variables. NL=self.NL Nx=self.kS.Nx Ny=self.kS.Ny kx0=self.kS.kx0 ky0=self.kS.ky0 dkx=self.kS.dkx dky=self.kS.dky self.LDM=np.zeros((NL,Nx+1,Ny+1,2,2),dtype=complex) ...
[ "def diag(B,s,H,ia,ib,ic,chia,chic):\n # Get a guess for the ground state based on the old MPS\n d = B[0].shape[0]\n theta0 = np.tensordot(np.diag(s[ia]),np.tensordot(B[ib],B[ic],axes=(2,1)),axes=(1,1))\n theta0 = np.reshape(np.transpose(theta0,(1,0,2,3)),((chia*chic)*(d**2)))\n\n # Diagonalize Hamil...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method allows to find an indirect gap in the model. The algorithm initiates a rondom point in the BZ and performs optimization algorithm to find minimal energy of the lowest empty band and highest energy of the highest empty band. Calculation is repeated several times to avoid geting stuck in local minimum. Return...
def find_indirect_gap(self,rpts=5): # First find the miniumu of the upper band. # Start with a random point in the BZ. x0up=[self.kS.kx0+random()*(self.kS.kxmax-self.kS.kx0),self.kS.ky0+random()*(self.kS.kymax-self.kS.ky0)] # Define functions to minimize fun1= lambda x: self.Ham_...
[ "def find_direct_gap(self,rpts=5):\n # Start with a random point in the BZ.\n x0up=[self.kS.kx0+random()*(self.kS.kxmax-self.kS.kx0),self.kS.ky0+random()*(self.kS.kymax-self.kS.ky0)]\n # Define functions to minimize\n fun1= lambda x: self.Ham_eigvals(x[0],x[1])[self.NL]-self.Ham_eigvals(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method allows to find an direct gap in the model. The algorithm initiates a rondom point in the BZ and performs optimization algorithm to find minimal gap. Calculation is repeated several times to avoid geting stuck in local minimum. Returns gap size and position in the BZ.
def find_direct_gap(self,rpts=5): # Start with a random point in the BZ. x0up=[self.kS.kx0+random()*(self.kS.kxmax-self.kS.kx0),self.kS.ky0+random()*(self.kS.kymax-self.kS.ky0)] # Define functions to minimize fun1= lambda x: self.Ham_eigvals(x[0],x[1])[self.NL]-self.Ham_eigvals(x[0],x[1]...
[ "def find_indirect_gap(self,rpts=5):\n # First find the miniumu of the upper band.\n # Start with a random point in the BZ.\n x0up=[self.kS.kx0+random()*(self.kS.kxmax-self.kS.kx0),self.kS.ky0+random()*(self.kS.kymax-self.kS.ky0)]\n # Define functions to minimize\n fun1= lambda x:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This represents the first method of calculationg topological invariant. Calcualtes TKNN invariant, that is the Chern number of the entire system. Implements Fukui's method. Returns the Chern number and a map of estimates of Berry curvature.
def method1(self): cres=0. # Variable for storing Chern number. # The U matrices from Fukui's method; storage... Ux=np.zeros((self.kS.Nx+1,self.kS.Ny+1),dtype=complex) Uy=np.zeros((self.kS.Nx+1,self.kS.Ny+1),dtype=complex) # ... and calculation of U matrices f...
[ "def computeBoundaryPoints(self):\n # First we need to make a node to represent the treebox, and we need\n # to work out its geometry.\n # We also need to know on which side of the root node the two boxes make contact.\n rootnode = self.tp.node\n rx, ry = rootnode.x, rootnode.y\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This represents the second method of calculationg topological invariant. Calcualtes layer specific invariant with a method defined by Junhui Zheng. Also uses Fukui's method for discretization. Returns the invariants for each layer as a list.
def method2(self): cres=np.zeros(self.NL,dtype=float) # List of invariants # The U matrices from Fukui's method; storage... Ux_loc=np.zeros((self.kS.Nx+1,self.kS.Ny+1),dtype=complex) Uy_loc=np.zeros((self.kS.Nx+1,self.kS.Ny+1),dtype=complex) for il in range(self.NL): ...
[ "def invariant(A1,A2,A3,A4,invt_ind):\n\n invt_ind_flip = tuple()\n flips = 0\n for tup in invt_ind:\n if tup in upper_all:\n invt_ind_flip += tup,\n else:\n invt_ind_flip += tup[::-1],\n flips += 1\n reorder, sgn = reorder_sign(invt_ind_flip)\n \n if...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Default constructor. It is best to use multiples of 24 for Nx and Ny, in order for grid of discretization to "hit" the K and K' points in Brillouin zone. Otherwise accuracy might go down close to the topological phase transitions due to the discretization of quite sharp features in the Berry curvature of the graphene. ...
def __init__(self,Nx=24,Ny=24,kx0=-pi/3.,ky0=0.,kxmax=pi,kymax=2.*pi/np.sqrt(3.)): self.Nx=Nx self.Ny=Ny self.kx0=kx0 self.ky0=ky0 self.kxmax=kxmax self.kymax=kymax self.dkx=(kxmax-kx0)/float(Nx) self.dky=(kymax-ky0)/float(Ny)
[ "def brillouinZone(self,a,initiator=None):\n if(initiator and not self.checkEventFlags(\"main\")):\n initiator.progress(\"Mapping the first Brillouin zone\")\n \n print(\"Mapping the first Brillouin zone\")\n N = self.N\n ks = self.ks\n \n # Reciproca...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates the user associated wallets table
def update_user_associated_wallets( session, update_task, user_record, associated_wallets, chain ): try: if not isinstance(associated_wallets, dict): # With malformed associated wallets, we update the associated wallets # to be an empty dict. This has the effect of generating new...
[ "def update_users(self):\n conn = sqlite3.connect(self.__DB)\n cursor = conn.cursor()\n\n users_data = []\n unsaved_histories_data = []\n for key, user in self.__users.items(): # here, key it's actually users id\n users_data.append((user.get_balance(), key))\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates the user events table
def update_user_events( session: Session, user_record: User, events: UserEventsMetadata, bus: ChallengeEventBus, ) -> None: try: if not isinstance(events, dict): # There is something wrong with events, don't process it return # Mark existing UserEvents entrie...
[ "def update_events_in_database(self):\n for i in range(0, len(self._event_id_list), 1):\n e_id = self._event_id_list[i] # DB ID\n e_ind = self._event_index_list[i] # Index of the event\n e_db = Event.objects.get(id=e_id) # Event as stored in the DB\n e_db...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a DAG of the object property hierarchy in the graph. This hierarchy is defined by the RDFS "subproperty of" property.
def get_prop_dag(graph: Graph, property_to_id: Dict[str, int]) -> Dict[int, DAGNode]: # dictionary pointing from object property id to the corresponding node in the entity type DAG property_dag = {} # iterate over property hierarchy for subject, predicate, object in graph.triples((None, RDFS.subPropert...
[ "def new_object_property(self, prop, d, r, t='', sub_prop=''):\n self.o_property += '### http://www.semanticweb.org/ontologies/2015/3/' + self.namespace + '.owl#' + prop + '\\n\\n'\n if t == '':\n self.o_property += self.namespace + ':' + prop + ' rdf:type owl:ObjectProperty ;\\n\\n'\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a DAG of the entity type hierarchy in the graph. This hierarchy is defined by the RDFS "subclass of" property.
def get_type_dag(graph: Graph, entity_type_to_id: Dict[str, int]) -> Dict[int, DAGNode]: # dictionary pointing from entity type id to the corresponding node in the entity type DAG entity_type_dag = {} # extract equivalence class relation equivalent_classes = {} for subject, predicate, object in gra...
[ "def create_hierarchy(self):\n\t\tpass", "def create_from_discriminator_value(parse_node: Optional[ParseNode] = None) -> OnenoteEntityHierarchyModel:\n if not parse_node:\n raise TypeError(\"parse_node cannot be null.\")\n try:\n mapping_value = parse_node.get_child_node(\"@oda...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extracts the domains from the Knowledge Graph. These are defined by the RDFS "domain" relation. These relations are defined between an object property (subject) and an entity type (object) and express that the object property
def get_domains(graph: Graph, property_to_id: Dict[str, int], entity_type_to_id: Dict[str, int]) -> Dict[int, int]: # dictionary pointing from object property id to an entity type id domains = {} # add all domain triples for which the subject is an object property and the object is an entity type for s...
[ "def _identify_domains(self):\n\n domains = [FEMDomain(TR3, MeshPart(self.mesh, labels=(0,)), self.media, self.labels)]\n return domains", "def infer_domains(self, relations):\n domains = dict()\n for name, args in relations.items():\n for arg in args:\n if arg not in domains:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extracts the ranges from the Knowledge Graph. These are defined by the RDFS "range" relation. These relations are defined between an object property (subject) and an entity type (object) and express that the value of the
def get_ranges(graph: Graph, property_to_id: Dict[str, int], entity_type_to_id: Dict[str, int]) -> Dict[int, int]: # dictionary pointing from object property id to an entity type id ranges = {} # add all range triples for which the subject is an object property and the object is an entity type for subj...
[ "def get_range(self, start, end):", "def ranges(self):\n return self._ranges", "def get_range(element, ranges, dimension):\n if dimension and dimension != 'categorical':\n if ranges and dimension.name in ranges:\n drange = ranges[dimension.name]['data']\n srange = ranges[d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initializes a RFC2579 datetime.
def __init__(self, precision=None, rfc2579_date_time_tuple=None): super(RFC2579DateTime, self).__init__( precision=precision or definitions.PRECISION_100_MILLISECONDS) self._day_of_month = None self._deciseconds = None self._hours = None self._minutes = None self._month = None self._...
[ "def test_rfc3339_as_datetime(self):\n self.assertEquals(\n rfc3339_as_datetime(\"1971-04-20T16:20:04Z\"),\n DateTime(1971, 4, 20, 16, 20, 4, tzinfo=utc)\n )", "def __init__(self, datestring, **kwargs):\n fmt = kwargs.get('fmt', self.default_fmt)\n is_local = kwar...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves the normalized timestamp.
def _GetNormalizedTimestamp(self): if self._normalized_timestamp is None: if self._number_of_seconds is not None: self._normalized_timestamp = ( decimal.Decimal(self._deciseconds) / definitions.DECISECONDS_PER_SECOND) self._normalized_timestamp += decimal.Decimal(self._...
[ "def _GetNormalizedTimestamp(self):\n if self._normalized_timestamp is None:\n if self._timestamp is not None:\n self._normalized_timestamp = (\n (decimal.Decimal(self._timestamp) / 100) +\n self._FAT_DATE_TO_POSIX_BASE)\n\n if self._time_zone_offset:\n self._nor...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update all view elements upon receiving "update_view" pub message.
def update_view(self): for row in self.view.obj_list: for obj in row: obj._update(self.model)
[ "def UpdateViews(self):\n \n for eachf in self._listeners:\n eachf(self)", "def UpdateView(self):\n self.View._viewData = self.Model.ModelViewData", "def update_view(self): \n raise NotImplementedError(\"Widget descendents MUST implement the update_view() method!\")",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Kill the active thread upon receiving "thread_finished" pub message.
def thread_finished(self): # self.worker.join() self.worker = None self.want_to_abort = False
[ "def stop_thread(self):\r\n self.thread.active = False\r\n self.thread.join()", "def kill(self):\n if self.thread is not None:\n self.raiseADebug('Terminating job thread \"{}\" and RAVEN identifier \"{}\"'.format(self.thread.ident, self.identifier))\n while self.thread is not None and self.thre...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test recalibration on mean absolute calibration error on the test set for some dummy values.
def test_recal_model_mace_criterion_on_test_set(supply_test_set): test_mace = mean_absolute_calibration_error( *supply_test_set, num_bins=100, vectorized=True, recal_model=None ) test_exp_props, test_obs_props = get_proportion_lists_vectorized( *supply_test_set, num_bins=100, recal_model=Non...
[ "def test_recal_model_rmce_criterion_on_test_set(supply_test_set):\n test_rmsce = root_mean_squared_calibration_error(\n *supply_test_set, num_bins=100, vectorized=True, recal_model=None\n )\n test_exp_props, test_obs_props = get_proportion_lists_vectorized(\n *supply_test_set, num_bins=100, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test recalibration on root mean squared calibration error on the test set for some dummy values.
def test_recal_model_rmce_criterion_on_test_set(supply_test_set): test_rmsce = root_mean_squared_calibration_error( *supply_test_set, num_bins=100, vectorized=True, recal_model=None ) test_exp_props, test_obs_props = get_proportion_lists_vectorized( *supply_test_set, num_bins=100, recal_mode...
[ "def test_energy_calibration(self):\n \n energy_calib_bkg = sp.interpolate_bkg(counts=self.Eu152_spectrum[1])\n \n energy_calib_peaks = sp.fit_spectrum(counts=self.Eu152_spectrum[1],\n expected_peaks=self.energy_calib_peaks['channel'],\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test recalibration on miscalibration area on the test set for some dummy values.
def test_recal_model_miscal_area_criterion_on_test_set(supply_test_set): test_miscal_area = miscalibration_area( *supply_test_set, num_bins=100, vectorized=True, recal_model=None ) test_exp_props, test_obs_props = get_proportion_lists_vectorized( *supply_test_set, num_bins=100, recal_model=N...
[ "def test_optimize_recalibration_ratio_miscal_area_criterion(supply_test_set):\n random.seed(0)\n np.random.seed(seed=0)\n\n y_pred, y_std, y_true = supply_test_set\n miscal_ratio = optimize_recalibration_ratio(\n y_pred, y_std, y_true, criterion=\"miscal\"\n )\n recal_ma_cal = mean_absolut...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test standard deviation recalibration on miscalibration area on the test set for some dummy values.
def test_optimize_recalibration_ratio_miscal_area_criterion(supply_test_set): random.seed(0) np.random.seed(seed=0) y_pred, y_std, y_true = supply_test_set miscal_ratio = optimize_recalibration_ratio( y_pred, y_std, y_true, criterion="miscal" ) recal_ma_cal = mean_absolute_calibration_e...
[ "def test_correct_sd():\n sd_outcome = np.array([[0.0, 0.0], [0.0, 0.0], [2.0, 2.0], [2.0, 2.0]])\n\n assert np.array_equal(std.stdizer(np_data, method=\"sd\"), sd_outcome), \"Output from (stdizer(np_data, method=`sd`..) is incorrect\"\n assert np.array_equal(std.stdizer(df_data, method=\"sd\"), sd_outcome...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test get_std_recalibration on the test set for some dummy values.
def test_get_std_recalibrator(supply_test_set): random.seed(0) np.random.seed(seed=0) y_pred, y_std, y_true = supply_test_set test_quantile_prop_list = [ (0.01, 0.00, 0.00), (0.25, 0.06, 0.00), (0.50, 0.56, 0.00), (0.75, 0.74, 0.56), (0.99, 0.89, 0.88), ] ...
[ "def test_recal_model_rmce_criterion_on_test_set(supply_test_set):\n test_rmsce = root_mean_squared_calibration_error(\n *supply_test_set, num_bins=100, vectorized=True, recal_model=None\n )\n test_exp_props, test_obs_props = get_proportion_lists_vectorized(\n *supply_test_set, num_bins=100, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The reason that we name this function "delete_and_update_priority" instead of "delete" is because, for some reason, Django would not use overriden version of "delete".
def delete_and_update_priority(self): for pbi in PBI.objects.filter(priority__gt=self.priority, project=self.project): pbi.priority -= 1 pbi.save() self.delete()
[ "def before_delete(self):", "def permissions_delete_override(permittee_kw, model_func, delete_perm):\n def delete(self, *args, **kwargs):\n \"\"\"\n Override the default delete method to enforce permissions.\n \"\"\"\n must_have_permission(permittee_kw, self, delete_perm)\n #...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Performs the provided computations and saves them to persistent storage. Next time, when this functions is called, the objects that exist in persistent storage are loaded instead of being computed again. If force_update is true, the computations are performed regardless of whether or not the objects already exist in pe...
def perist_computation(self, computations: List[Tuple], force_update: bool = False) -> List: results = [] for computation, persistence_name in computations: if force_update or self.object_exists(persistence_name) is False: object = computation() self.save_obje...
[ "def update(force = False):\n cso = CSO(load_ontology = False)\n cso.update(force = force)\n \n model = MODEL(load_model = False)\n model.update(force = force)", "def _update_observables(self, force=False):\n for observable in self._observables.values():\n observable.update(timest...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Simulate random cassandra node failure and 'rejoin' into cluster
def simulate_node_failure(node_ips, max_duration, tests_completed): run = True l.info("START Cassandra Node Failure Simulation. Entering.") while run: # If stress-tests are still running continue with node failure simulation if not tests_completed.isSet(): # Select 'random' node ...
[ "def fail_without_replace_test(self):\n debug(\"Starting cluster with 3 nodes.\")\n cluster = self.cluster\n cluster.populate(3)\n node1, node2, node3 = cluster.nodelist()\n cluster.seeds.remove(node3)\n NUM_TOKENS = os.environ.get('NUM_TOKENS', '256')\n if DISABLE_V...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Select a random cassandra node from a list of IPs
def select_random_node(cluster_ips): return random.choice(cluster_ips)
[ "def selectRandomNode(nodes):\n return nodes[selectRandomInt(len(nodes))]", "def _select_node_to_ping(self):\n if self.nodes_to_ping is None:\n random.shuffle(self.expected_remote_members)\n self.nodes_to_ping = itertools.cycle(self.expected_remote_members)\n return self.nod...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Normalize path (like os.path.normpath) for given os. >>> from piecutter.engines.jinja import path_normalize >>> path_normalize('foo/bar') 'foo/bar' >>> path_normalize('foo/toto/../bar') 'foo/bar' Currently, this is using os.path, i.e. the separator and rules for the computer running Jinja2 engine. A NotImplementedError...
def path_normalize(path, target_os=None): if target_os and target_os is not os.name: raise NotImplementedError('Cannot join path with "{target}" style. ' 'Host OS is "{host}".'.format( target=target_os, ...
[ "def _normalize_path(value): # pragma: no cover\n return path.abspath(path.normpath(value))", "def sys_norm_path(path):\n from os.path import normpath\n\n result = None\n try:\n result = normpath(path)\n except Exception as e:\n Pro...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Populate self.environment.globals with some global functions.
def register_environment_functions(self): self.environment.globals['path_join'] = path_join self.environment.globals['path_normalize'] = path_normalize
[ "def update_globals(self, new_globals):\n self.env.globals.update(new_globals)", "def set_lookup_globals(self):\n return", "def load_env_registers(self) -> None:\n self.add_args_to_env(local=True)\n\n fn_info = self.fn_info\n fitem = fn_info.fitem\n if fn_info.is_nested...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a ratio showing whether template looks like using engine. >>> engine = Jinja2Engine() >>> engine.match('', {}) 0.0 >>> engine.match('{ Jinja2 }', {}) 1.0 >>> engine.match('Not shebang { Jinja2 }', {}) 0.0 >>> engine.match('{{ key }}', {}) 0.9
def match(self, template, context): # Try to locate a root variable in template. if template.startswith('{# Jinja2 #}'): return 1.0 if re.search(r'{{ .+ }}', template): return 0.9 return 0.0
[ "def assert_render_matches(template, match_regexp, vars={}):\n r = re.compile(match_regexp)\n actual = Template(template).render(Context(vars))\n ok_(r.match(actual), \"Expected: %s\\nGot: %s\" % (\n match_regexp, actual\n ))", "def _match(a, b):\n return SequenceMatcher(None, a, b).rati...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create Icy with model and tokenizer.
def __init__(self, model, tokenizer): self.model = model self.tokenizer = tokenizer self.max_context_size = max_context self.predict_len = steps self.beam_size = beam_size self.beam_steps = beam_steps
[ "def create_tokenizer() -> keras.preprocessing.text.Tokenizer:\n # Find all captions\n image_ids = annotcoco.getImgIds()\n annotation_ids = capcoco.getAnnIds(imgIds=image_ids)\n annotations = capcoco.loadAnns(annotation_ids)\n captions = [annotation['caption'] for annotation in annotations]\n\n # ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Predict the code complettion candidates from a given context.
def predict(self, context, filepath=None): if len(context.splitlines()) < 5: context = self.get_guide_context(filepath) + context context_ids = self.tokenizer.encode(context) if len(context_ids) <= 1: return None context_ids = context_ids...
[ "def __call__(self, contexts: List[str], questions: List[str], **kwargs) -> Tuple[List[str], List[int], List[float]]:\n batch_indices = []\n contexts_to_predict = []\n questions_to_predict = []\n predictions = {}\n for i, (context, question) in enumerate(zip(contexts, questions)):...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check whether this environment will allow multiprocessing.
def check_multiprocessing(): try: import multiprocessing except ImportError: return False return True
[ "def is_multiprocessing_problematic():\n # Handling numpy linked against accelerate.\n config_info = str([value for key, value in\n np.__config__.__dict__.items()\n if key.endswith(\"_info\")]).lower()\n\n if \"accelerate\" in config_info or \"veclib\" in config_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Apply task_function to each element of task_iterable using a parallel producer/consumer algorithm over nproc processes. Skip over input data where an error occurs.
def parallel_pc(task_function, task_iterable, nproc): import multiprocessing work_queue = multiprocessing.Queue() results_queue = multiprocessing.Queue() loader = get_worker_processes( _load_data, (task_iterable, work_queue, nproc), nproc=1, allow_scalar=True ) ...
[ "def apply_func(\n func: Callable,\n iterator: Iterable,\n parallel: bool = False,\n processes: int = 4,\n) -> List[Any]:\n result = []\n if parallel:\n pool = Pool(processes)\n result = list(\n tqdm(\n pool.imap(func, iterator),\n total=len(i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a set of worker processes for a given function and argument set. If no process count is given, use the CPU count of the current machine. If allow_scalar is set to True, allow this routine to return a single process instead of listoflength1 containing a single process.
def get_worker_processes(f, args, nproc=None, allow_scalar=False): import multiprocessing num_procs = get_num_processors(nproc) workers = [ multiprocessing.Process(target=f, args=args) for _ in range(num_procs) ] if allow_scalar and len(workers) == 1: return workers[0] else: ...
[ "def get_processes(options):\n\n multiprocesses = []\n inputs = []\n outputs = []\n errouts = []\n pargs = []\n\n workloads = options.cmd.split(';')\n if options.input != \"\":\n inputs = options.input.split(';')\n if options.output != \"\":\n outputs = options.output.split(';'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Wrapper function to load the data from the iterable l into queue q, assuming that there will be nproc processes working on the queue. This is the "producer" in the producer/consumer algorithm.
def _load_data(l, q, nproc): for element in l: q.put(element) for _ in range(nproc): q.put(FINISHED)
[ "def prefetch(g: Iterable, size=1) -> Generator:\n coord = {'done': False}\n prefetch_queue = queue.Queue(size)\n\n def fill_prefetch_queue():\n for item in g:\n while not coord['done']:\n try:\n prefetch_queue.put(item, block=True, timeout=0.1)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Wrapper function that will apply the function f to each element of the work queue and place the results in the results queue. This is the "consumer" in the producer/consumer algorithm.
def _process_data(f, work_queue, results_queue): for element in iter(work_queue.get, FINISHED): try: results_queue.put(f(element)) except Exception, work_error: LOG.critical('parallel_pc Error: {0}\n\n\tconfig settings {1}\n'.format(work_error, element)) results_queue.put...
[ "def queue_wrapper(result_queue, wid,\n func, args):\n result_queue.put((wid, func(*args)))", "def collect_results_in_queue(func):\n @wraps(func)\n def func_wrapper(*args, **kwargs):\n results_queue = kwargs.pop('results_queue')\n # Pass args and kwargs as is to the functio...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set up the OpenGL environment.
def setup(self): # Initialize the drawing environment (create main windows, etc) glutInit(sys.argv) glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH) glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT) glutCreateWindow(name) glShadeModel(GL_SMOOTH) glClearDep...
[ "def initgl(self):\r\n # Set the screen background color. \r\n glClearColor( 0.0, 0.0, 0.0, 1.0 )\r\n \r\n # Enable back face culling. \r\n glEnable( GL_CULL_FACE )\r\n \r\n # Initialize viewport and projection. \r\n self.resize()\r\n \r\n # Enable vertex arrays. \r\n glEnableClien...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a segmentlist that is the union of all excitation, segdb and bitmasked channels.
def inj_seg(self, exclude_coinc_flags=None): if exclude_coinc_flags is None: exclude_coinc_flags = [] tmp_list = segments.segmentlist([]) for key in self.exc_dict.keys(): if key[3:] not in exclude_coinc_flags: tmp_list.extend(self.exc_dict[key]) ...
[ "def get_all(self):\n return self._segments", "def getSegments(self):\n segments=[]\n l=len(self.points)\n for j in range(l):\n for i in range(j):\n if self.network[i][j]:\n segment=Segment(self.points[i],self.points[j])\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Logical check that there was only one excitation at the time.
def check_single_excitation(self): if len(self.exc_dict.keys()) != 1: return False for key in self.exc_dict.keys(): if len(self.exc_dict[key]) != 1: return False return True
[ "def check_if_previously_escalated(self, event: EventRecord) -> None:\n with self.session.begin() as session:\n return (\n session.query(EventRecord)\n .filter(EventRecord.fingerprint == event.fingerprint)\n .filter(EventRecord.escalated_at.isnot(None))...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
scrape function starts scraping a channel for its playlists, checks for multiple pages, and returns a list of playlistId for all the playlist of the channel.
def scrape(self): request = self.youtube.playlists().list( part="id,snippet", channelId=self.channelId, maxResults=50) response = request.execute() items = response['items'] for item in items: self.playlists.append(item['id']) if ...
[ "def get_all_playlists(self, channel_id, default_param='snippet,contentDetails'):\n result = {}\n page_token = ''\n while True:\n url = self._create_url(channel_id, 50, page_token, default_param)\n response = requests.get(url)\n if response.status_code == 200:\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns API instance for cloud provider.
def get_api(provider): # TODO(b/167685797): Use thread-local. if provider == storage_url.ProviderPrefix.GCS: return gcs_api.GcsApi() elif provider == storage_url.ProviderPrefix.S3: return s3_api.S3Api() raise ValueError('Provider API value must be "gs" or "s3".')
[ "def Cloud():\n ProviderClass = _find_provider(PROVIDERS)\n return ProviderClass()", "def get_api(self):\n return self.api", "def get_cloud(cls):\n o = cls.get(\"cloud\", cloud=\"general\")\n return o", "def api_client():\n return APIClient()", "def api_conn(self):\n try...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find the value which corresponds to a given quantile, based on a rolling window
def quantile(obj, quantile, window, min_periods=None, interpolation='linear'): return obj.rolling(window=window, min_periods=min_periods).quantile(quantile, interpolation=interpolation)
[ "def quantile_inv(obj, window, min_periods=None):\n return obj.rolling(window=window, min_periods=min_periods).apply(lambda x: stats.percentileofscore(x, x[-1]))", "def compute_rolling_quantile(data, feature, time_window, q=0.75, center=False):\n name = '_'.join([feature, time_window, 'quantile', str(int(q*...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find the quantile which corresponds to a given value, based on a rolling window
def quantile_inv(obj, window, min_periods=None): return obj.rolling(window=window, min_periods=min_periods).apply(lambda x: stats.percentileofscore(x, x[-1]))
[ "def quantile(obj, quantile, window, min_periods=None, interpolation='linear'):\n return obj.rolling(window=window, min_periods=min_periods).quantile(quantile, interpolation=interpolation)", "def compute_rolling_quantile(data, feature, time_window, q=0.75, center=False):\n name = '_'.join([feature, time_win...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the height of the utopian tree after the given number of "cycles"
def get_tree_height(num_cycles): # Base case, at 0 cycles the tree is of height 1 if num_cycles < 1: return 1 # Recursive case 1, in the spring (odd numbered cycles) the tree's height doubles elif num_cycles % 2 == 1: return get_tree_height(num_cycles - 1) * 2 # Recursive case 2, ...
[ "def height(T):\r\n if T.isLeaf:\r\n return 0\r\n return 1 + height(T.child[0])", "def calculate_height(cycle_count):\n growths = cycle([lambda x: x * 2, lambda x: x + 1])\n height = 1\n\n for growth in islice(growths, cycle_count):\n height = growth(height)\n\n return height", "...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the color at index c_ix to the value given by rgb data in threetuple.
def set_color_rgb(self, c_ix, data): if c_ix < 0 or c_ix > 1: print "Don't understand color ix %d" % c_ix return if len(data) < 3: print "Not enough data values to set rgb color: %s" % (str(data)) return self.chosen_colors[c_ix] = (data[0],dat...
[ "def setByValue(self, rgbTuple):\n if not isinstance(rgbTuple, tuple):\n raise TypeError('(r,g,b) tuple expected')\n if len(rgbTuple) != 3:\n raise ValueError('(r,g,b) tuple must have three components')\n for val in rgbTuple:\n if not isinstance(val, (int, float...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
How many friends does _user_ have?
def number_of_friends(user): user_id = user["id"] friend_ids = friendships[user_id] return len(friend_ids)
[ "def number_of_friends(user):\n return len(friendship[user[\"id\"]])", "def number_of_friends(user):\n return len(user[\"friends\"]) # length of friend_ids list", "def number_of_friends(user):\n\tuser_id = user[\"id\"]\n\tfriend_ids = friendships[user_id]\n\treturn len(friend_ids)"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Implementation of AlexNet for Imagenet dataset
def AlexNet_ImageNet(sobel, batch_normalization, device, concat_sobel=False): n_input_channels = 2 + int(not sobel) if not concat_sobel else 5 alexnet_features_cfg = [ { "type": "convolution", "out_channels":96, "kernel_size":11, ...
[ "def imagenet_alexnet(**kwargs):\r\n model = ImageNetAlexNet(**kwargs)\r\n return model", "def get_alex_net(self, pic_size):\n\n from tflearn.layers.core import input_data, dropout, fully_connected\n from tflearn.layers.conv import conv_2d, max_pool_2d\n from tflearn.layers.normalizatio...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
L{eridanus.superfeedr.SuperfeedrService.subscribe} returns a C{Deferred} that is fired once the service is in a ready state.
def test_deferredSubscribe(self): d = self.service.subscribe(u'url', None) @d.addCallback def clientConnected(dummy): pubsubClient = self.service.pubsubClient self.assertIn(u'url', pubsubClient.subscriptions) # This makes d callback. self.assertFalse(d.c...
[ "def subscribe(self):\n res = self._subscribe()\n if res is not None:\n self._subscribed = True\n return res", "def subscribe(self, feed, **args):\n args.update(feed=feed)\n return self.fetch(\"/subscribe\", post_args=args)", "def subscribe(self, subject):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
L{eridanus.superfeedr.SuperfeedrService.itemsReceived} is called when PubSub notifications arrive.
def test_itemsReceived(self): called = [] def cb(url, items): called.append((url, items)) self.service.clientConnected() self.service.subscribe(u'url', cb) event = EventMock( nodeIdentifier=u'url', items=[1, 2]) self.service.pubsubCli...
[ "def itemsReceived(self, url, items):\n callbacks = self._subscribers.get(url, [])\n for callback in callbacks:\n callback(url, items)", "def reliable_item_notifications(self):\n pass", "def event_publish(self, cmd):\n for sub in self.subscribers:\n sub.event_re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parses Beilstein Registry Number data to output a list of dictionaries relating number and SMILES
def reagent_parser(self, filename, initial_dictlist = dict()): results = initial_dictlist filepath = os.path.join(self.base_dir, filename) with open(filepath, 'r') as fileobj: xml = fileobj.read() parsed = BeautifulSoup(xml, "lxml-xml") substances = parsed....
[ "def info(number):\n number = compact(number)\n from stdnum import numdb\n info = {}\n for nr, found in numdb.get('nz/banks').info(number):\n info.update(found)\n return info", "def _convert_flower_data_to_dict(data: str) -> Dict[str, int]:\n flowers = {}\n for max_quantity, sp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Saves list of dicts to a JSON file
def save_to_json(self, dict_list, filename): try: with open(filename + ".json", "w") as outfile: dump(dict_list, outfile) return True except: return False
[ "def save_to_file(cls, list_objs):\n li = []\n with open(cls.__name__ + \".json\", mode=\"w\") as fl:\n if list_objs is None:\n fl.write(Base.to_json_string(list_objs))\n return\n for i in list_objs:\n li.append(i.to_dictionary())\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decorator to specify the minimum SDK version required.
def minimum_required(version): def _minimum_required(func): """Internal decorator that wraps around the given function. Args: func (function): function being decorated Returns: The wrapper unction. """ @functools.wraps(fun...
[ "def require_version(self, version):", "def version_min():\n return VERSION_MIN", "def get_minimum_sdk(self):\n return self.minimum_sdk", "def min_version(minimum_version='2.1'):\n return LooseVersion(version()) >= LooseVersion(minimum_version)", "def get_min_sdk_version(self):\n return ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decorator to specify that the JLink DLL must be opened, and a JLink connection must be established.
def open_required(func): @functools.wraps(func) def wrapper(self, *args, **kwargs): """Wrapper function to check that the given ``JLink`` has been opened. Args: self (JLink): the ``JLink`` instance args: list of arguments to pass to the wr...
[ "def connection_required(func):\n @functools.wraps(func)\n def wrapper(self, *args, **kwargs):\n \"\"\"Wrapper function to check that the given ``JLink`` has been\n connected to a target.\n\n Args:\n self (JLink): the ``JLink`` instance\n args...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decorator to specify that a target connection is required in order for the given method to be used.
def connection_required(func): @functools.wraps(func) def wrapper(self, *args, **kwargs): """Wrapper function to check that the given ``JLink`` has been connected to a target. Args: self (JLink): the ``JLink`` instance args: list of argume...
[ "def require_connection(func):\n def wrapped(self, *args):\n if self.sock == None:\n logging.error(\"Connection not established\")\n else:\n return func(self, *args)\n\n return wrapped", "def driver_needed(func):\n\n def wrapped(self, *args):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decorator to specify that a coresight configuration or target connection is required in order for the given method to be used.
def coresight_configuration_required(func): @functools.wraps(func) def wrapper(self, *args, **kwargs): """Wrapper function to check that the given ``JLink`` has been connected to a target or at least the coresight configuration has been done. Args: self...
[ "def cfgmandatory(func):\n\n # pylint: disable = inconsistent-return-statements\n\n def decorator(*args, **kwargs):\n mandatory = kwargs.pop('mandatory', True)\n try:\n return func(*args, **kwargs)\n except waferror.ConfigurationError:\n if mandatory:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decorator to specify that a particular interface type is required for the given method to be used.
def interface_required(interface): def _interface_required(func): """Internal decorator that wraps around the decorated function. Args: func (function): function being decorated Returns: The wrapper function. """ @functool...
[ "def decorator(fn):\n\n def wrapper(self, *args, **kw):\n \"\"\" Type-checking method wrapper. \"\"\"\n\n actual_args = _validate_args(self, fn, trait_types, args)\n actual_kw = _validate_kw(self, fn, trait_types, kw)\n\n return_value = fn(self, *actual_args, **a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts a register name to a register index
def _get_register_index_from_name(self, register): regs = list(self.register_name(idx) for idx in self.register_list()) if isinstance(register, six.string_types): try: result = regs.index(register) except ValueError: error_message = "No register fo...
[ "def regToInt(name):\n match = re.match(r\"r([0-9]+)\", name)\n if match:\n index = int(match.group(1))\n if 0 <= index <= 15:\n return index\n raise AsmException(\"incorrect register %s\" % name)", "def getRegister(registerName):\n\tspecialRegisterNames = ['pc', 'sp', 'sr', 'cg'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns whether the DLL is open.
def opened(self): return bool(self._dll.JLINKARM_IsOpen())
[ "def is_open(self):\n opened = ctypes.c_bool()\n\n result = self._lib.NRFJPROG_is_dll_open(ctypes.byref(opened))\n if result != NrfjprogdllErr.SUCCESS:\n raise APIError(result)\n \n return opened.value", "def IsOpen(self):\n return self._is_open", "def open(s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns whether a target is connected to the JLink.
def target_connected(self): return self.connected() and bool(self._dll.JLINKARM_IsConnected())
[ "def is_connected(self):\n return bool(self._reference.GetConnectedOutput())", "def isConnected(self) -> bool:\n return nx.is_connected(self.graph)", "def is_connected(self):\n return any(self._reference.GetConnectedInputs().values())", "def is_connected(self):\n connected = False\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the log handler function.
def log_handler(self): return self._log_handler
[ "def get_system_logging_handler(self):\n return None", "def get_logging_handler(args):\n fmt = '[%(levelname)s]%(message)s'\n log_level = args.log_level\n if args.log_level is not None:\n log_level = args.log_level\n if args.verbose:\n log_level = 'INFO'\n if args.quiet:\n l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the detailed log handler function.
def detailed_log_handler(self): return self._detailed_log_handler
[ "def log_handler(self):\n return self._log_handler", "def get_system_logging_handler(self):\n return None", "def detailed_log_handler(self, handler):\n if not self.opened():\n handler = handler or util.noop\n self._detailed_log_handler = enums.JLinkFunctions.LOG_PROTOTYPE(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Setter for the detailed log handler function.
def detailed_log_handler(self, handler): if not self.opened(): handler = handler or util.noop self._detailed_log_handler = enums.JLinkFunctions.LOG_PROTOTYPE(handler) self._dll.JLINKARM_EnableLogCom(self._detailed_log_handler)
[ "def detailed_log_handler(self):\n return self._detailed_log_handler", "def logging(self, fn):\n self._logging = fn", "def set_debug_log_handler(log_function, user_data=None):\n return _librepo.set_debug_log_handler(log_function, user_data)", "def set_logger(self, function):\n self._lo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the error handler function.
def error_handler(self): return self._error_handler
[ "def _get_error_func(self):\n return eval(self._options.error_func)", "def error(self, func):\n self.error_handler = func\n return func", "def error():\n return _ErrorFunction()", "def get_exception_handler(self):\n return code_exception_handler", "def error(self, handler)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Setter for the error handler function. If the DLL is open, this function is a noop, so it should be called prior to calling ``open()``.
def error_handler(self, handler): if not self.opened(): handler = handler or util.noop self._error_handler = enums.JLinkFunctions.LOG_PROTOTYPE(handler) self._dll.JLINKARM_SetErrorOutHandler(self._error_handler)
[ "def error(self, func):\n self.error_handler = func\n return func", "def _set_error_handler(self):\n if self.on_error:\n error_step = self.context.root.path_to_step(self.on_error)\n self._on_error_handler = error_step.run", "def fl_set_error_handler(pyfn_ErrorFunc):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the warning handler function.
def warning_handler(self): return self._warning_handler
[ "def warning_handler(self, handler):\n if not self.opened():\n handler = handler or util.noop\n self._warning_handler = enums.JLinkFunctions.LOG_PROTOTYPE(handler)\n self._dll.JLINKARM_SetWarnOutHandler(self._warning_handler)", "def warning(self, warning):\n pass", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Setter for the warning handler function. If the DLL is open, this function is a noop, so it should be called prior to calling ``open()``.
def warning_handler(self, handler): if not self.opened(): handler = handler or util.noop self._warning_handler = enums.JLinkFunctions.LOG_PROTOTYPE(handler) self._dll.JLINKARM_SetWarnOutHandler(self._warning_handler)
[ "def warning_handler(self):\n return self._warning_handler", "def warning(self, warning):\n pass", "def warning(self, warning):\n\n self._warning = warning", "def svn_fs_set_warning_func(*args):\r\n return _fs.svn_fs_set_warning_func(*args)", "def warning(self) -> None:\n logger...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the number of emulators which are connected via USB to the host.
def num_connected_emulators(self): return self._dll.JLINKARM_EMU_GetNumDevices()
[ "def get_usb_devices_count(self):\n\t\treturn call_sdk_function('PrlVmCfg_GetUsbDevicesCount', self.handle)", "def get_number_of_devices(self):\n return self.drt_manager.get_number_of_devices()", "def get_number_devices(self):\n return len(self.__devices_list)", "def get_count():\n _check_init()\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a list of all the connected emulators.
def connected_emulators(self, host=enums.JLinkHost.USB): res = self._dll.JLINKARM_EMU_GetList(host, 0, 0) if res < 0: raise errors.JLinkException(res) num_devices = res info = (structs.JLinkConnectInfo * num_devices)() num_found = self._dll.JLINKARM_EMU_GetList(host,...
[ "def num_connected_emulators(self):\n return self._dll.JLINKARM_EMU_GetNumDevices()", "def get_simulators(self,online=False):\n teknon_clients = HWIOS.pb_server.get_clients()\n simulators = []\n for client in teknon_clients:\n for service in client.services:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds index of device with chip name
def get_device_index(self, chip_name): index = self._dll.JLINKARM_DEVICE_GetIndex(chip_name.encode('ascii')) if index <= 0: raise errors.JLinkException('Unsupported device selected.') return index
[ "def get_device_index(name):\n dev_list = get_device_list()\n \n for i in range(0, len(dev_list)):\n if name == dev_list[i][\"name\"]:\n return i \n\n raise DRTError(\"Name: %s is not a known type of devices\" % name)", "def device_index(self) -> pulumi.Input[str]:\n return pulumi.get(self, \...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the number of devices that are supported by the opened JLink DLL.
def num_supported_devices(self): return int(self._dll.JLINKARM_DEVICE_GetInfo(-1, 0))
[ "def get_count():\n _check_init()\n return _pypm.CountDevices()", "def get_number_devices(self):\n return len(self.__devices_list)", "def get_number_of_devices(self):\n return self.drt_manager.get_number_of_devices()", "def num_connected_emulators(self):\n return self._dll.JLINKARM_EMU_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Connects to the JLink emulator (defaults to USB). If ``serial_no`` and ``ip_addr`` are both given, this function will connect to the JLink over TCP/IP.
def open(self, serial_no=None, ip_addr=None): if self._open_refcount > 0: self._open_refcount += 1 return None # For some reason, the J-Link driver complains if this isn't called # first (may have something to do with it trying to establish a # connection). With...
[ "def connect_to_device(self):\n result = self._lib.NRFJPROG_connect_to_device()\n if result != NrfjprogdllErr.SUCCESS:\n raise APIError(result)", "def connectArduino(self):\n \n portCom=self.maker.get_portCom()\n \n self.arduino.connect(portCom)", "def connec...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Invalidates the emulator's firmware. This method is useful for downgrading the firmware on an emulator. By calling this method, the current emulator's firmware is invalidated, which will make the emulator download the firmware of the JLink SDK DLL that this instance was created with.
def invalidate_firmware(self): self.exec_command('InvalidateFW') return None
[ "def update_firmware(self):\n self.execute_command(CMD_UPDATE_FIRMWARE)", "def firmware_version(self): # pylint: disable-msg=E0102\n del self._fw_version", "def update_firmware(self) -> str:", "def update_firmware(self):\n return self._dll.JLINKARM_UpdateFirmwareIfNewer()", "def invalid...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Performs a firmware update. If there is a newer version of firmware available for the JLink device, then updates the firmware.
def update_firmware(self): return self._dll.JLINKARM_UpdateFirmwareIfNewer()
[ "def update_firmware(self):\n self.execute_command(CMD_UPDATE_FIRMWARE)", "def update_firmware(self) -> str:", "def performFirmwareUpdate(self, deviceIndex) -> None:\r\n fn = self.function_table.performFirmwareUpdate\r\n error = fn(deviceIndex)\r\n openvr.error_code.FirmwareError.che...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Syncs the emulator's firmware version and the DLL's firmware. This method is useful for ensuring that the firmware running on the JLink matches the firmware supported by the DLL.
def sync_firmware(self): serial_no = self.serial_number if self.firmware_newer(): # The J-Link's firmware is newer than the one compatible with the # DLL (though there are promises of backwards compatibility), so # perform a downgrade. try: ...
[ "def update_firmware(self):\n self.execute_command(CMD_UPDATE_FIRMWARE)", "def update_firmware(self):\n return self._dll.JLINKARM_UpdateFirmwareIfNewer()", "def update_firmware(self) -> str:", "def test_update_hyperflex_server_firmware_version(self):\n pass", "def test_patch_hyperflex_s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enables showing dialog boxes on certain methods.
def enable_dialog_boxes(self): self.exec_command('SetBatchMode = 0') self.exec_command("HideDeviceSelection = 0") self.exec_command("EnableInfoWinFlashDL") self.exec_command("EnableInfoWinFlashBPs")
[ "def OnShowManager(self,event):\n #check if there is an engine\n eng=self.console.get_current_engine()\n if eng is None:\n return\n #show the dialog\n d=PathManDialog(None)\n d.ShowModal()", "def show_gui():\n pass", "def show(self) -> DialogResult:\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Disables showing dialog boxes on certain methods.
def disable_dialog_boxes(self): self.exec_command('SilentUpdateFW') self.exec_command('SuppressInfoUpdateFW') self.exec_command('SetBatchMode = 1') # SuppressControlPanel self.exec_command("HideDeviceSelection = 1") self.exec_command("SuppressControlPanel") # Hid...
[ "def hide_gui():\n pass", "def HidePopups(self):\n if self.AutoCompActive():\n self.AutoCompCancel()\n\n self.CallTipCancel()", "def hideRunDialogs(self):\n self.runsDialog.close()", "def enable_dialog_boxes(self):\n self.exec_command('SetBatchMode = 0')\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clears the DLL internal error state.
def clear_error(self): error = self.error self._dll.JLINKARM_ClrError() return error
[ "def clear_error_state(self):\n lib.ClearErrorValue(self._env)", "def clear_error(self):\n self.got_error = False", "def reset_error_state(self):\n self.error_state = Error.none\n self.error_info = ''", "def reset_error(self):\n\t\t\n\t\tself.error = None", "def clear(self) -> No...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a string specifying the date and time at which the DLL was translated.
def compile_date(self): result = self._dll.JLINKARM_GetCompileDateTime() return ctypes.cast(result, ctypes.c_char_p).value.decode()
[ "def getApplicationBuildDate(self) -> unicode:\n ...", "def build_date(self) -> str:\n data = \"none yet\"\n if self.STARTED:\n data = self.about.get(\"Build Date\", \"UNKNOWN\")\n return data", "def getTimeString():\n\tfrom time import strftime\n\treturn strftime(\"%d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }