query
stringlengths
9
3.4k
document
stringlengths
9
87.4k
metadata
dict
negatives
listlengths
4
101
negative_scores
listlengths
4
101
document_score
stringlengths
3
10
document_rank
stringclasses
102 values
Read stop words from input file (filename) and insert each word as a key into the stop words hash table.
def load_stop_table(self, filename): self.stop_table = HashTable(191) try: a = open(filename, "r") lines = a.readlines() a.close() except: raise FileNotFoundError() for n in range(len(lines)): self.stop_table.insert(lines[n][:-1], n)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def load_stop_table(self, filename):\n self.stop_table = HashTable(191)\n with open(filename, 'r') as f:\n for word in f.readlines():\n self.stop_table.insert(word.replace('\\n',''),None)", "def load_stop_words(stop_word_file):\n stop_words = []\n for line in open(st...
[ "0.7675772", "0.6984068", "0.67051345", "0.65770996", "0.6555971", "0.65203714", "0.6489752", "0.6475122", "0.6467671", "0.6451879", "0.6377066", "0.63083595", "0.63079983", "0.6283576", "0.6268957", "0.6258872", "0.6253571", "0.6214078", "0.61646724", "0.6143819", "0.608474"...
0.69579995
2
Read words from input text file (filename) and insert them into the concordance hash table, after processing for punctuation, numbers and filtering out words that are in the stop words hash table. Do not include duplicate line numbers (word appearing on same line more than once, just one entry for that line)
def load_concordance_table(self, filename): self.concordance_table = HashTable(191) try: a = open(filename, "r") lines = a.readlines() a.close() except: raise FileNotFoundError() for n in range(len(lines)): lone = clean(lines[n]) line = lone.split(" ") for i in line: if (i != None) and (self.stop_table.in_table(i) == False) and (i != ""): self.concordance_table.insert(i, n+1)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def read_text_file(self, filepath: str):\n with open(filepath) as fh:\n for line in fh:\n for word in re.split('\\W+', line):\n word = word.lower()\n if len(word):\n l = self.hash_map.lookup(word)\n ...
[ "0.70385915", "0.6925145", "0.6899971", "0.6768178", "0.6651934", "0.6420912", "0.6312901", "0.6296871", "0.6231026", "0.6214866", "0.62069726", "0.6178269", "0.616501", "0.615068", "0.61372495", "0.6134684", "0.612722", "0.61159056", "0.6110232", "0.6060298", "0.6052872", ...
0.65844196
5
Write the concordance entries to the output file(filename) See sample output files for format.
def write_concordance(self, filename): all_keys = self.concordance_table.get_all_keys() lines = [] for i in all_keys: a = "" a += i + ":" f = self.concordance_table.get_value(i) if f != None: for s in f: a += " " + str(s) a += "\n" lines.append(a) a = open(filename, "w+") for i in lines: a.write(i) a.close()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def write_concordance(self, filename):\n out = ''\n values = [x for x in self.concordance_table.hash_table if x is not None]\n values.sort(key=lambda x: x[0])\n for v in values:\n out += f'{v[0]}: {\" \".join(str(x) for x in sorted(set(v[1])))}\\n' \n with open(filenam...
[ "0.7794726", "0.66742295", "0.64932483", "0.64526165", "0.6379942", "0.63655496", "0.63634735", "0.62910575", "0.6240714", "0.6233921", "0.6233921", "0.6233921", "0.61785156", "0.61412483", "0.61257005", "0.610843", "0.6082861", "0.60720426", "0.6064205", "0.60603034", "0.598...
0.7876976
0
Builds a kfactor circulant matrix (A matrix with the structure of circulant matrices, but with the entries above the diagonal multiplied by the same factor.) The matrix is store in memory.
def factor_circulant_matrix(x, k): n=len(x) return circulant(x) * (tri(n,n, 0) + k*np.transpose(tri(n,n, -1)))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def make_k_matrix(self):\r\n K = self.uv_vol + self.Epsilon * self.guv_vol + \\\r\n (self.Epsilon / self.Beta) * self.uv_bound\r\n return K", "def _K(m):\n M = m*(m - 1)/2\n K = np.zeros((M, m**2), dtype=np.int64)\n row = 0\n for j in range(1, m):\n col = (j - 1)*m + j...
[ "0.6495986", "0.6089255", "0.6045119", "0.59890914", "0.5949488", "0.59035623", "0.5859298", "0.58462423", "0.57634705", "0.574443", "0.5730508", "0.5717386", "0.56819576", "0.566873", "0.5568253", "0.55545205", "0.5523086", "0.55172205", "0.5492196", "0.5491694", "0.5478032"...
0.78092545
0
Compute the matrixvector product y = Cu where C is a kfactor circulant matrix All matrices are real
def factor_circulant_multiplication(u, x, k=1): n = len(u) D_k = (k**(1/n))**np.arange(0,n) Lambda = fft(D_k*x) return (1/D_k)*real(ifft(Lambda*fft(D_k*u))) # y
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def updateC(A, U, B):\n \n m_dim = A.shape[1] \n q_dim = B.shape[0]\n \n C_tensor = np.zeros((m_dim, m_dim, q_dim), dtype=np.complex)\n \n for k in range(q_dim):\n A_k = A[:, :, k]\n b_k = B[k]\n \n x_hat = U @ b_k\n y_hat = A_k.conj().T @ x_hat\n \...
[ "0.6325033", "0.6273725", "0.6251581", "0.62479377", "0.6177961", "0.6087597", "0.6022537", "0.60215706", "0.6020421", "0.60090333", "0.6000697", "0.5998053", "0.59429264", "0.59204763", "0.58713275", "0.5850264", "0.5813686", "0.57964927", "0.57901424", "0.57262236", "0.5726...
0.693636
0
Compute the matrixvector product y = Cu where C is a circulant matrix All matrices are real
def circulant_multiplication(u, a): return real(ifft(fft(a)*fft(u)))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def covar(fx,cx):\n \n fx = np.array(fx)\n cx = np.array(cx)\n \n shape_fx = fx.shape\n shape_cx = cx.shape\n \n \n if shape_fx[1] != shape_cx[0]:\n print('-----------------------------------------')\n print(\"Shapes of fx and cx cannot be multiplied:\")\n print(shap...
[ "0.650418", "0.650212", "0.6441079", "0.6313763", "0.6310517", "0.62949276", "0.62782884", "0.62631303", "0.61975265", "0.6096459", "0.608041", "0.606508", "0.6038961", "0.6011421", "0.60068315", "0.59920776", "0.59303707", "0.58836865", "0.5879482", "0.58772385", "0.58575416...
0.6389226
3
Compute the matrixvector product y = Tu where T is a Toeplitz matrix All matrices are real
def toeplitz_multiplication(u, c, r=None): n = len(u) if r is None: r = c u1 = zeros((2*n)) u1[0:n] = u c = np.concatenate((c, [0], r[-1:0:-1])) y1 = circulant_multiplication(u1, c) return y1[0:n]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def matrix_vector_prod(m,u):\n each_product = []\n for v in m:\n each_product.append(dot_prod(v, u))\n return each_product", "def matmul(x, y):\n if len(list(y.size())) == 2:\n # if one of them is a vector (i.e. wanting to do MV mult)\n z = torch.zeros(2, x.size()[1], dtype=torch...
[ "0.7003199", "0.6513981", "0.64759356", "0.6454179", "0.6377554", "0.6326698", "0.6245358", "0.620894", "0.6208685", "0.61977005", "0.6195611", "0.61694974", "0.6168602", "0.6134469", "0.6106113", "0.60868716", "0.6082444", "0.60823506", "0.6070701", "0.60688484", "0.6063607"...
0.63380134
5
Solves Tx=b using the Levinson algorithm where T is apositivedefinite symmetric Toeplitz matrix b is a real vector
def levinson(r, b): n = len(b) y = zeros((n,)) x = zeros((n,)) # normalize the system so that the T matrix has diagonal of ones r_0 = r/r[0] b_0 = b/r[0] if n == 1: return b_0 y[0] = -r_0[1] x[0] = b_0[0] beta = 1 alpha = -r_0[1] for k in range(0,n-1): beta = (1 - alpha*alpha)*beta mu = (b_0[k+1] - dot(r_0[1:k+2], x[k::-1])) /beta x[0:k+1] = x[0:k+1] + mu*y[k::-1] x[k+1] = mu if k < n-2: alpha = -(r_0[k+2] + dot(r_0[1:k+2], y[k::-1]))/beta y[0:k+1] = y[0:k+1] + alpha * y[k::-1] y[k+1] = alpha return x
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _tridisolve(d, e, b, overwrite_b=True):\n\t\tN = len(b)\n\t\t# work vectors\n\t\tdw = d.copy()\n\t\tew = e.copy()\n\t\tif overwrite_b:\n\t\t\tx = b\n\t\telse:\n\t\t\tx = b.copy()\n\t\tfor k in range(1, N):\n\t\t\t# e^(k-1) = e(k-1) / d(k-1)\n\t\t\t# d(k) = d(k) - e^(k-1)e(k-1) / d(k-1)\n\t\t\tt = ew[ k - 1 ]\n...
[ "0.63466734", "0.61827254", "0.61033237", "0.6093494", "0.60769826", "0.5885008", "0.58844715", "0.5877297", "0.58737326", "0.58588946", "0.5838278", "0.5794063", "0.57753825", "0.5773156", "0.5763559", "0.57562786", "0.574674", "0.57452273", "0.57390094", "0.57179475", "0.56...
0.7257071
0
Compute the log determinant of a positivedefinite symmetric toeplitz matrix. The determinant is computed recursively. The intermediate solutions of the Levinson recursion are expolited.
def toeplitz_slogdet(r): n = len(r) r_0 = r[0] r = np.concatenate((r, np.array([r_0]))) r /= r_0 # normalize the system so that the T matrix has diagonal of ones logdet = n*np.log(np.abs(r_0)) sign = np.sign(r_0)**n if n == 1: return (sign, logdet) # now on is a modification of Levinson algorithm y = zeros((n,)) x = zeros((n,)) b = -r[1:n+1] r = r[:n] y[0] = -r[1] x[0] = b[0] beta = 1 alpha = -r[1] d = 1 + dot(-b[0], x[0]) sign *= np.sign(d) logdet += np.log(np.abs(d)) for k in range(0,n-2): beta = (1 - alpha*alpha)*beta mu = (b[k+1] - dot(r[1:k+2], x[k::-1])) /beta x[0:k+1] = x[0:k+1] + mu*y[k::-1] x[k+1] = mu d = 1 + dot(-b[0:k+2], x[0:k+2]) sign *= np.sign(d) logdet += np.log(np.abs(d)) if k < n-2: alpha = -(r[k+2] + dot(r[1:k+2], y[k::-1]))/beta y[0:k+1] = y[0:k+1] + alpha * y[k::-1] y[k+1] = alpha return(sign, logdet)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def fast_logdet(matrix):\n sign, ld = np.linalg.slogdet(matrix)\n if not sign > 0:\n return -np.inf\n return ld", "def pddet(A):\r\n L = jitchol(A)\r\n logdetA = 2*sum(np.log(np.diag(L)))\r\n return logdetA", "def log_abs_det_jacobian(self, z):\n pre_u = self.u_ + self.u\n ...
[ "0.7205463", "0.69225436", "0.6803772", "0.6577487", "0.65662503", "0.6258033", "0.6235449", "0.6192166", "0.61640286", "0.60718197", "0.602648", "0.5906651", "0.5904567", "0.58784807", "0.58522433", "0.5850299", "0.58452636", "0.5838441", "0.5796368", "0.57808894", "0.577887...
0.6977162
1
Preprocessing needed for toeplitz_inverse_multiplication()
def toeplitz_inverse_multiplication_prep(T_column): phi=1 psi=2 assert phi != 0 assert psi != 0 assert phi != psi n = len(T_column) x = levinson(T_column, np.concatenate( (np.array([1]), np.zeros((n-1,))) ) ) y = levinson(T_column, np.concatenate( (np.zeros((n-1,)), np.array([1])) ) ) x_0 = x[0] D_phi = (phi**(1/n))**np.arange(0,n) D_psi = (psi**(1/n))**np.arange(0,n) Lambda_1 = fft(D_psi*x) Lambda_2 = fft(D_phi*np.concatenate(([phi*y[-1]], y[0:-1]))) Lambda_3 = fft(D_psi*np.concatenate(([psi*y[-1]], y[0:-1]))) Lambda_4 = fft(D_phi*x) return (x_0, phi, psi, D_phi, D_psi, Lambda_1, Lambda_2, Lambda_3, Lambda_4)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def bd_toeplitz_inverse_multiplication_prep(*arrs):\n \n t = []\n for c in arrs: # loop over each block\n t.append(toeplitz_inverse_multiplication_prep(c))\n return tuple(t)", "def toeplitz_inverse_multiplication(u, x_0, phi, psi, D_phi, D_psi, Lambda_1, Lambda_2, Lambda_3, Lambda_4):\n\n y...
[ "0.65743506", "0.63173485", "0.60780877", "0.60345995", "0.5920918", "0.5710167", "0.5684219", "0.56176597", "0.56087387", "0.5590726", "0.5568226", "0.556281", "0.5558012", "0.5548983", "0.5540906", "0.5426001", "0.5426001", "0.5406237", "0.53970987", "0.5395093", "0.5389461...
0.65871215
0
Compute y = inv(T) u Where T is a symmetrix Toeplitz matrix. Requires preprocessing with toeplitz_inverse_multiplication_prep() See Gohberg, I. and V. Olshevsky (1994)
def toeplitz_inverse_multiplication(u, x_0, phi, psi, D_phi, D_psi, Lambda_1, Lambda_2, Lambda_3, Lambda_4): y = fft(D_phi*u) a = Lambda_1*fft(D_psi*(1/D_phi)*ifft(Lambda_2*y)) b = Lambda_3*fft(D_psi*(1/D_phi)*ifft(Lambda_4*y)) y = (1/D_psi)*real(ifft(a-b))/(x_0*(phi-psi)) return y
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def toeplitz_inverse_multiplication_prep(T_column):\n \n phi=1\n psi=2\n assert phi != 0\n assert psi != 0\n assert phi != psi\n \n n = len(T_column)\n \n x = levinson(T_column, np.concatenate( (np.array([1]), np.zeros((n-1,))) ) )\n y = levinson(T_column, np.concatenate( (np.zeros...
[ "0.7413214", "0.7380314", "0.7238792", "0.711224", "0.7110274", "0.70157236", "0.6988002", "0.69570976", "0.69044274", "0.68427217", "0.6829249", "0.68215156", "0.6778755", "0.6680136", "0.6677371", "0.66401356", "0.66035974", "0.6586728", "0.65792894", "0.6540509", "0.651056...
0.7070988
5
Determinant of a blockdiagonal matrix having Toeplitz blocks
def bd_toeplitz_slogdet(*arrs): sign = 1 logdet = 0 for c in arrs: # loop over each block (t_sign, t_logdet) = toeplitz_slogdet(c) sign *= t_sign logdet += t_logdet return (sign, logdet)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _block_diagonal(factor_matrices):\n shapes_dict = {}\n for i, matrix_i in enumerate(factor_matrices):\n for j, matrix_j in enumerate(factor_matrices):\n shapes_dict[(i, j)] = matrix_i.shape[:-1] + matrix_j.shape[-1:]\n rows = []\n # concacatenate along axis = -2\n for i, matrix...
[ "0.6306205", "0.62420654", "0.6225076", "0.62029904", "0.61590856", "0.6147025", "0.61394644", "0.60699403", "0.6061244", "0.60523754", "0.6031275", "0.6016392", "0.6009104", "0.60022414", "0.59936255", "0.59645134", "0.5953049", "0.59515077", "0.5947138", "0.59100145", "0.58...
0.0
-1
Preprocessing for block diagonal matrices analogous to toeplitz_inverse_multiplication_prep()
def bd_toeplitz_inverse_multiplication_prep(*arrs): t = [] for c in arrs: # loop over each block t.append(toeplitz_inverse_multiplication_prep(c)) return tuple(t)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _block_diagonal(factor_matrices):\n shapes_dict = {}\n for i, matrix_i in enumerate(factor_matrices):\n for j, matrix_j in enumerate(factor_matrices):\n shapes_dict[(i, j)] = matrix_i.shape[:-1] + matrix_j.shape[-1:]\n rows = []\n # concacatenate along axis = -2\n for i, matrix...
[ "0.6073989", "0.5890842", "0.57211554", "0.5672026", "0.5595262", "0.5567827", "0.5543956", "0.5539411", "0.5534139", "0.5419887", "0.537693", "0.5354077", "0.5354077", "0.53476894", "0.53476274", "0.52978414", "0.52978414", "0.5297459", "0.5286128", "0.52755713", "0.5268031"...
0.55643
6
matrix multiplication with the inverse of a blockdiagonal matrix having Toeplitz blocks. y = T u Analogous to toeplitz_inverse_multiplication()
def bd_toeplitz_inverse_multiplication(u, *arrs): y = zeros(shape(u)) n_start = 0 n_end = 0 for t in arrs: n_start = n_end n_end += len(t[3]) # len(t[3]) is the length of the block y[n_start:n_end] = toeplitz_inverse_multiplication(u[n_start:n_end], *t) assert len(y) == n_end return y
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def toeplitz_inverse_multiplication_prep(T_column):\n \n phi=1\n psi=2\n assert phi != 0\n assert psi != 0\n assert phi != psi\n \n n = len(T_column)\n \n x = levinson(T_column, np.concatenate( (np.array([1]), np.zeros((n-1,))) ) )\n y = levinson(T_column, np.concatenate( (np.zeros...
[ "0.65371925", "0.6473114", "0.639856", "0.6361315", "0.6302969", "0.6292023", "0.6192051", "0.61344135", "0.61059606", "0.60929507", "0.6069136", "0.6021487", "0.60205114", "0.6011188", "0.5997013", "0.5966648", "0.5926399", "0.5926365", "0.5916658", "0.5888663", "0.5883227",...
0.7164876
0
Parse a single line of csvtoarrow output. Raise RuntimeError if a line cannot be parsed. (We can't recover from that because we don't know what's happening.)
def _parse_csv_to_arrow_warning(line: str) -> I18nMessage: for pattern, builder in _ERROR_PATTERNS: match = pattern.match(line) if match: return builder(**match.groupdict()) raise RuntimeError("Could not parse csv-to-arrow output line: %r" % line)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def parse_line(self, line):\n raise NotImplementedError", "def test_parseLine2(mocker):\n \n # given: setup test framework\n worker = Worker()\n testString = \"11/11/19,Brighter Futures,12000\"\n \n # when:\n result = worker.parseLineCSV(testString)\n \n # then: (Using PyTruth a...
[ "0.6595832", "0.6529445", "0.62704617", "0.61401874", "0.61335003", "0.61316746", "0.61252147", "0.61061907", "0.5982218", "0.5961737", "0.5809438", "0.5809438", "0.5809438", "0.5809438", "0.5806658", "0.5806658", "0.5729117", "0.5704075", "0.5667828", "0.56519485", "0.562726...
0.7278119
0
Return `table`, with final column names but still String values.
def _postprocess_name_columns( table: pyarrow.Table, has_header: bool, settings: Settings ) -> Tuple[pyarrow.Table, List[I18nMessage]]: if has_header and table.num_rows > 0: names, warnings = gen_unique_clean_colnames_and_warn( list((c[0].as_py() if c[0].is_valid else "") for c in table.columns), settings=settings, ) # Remove header (zero-copy: builds new pa.Table with same backing data) table = table.slice(1) else: names = [f"Column {i + 1}" for i in range(len(table.columns))] warnings = [] return ( pyarrow.table(dict(zip(names, table.columns))), warnings, )
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __str__(self):\n\n table_list = [self.headers]\n\n for row in self.data:\n table_list.append([row[col] or \"\" for col in self.headers])\n\n return create_table_string(table_list)", "def _fix_query_table(table):\n for i in table.columns:\n tdtype = table[i].dtype.cha...
[ "0.6711792", "0.64184517", "0.64011616", "0.62590617", "0.6193587", "0.6136157", "0.6058402", "0.6052583", "0.60350543", "0.5984028", "0.5966508", "0.59490246", "0.5942764", "0.5938039", "0.59240717", "0.5916883", "0.5916883", "0.5908916", "0.59033936", "0.5902068", "0.589069...
0.602494
9
Return a pa.Array that replaces "" with null. Assume `arr` is of type `utf8` or a dictionary of `utf8`.
def _nix_utf8_chunk_empty_strings(chunk: pyarrow.Array) -> pyarrow.Array: # pyarrow's cast() can't handle empty string. Create a new Array with # "" changed to null. _, offsets_buf, data_buf = chunk.buffers() # Build a new validity buffer, based on offsets. Empty string = null. # Assume `data` has no padding bytes in the already-null values. That way # we can ignore the _original_ validity buffer and assume all original # values are not-null. (Null values are stored as "" plus "invalid".) # # Validity-bitmap spec: # https://arrow.apache.org/docs/format/Columnar.html#validity-bitmaps # first offset must be 0. Next offsets are used to calculate lengths offsets = array.array("i") assert offsets.itemsize == 4 offsets.frombytes(offsets_buf) if sys.byteorder != "little": offsets.byteswap() # pyarrow is little-endian validity = bytearray() null_count = 0 last_offset = offsets[0] assert last_offset == 0 pos = 1 while True: # Travel offsets in strides of 8: one per char in the validity bitmap. # Pad with an extra 1 bit -- [2020-02-20, adamhooper] I think I read # this is needed somewhere. valid_byte = 0x00 block = offsets[pos : pos + 8] try: if block[0] > last_offset: valid_byte |= 0x1 else: null_count += 1 if block[1] > block[0]: valid_byte |= 0x2 else: null_count += 1 if block[2] > block[1]: valid_byte |= 0x4 else: null_count += 1 if block[3] > block[2]: valid_byte |= 0x8 else: null_count += 1 if block[4] > block[3]: valid_byte |= 0x10 else: null_count += 1 if block[5] > block[4]: valid_byte |= 0x20 else: null_count += 1 if block[6] > block[5]: valid_byte |= 0x40 else: null_count += 1 if block[7] > block[6]: valid_byte |= 0x80 else: null_count += 1 validity.append(valid_byte) last_offset = block[7] pos += 8 except IndexError: validity.append(valid_byte) break # end of offsets validity_buf = pyarrow.py_buffer(validity) # We may have over-counted in null_count: anything before `chunk.offset` # should not count. # # It's less work to "undo" the counting we did before -- otherwise we'd # riddle the above loop with if-statements. for i in range(chunk.offset): if offsets[i + 1] == offsets[i]: null_count -= 1 return pyarrow.StringArray.from_buffers( length=len(chunk), value_offsets=offsets_buf, data=data_buf, null_bitmap=validity_buf, null_count=null_count, offset=chunk.offset, )
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _unicode(arr):\n try:\n return unicode(arr)\n except UnicodeEncodeError:\n dt = arr.dtype.newbyteorder('S')\n return unicode(arr.view(dt))", "def strip_array(arr):\n\n return [word.strip(' ') for word in arr]", "def _strip_all(dic):\n for k, v in dic.items():\n\n if ...
[ "0.6056737", "0.60276425", "0.5736321", "0.56652236", "0.5625485", "0.55626565", "0.5436401", "0.5387418", "0.53866494", "0.53788817", "0.53714484", "0.5352443", "0.53399795", "0.53159595", "0.52804863", "0.5268372", "0.52583706", "0.52422833", "0.5236339", "0.5233802", "0.52...
0.5096824
28
Return true if we should fastskip converting a pa.Array. The _true_ reason for this function is to test whether an Array contains "Inf" or "NaN". A numberconversion library will parse those. But _this_ library is for Workbench, and Workbench doesn't support NaN/Inf. So this function helps us decide _not_ to autoconvert a column when the intent isn't perfectly clear. Assume `arr` is of type `utf8` or a dictionary of `utf8`. Assume there are no gaps hidden in null values in the buffer. (It's up to the caller to prove this.)
def _utf8_chunk_may_contain_inf_or_nan(chunk: pyarrow.Array) -> bool: _, offsets_buf, data_buf = chunk.buffers() offsets = array.array("i") assert offsets.itemsize == 4 offsets.frombytes(offsets_buf) if sys.byteorder != "little": offsets.byteswap() # pyarrow is little-endian offset0 = offsets[chunk.offset] offsetN = offsets[chunk.offset + len(chunk)] # len(offsets) == 1 + len(chunk) b = data_buf[offset0:offsetN].to_pybytes() return SCARY_BYTE_REGEX.search(b) is not None
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def asarray_chkfinite(a):\n a = asarray(a)\n if (a.dtype.char in typecodes['AllFloat']) \\\n and (_nx.isnan(a).any() or _nx.isinf(a).any()):\n raise ValueError, \"array must not contain infs or NaNs\"\n return a", "def is_array(self, arr):\n return isinstance(arr, np.ndarray)", ...
[ "0.63142204", "0.59511065", "0.59251046", "0.5863669", "0.5700599", "0.5661153", "0.5581066", "0.54970616", "0.54685277", "0.54147017", "0.53897524", "0.5384138", "0.53668594", "0.5293467", "0.52856606", "0.527953", "0.5257239", "0.5248469", "0.5248469", "0.5215622", "0.52145...
0.60420185
1
Convert `data` to float64 or int(64|32|16|8); as fallback, return `data`. Assume `data` is of type `utf8` or a dictionary of utf8.
def _autocast_column(data: pyarrow.ChunkedArray) -> pyarrow.ChunkedArray: # All-empty (and all-null) columns stay text for chunk in data.iterchunks(): # https://arrow.apache.org/docs/format/Columnar.html#variable-size-binary-layout _, offsets_buf, _ = chunk.buffers() # If data has an offset, ignore what comes before # # We don't need to grab the _int_ offset: we can just look at the # byte-representation of it. offset_0_buf = offsets_buf[chunk.offset * 4 : (chunk.offset + 1) * 4] # last offset isn't always the last 4 bytes: there can be padding offset_n_buf = offsets_buf[ (chunk.offset + len(chunk)) * 4 : (chunk.offset + len(chunk) + 1) * 4 ] if offset_0_buf.to_pybytes() != offset_n_buf.to_pybytes(): # there's at least 1 byte of text. (Assumes the CSV reader doesn't # pad the buffer with gibberish.) break else: # there are 0 bytes of text return data # Convert "" => null, so pyarrow cast() won't balk at it. sane = pyarrow.chunked_array( [_nix_utf8_chunk_empty_strings(chunk) for chunk in data.iterchunks()] ) for chunk in sane.iterchunks(): # pyarrow cast() uses double-conversion, so it parses "NaN" and "Inf" # as doubles. Workbench doesn't support NaN or Inf, so don't convert to # them. if _utf8_chunk_may_contain_inf_or_nan(chunk): return data try: numbers = sane.cast(pyarrow.float64()) except pyarrow.ArrowInvalid: # Some string somewhere wasn't a number return data # Test that there's no infinity. We'll use numpy. .to_numpy() with # zero_copy_only=False will convert nulls to NaN. That's fine, since we # know `numbers` has no NaN values (because `cast()` would have raised # rather than return a NaN.) for chunk in numbers.iterchunks(): npchunk = chunk.to_numpy(zero_copy_only=False) if np.inf in npchunk or -np.inf in npchunk: # Numbers too large return data # Downcast integers, when possible. # # We even downcast float to int. Workbench semantics say a Number is a # Number; so we might as well store it efficiently. try: # Shrink as far as we can, until pyarrow complains. # # pyarrow will error "Floating point value truncated" if a conversion # from float to int would be lossy. # # We'll return the last _successful_ `numbers` result. numbers = numbers.cast(pyarrow.int32()) numbers = numbers.cast(pyarrow.int16()) numbers = numbers.cast(pyarrow.int8()) except pyarrow.ArrowInvalid: pass return numbers
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def try_float(data):\n try:\n return float(data)\n except (ValueError, TypeError ):\n return data", "def float_from_string(data):\n return float(maybe_number(data))", "def _float(data):\n try:\n return float(data)\n except ValueError as err:\n if data in ('None', 'NA'...
[ "0.748317", "0.69878703", "0.6950177", "0.6709056", "0.6397729", "0.6396958", "0.63965064", "0.6293659", "0.6279694", "0.6161165", "0.61318475", "0.61182475", "0.5992608", "0.596135", "0.5870688", "0.5860507", "0.58470494", "0.58467394", "0.5794232", "0.5766028", "0.5722432",...
0.0
-1
Parse CSV, TSV or other delimiterseparated text file. Raise LookupError for an `encoding` Python cannot handle. Raise UnicodeError when the file simply cannot be read as text. (e.g., a UTF16 file that does not start with a byteorder marker.)
def _parse_csv( path: Path, *, settings: Settings = DEFAULT_SETTINGS, encoding: Optional[str], delimiter: Optional[str], has_header: bool, autoconvert_text_to_numbers: bool, ) -> ParseCsvResult: warnings = [] with contextlib.ExitStack() as ctx: n_bytes = path.stat().st_size if n_bytes > settings.MAX_CSV_BYTES: # We can't simply os.truncate() the input file, because sandboxed code # can't modify input files. truncated_path = ctx.enter_context(tempfile_context(prefix="truncated-")) with path.open("rb") as src, truncated_path.open("wb") as dest: os.sendfile(dest.fileno(), src.fileno(), 0, settings.MAX_CSV_BYTES) path = truncated_path warnings.append( _trans_cjwparse( "csv.truncated_file", "{n_bytes_truncated, one{Truncated # byte} other{Truncated # bytes}} from file (maximum is {max_n_bytes} bytes)", dict( n_bytes_truncated=(n_bytes - settings.MAX_CSV_BYTES), max_n_bytes=settings.MAX_CSV_BYTES, ), ) ) utf8_path = ctx.enter_context(tempfile_context(prefix="utf8-", suffix=".txt")) # raises LookupError, UnicodeError warnings.extend( transcode_to_utf8_and_warn(path, utf8_path, encoding, settings=settings) ) # Sniff delimiter if not delimiter: delimiter = detect_delimiter(utf8_path, settings) with tempfile_context(suffix=".arrow") as arrow_path: # raise subprocess.CalledProcessError on error ... but there is no # error csv-to-arrow will throw that we can recover from. child = subprocess.run( [ "/usr/bin/csv-to-arrow", "--delimiter", delimiter, "--max-rows", str(settings.MAX_ROWS_PER_TABLE), "--max-columns", str(settings.MAX_COLUMNS_PER_TABLE), "--max-bytes-per-value", str(settings.MAX_BYTES_PER_VALUE), utf8_path.as_posix(), arrow_path.as_posix(), ], capture_output=True, check=True, ) warnings.extend(_parse_csv_to_arrow_warnings(child.stdout.decode("utf-8"))) reader = pyarrow.ipc.open_file(arrow_path.as_posix()) raw_table = reader.read_all() # efficient -- RAM is mmapped table, more_warnings = _postprocess_table( raw_table, has_header, autoconvert_text_to_numbers, settings ) return ParseCsvResult(table, warnings + more_warnings)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _read(filename, encodings=['ascii', 'utf-8', 'utf-16', 'latin-1']):\n text = None\n\n for encoding in encodings:\n try:\n f = open(filename, encoding=encoding)\n text = f.read()\n f.close()\n except UnicodeDecodeError:\n f.close()\n except ...
[ "0.6560378", "0.62868285", "0.61147213", "0.6035779", "0.6029811", "0.5926391", "0.5827321", "0.5804859", "0.58034223", "0.5774665", "0.5699063", "0.56861764", "0.56857336", "0.56818", "0.56673634", "0.5613292", "0.56082886", "0.55889183", "0.5518909", "0.5518909", "0.5518909...
0.60616267
3
Initialize your data structure here.
def __init__(self):        self.intervals = []            ### O(len(intervals))    def addNum(self, val: int) -> None:        if(len(self.intervals) == 0):            self.intervals.append([val, val])            return                flag, left = 1, -math.inf        for i, interval in enumerate(self.intervals):            for point in interval:                right = point                if(left == val or right == val):                    return                elif(left < val and right > val):                    if(flag):                        ### merge case                        if(val == left+1 and val == right -1):                            self.intervals[i-1][1] = self.intervals[i][1]                            self.intervals.pop(i)                        elif(val == left+1):                            self.intervals[i-1][1] = val                        elif(val == right-1):                            self.intervals[i][0] = val                        else:                            self.intervals.insert(i, [val, val])                    ### val in one of the existing intervals                    return
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _init_empty(self):\n self._data = []", "def __init__(self):\n self._data = []", "def __init__(self):\n self._data = []", "def __init__(self):\n self._data = []", "def __init__(self):\n self._data = []", "def __init__(self):\n self._data = []", "def __init__...
[ "0.77675813", "0.7644977", "0.7644977", "0.7644977", "0.7644977", "0.7644977", "0.7644977", "0.75942147", "0.7585732", "0.75570554", "0.75295925", "0.75295925", "0.75295925", "0.75295925", "0.75295925", "0.7495997", "0.7495997", "0.7476943", "0.7476324", "0.7476324", "0.74763...
0.0
-1
Clean up any files leftover from past runs with different hyperparameters.
def clean_up(model_path): cmds = ["rm */grad*.pickle", "rm -r checkpoints", "rm */train_len", "rm log_human_read.csv", "rm */log_human_read.csv", "rm -r best_model", "rm */*epoch*"] for cmd in cmds: os.system("cd {} && {}".format(model_path, cmd))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _clean_files(self):\n if self.delfiles & 1:\n ProcUtils.remove(self.okm)\n if self.delfiles & 2:\n ProcUtils.remove(self.hkm)\n if self.delfiles & 4:\n ProcUtils.remove(self.qkm)\n if self.delfiles & 8:\n ProcUtils.remove(self.obc)\n\n ...
[ "0.74296117", "0.7379356", "0.721091", "0.7174838", "0.7121328", "0.7096112", "0.7081824", "0.7073559", "0.7040567", "0.69962186", "0.69456387", "0.69263583", "0.689189", "0.68870115", "0.6879709", "0.68567586", "0.6842316", "0.6828324", "0.6814952", "0.6776448", "0.6773137",...
0.0
-1
Train a model with the current hyperparameters.
def run(job_path, model_path, metric): cmd = (f"cd $NFFDIR/scripts/cp3d/train " f"&& python train_parallel.py {job_path}") os.system(cmd) best_score, best_epoch = parse_score(model_path, metric) return best_score
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def train_model(self, *args, **kwargs):\n self.model.train(self.training, *args, **kwargs)", "def train(self, current_hyper_params):\n train_loss = 0\n train_n_iter = 0\n # Set model to train mode\n self.model.train()\n # Iterate over train data\n print(\"Iteratin...
[ "0.7977213", "0.7823189", "0.77489245", "0.77486706", "0.744381", "0.74099916", "0.74027795", "0.73351485", "0.7293548", "0.72867054", "0.7273446", "0.72411215", "0.7087587", "0.708289", "0.708289", "0.708289", "0.708289", "0.708289", "0.70720506", "0.7064753", "0.70588857", ...
0.0
-1
Update the config information with new dropout values.
def update_dropout(info, dropout, dropout_type, prop_name): if dropout_type == "schnet_dropout": info["model_params"]["schnet_dropout"] = dropout elif dropout_type == "chemprop_dropout": info["model_params"]["cp_dropout"] = dropout elif dropout_type == "readout_dropout": # if it's in the readout layers, find the dropout # layers in the readout dictionary and update them readout = info["model_params"]["readoutdict"] layer_dics = readout[prop_name] for layer_dic in layer_dics: if layer_dic["name"] == "Dropout": layer_dic["param"]["p"] = dropout info["model_params"]["readoutdict"] = {prop_name: layer_dics} elif dropout_type == "attention_dropout": info["model_params"]["boltzmann_dict"]["dropout_rate"] = dropout else: info["model_params"][dropout_type] = dropout
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def conf_update(self):\n pass", "def update(self):\n self.save_config_file()", "def updateConfig(self):\n # Make sure to keep the default values in place.\n if self.newConfig['sensor'] == 0:\n self.newConfig['sensor'] = self.config['sensor']\n if self.newConfig['ca...
[ "0.6544299", "0.63342535", "0.60116196", "0.59151256", "0.5909534", "0.57759255", "0.57704425", "0.5765275", "0.5730661", "0.56408286", "0.5635697", "0.558882", "0.55770063", "0.5571904", "0.5553866", "0.5534613", "0.5478377", "0.546527", "0.5463798", "0.5436312", "0.5427711"...
0.63966775
1
Update the config information with the number of attention heads.
def update_heads(info, heads): info["model_params"]["boltzmann_dict"]["num_heads"] = heads # Concatenate the fingerprints produced by the different heads info["model_params"]["boltzmann_dict"]["head_pool"] = "concatenate" readoutdict = info["model_params"]["readoutdict"] feat_dim = info["model_params"]["mol_basis"] for key, lst in readoutdict.items(): for i, dic in enumerate(lst): if "param" in dic and "in_features" in dic.get("param", {}): # make sure that the input dimension to the readout is equal to # `heads * feat_dim`, where `feat_dim` is the feature dimension # produced by each head readoutdict[key][i]["param"]["in_features"] = feat_dim * heads break info["model_params"]["readoutdict"] = readoutdict
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def update_config(self):\n self.channel_count = self.config_global['channel_count']\n self.pixel_count = self.config_global['pixel_count']\n self.pixel_index_max = self.pixel_count - 1\n self.repeat_count = self.config_global['repeat_count']\n self.repeat_snake = self.config_glob...
[ "0.5661511", "0.5599164", "0.54210174", "0.53882116", "0.5338775", "0.5247799", "0.5247248", "0.5225227", "0.51431704", "0.5058479", "0.49841285", "0.49445143", "0.49379683", "0.48532596", "0.4848556", "0.48481622", "0.4835506", "0.48258802", "0.48030823", "0.48024145", "0.47...
0.5935313
0
Update a general parameter that's in the main info dictionary.
def update_general(info, key, val): info["model_params"][key] = val
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def change_general_param(self, param, val):\n assert param in self.params, '%s is not recognized as a valid parameter' % param\n self.params[param].change_value(val)", "def _paramUpdate(self):\n\n # Update the database attributes accordingly.\n dt.utilities.DB_attrs_save(self.Database...
[ "0.7279819", "0.71316004", "0.70896465", "0.68731415", "0.6845889", "0.68180555", "0.6810109", "0.67108864", "0.6680052", "0.6631445", "0.6597182", "0.6568276", "0.65336627", "0.65146816", "0.64628476", "0.64187586", "0.64153326", "0.63640064", "0.63570213", "0.63570213", "0....
0.7829526
0
Update the config information and save it.
def update_info(job_path, vals, param_names, prop_name): with open(job_path, "r") as f: info = json.load(f) real_names = [] real_vals = [] for param_name, val in zip(param_names, vals): if param_name.startswith("log_"): # if anything starts with "log_" (e.g. "log_schnet_dropout"), # exponentiate its value to get the actual number real_names.append(param_name.replace("log_", "")) real_vals.append(np.exp(val)) else: real_names.append(param_name) real_vals.append(val) # update values for param_type, val in zip(real_names, real_vals): if 'dropout' in param_type: update_dropout(info=info, dropout=val, dropout_type=param_type, prop_name=prop_name) elif param_type == "num_heads": update_heads(info=info, heads=val) elif param_type == "attention_type": info["model_params"]["boltzmann_dict"]["type"] = val else: if param_type not in info["model_params"]: msg = (f"Warning: assuming that {param_type} " "is just a key in `model_params`, but " "it is not currently in `model_params` in " "the config file. If it should be in a " "different location then you will need " "to write a custom function for updating " "it.") fprint(msg) update_general(info, key=param_type, val=val) # save with open(job_path, "w") as f: json.dump(info, f, indent=4, sort_keys=True)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def update(self):\n self.save_config_file()", "def save(self):\n self.__config.sync()\n self.__saved = True\n Logger().debug(\"Configuration saved\")", "def update_config(self, data):\n self.config.data = dict_merge(self.config.data, data)\n self.config.save()", "def...
[ "0.9107356", "0.79640085", "0.77216876", "0.7674935", "0.767021", "0.7651261", "0.7618307", "0.7609429", "0.7594311", "0.75444627", "0.74497473", "0.73920816", "0.7372493", "0.73333156", "0.73213214", "0.72997504", "0.7294209", "0.7274685", "0.72723716", "0.7229026", "0.72210...
0.0
-1
Create a space for `hyperopt`.
def get_space(options, param_types, names): space = {} for i, lst in enumerate(options): param_type = param_types[i] name = names[i] # if categorical, sample one of the options randomly if param_type == "categorical": sample = hp.choice(name, lst) # otherwise sample between the minimum and maximum values elif param_type in ["int", "float"]: min_val = lst[0] max_val = lst[1] if "dropout" in name: if min_val == 0: min_val = 1e-4 low = np.log(min_val) high = np.log(max_val) sample = hp.loguniform(name, low=low, high=high) elif param_type == "float": sample = hp.uniform(name, low=min_val, high=max_val) elif param_type == "int": sample = hp.quniform(name, low=min_val, high=max_val, q=1) space[name] = sample return space
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _build_space(self, param_grid):\n if self.verbose>9:\n 'Building param space...'\n \n _warnings.filterwarnings('ignore')\n \n param_grid = param_grid.copy()\n space = {}\n for key in param_grid.keys():\n params = param_grid[key]\n ...
[ "0.62174714", "0.5995565", "0.59907234", "0.5958852", "0.58709556", "0.5789153", "0.5679872", "0.54301524", "0.5426742", "0.5412645", "0.5411937", "0.535265", "0.53177315", "0.5313377", "0.5309271", "0.52801293", "0.52665275", "0.524695", "0.524695", "0.52416915", "0.5237613"...
0.53067887
15
Save score from a hyperparameter iteration.
def save_score(dic_path, hyperparams, metric, best_score): if os.path.isfile(dic_path): with open(dic_path, "r") as f: score_list = json.load(f) else: score_list = [] score_list.append(hyperparams) score_list[-1].update({metric: best_score}) with open(dic_path, "w") as f: json.dump(score_list, f, indent=4, sort_keys=True)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __call__(self, score, model):\n if self.best_score is None:\n # assign the best score and save the model at the end of the first epoch\n self.best_score = score\n self.save_checkpoint(model)\n elif score < self.best_score + self.delta:\n # if the score ...
[ "0.62541574", "0.61163104", "0.6092135", "0.59902626", "0.5891033", "0.57781833", "0.5758972", "0.5758972", "0.5757687", "0.57543606", "0.5740902", "0.57180816", "0.5717469", "0.5684043", "0.5682911", "0.5615517", "0.5614505", "0.55993366", "0.5589203", "0.55578935", "0.55561...
0.5386014
76
Make objective function that gets called by `hyperopt`.
def make_objective(model_path, param_names, param_types, job_path, prop_name, metric, dic_path): param_type_dic = {name: typ for name, typ in zip(param_names, param_types)} def objective(hyperparams): # clean up model folder from previous interation clean_up(model_path=model_path) # Convert hyperparams from float to int when necessary for key, typ in param_type_dic.items(): if typ == "int": hyperparams[key] = int(hyperparams[key]) # print hyperparameters being used val_str = " " + "\n ".join([f"{key}: {val}" for key, val in hyperparams.items()]) fprint(f"Hyperpameters used this round:\n{val_str}") # update config file, run, get the score, and save vals = [hyperparams[key] for key in param_names] update_info(job_path=job_path, vals=vals, param_names=param_names, prop_name=prop_name) # train the model and get the score best_score = run(job_path=job_path, model_path=model_path, metric=metric) # get the hyperparameter score, given that the aim is # to minimize whatever comes out metric_obj = METRIC_DIC[convert_metric(metric)] hyper_score = -best_score if (metric_obj == "maximize") else best_score # save the score save_score(dic_path=dic_path, hyperparams=hyperparams, metric=metric, best_score=best_score) return hyper_score return objective
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def objective_function(x):\n return x * 1 # change this to our actual function", "def objective(hyperparams): \n global iteration #necessary with a global variable because of implementation from hyperopt. \n iteration += 1\n\n result = run_model(hyperparams, iteration)\n loss = -result #transfo...
[ "0.7482436", "0.73444074", "0.7161457", "0.7161457", "0.6737644", "0.67088556", "0.6661867", "0.66453636", "0.6605384", "0.6507975", "0.6357", "0.6254179", "0.62437993", "0.62437993", "0.62322885", "0.6193143", "0.61185783", "0.6108092", "0.6072014", "0.6065767", "0.60194516"...
0.65957934
9
Save the best parameters from the optimization.
def save_best(dic_path, metric, model_path): # load the scores with open(dic_path, "r") as f: score_list = json.load(f) # get the best parameters objective = METRIC_DIC[convert_metric(metric)] pref = 1 if (objective == "minimize") else (-1) hyper_scores = [pref * score_dic[metric] for score_dic in score_list] best_params = score_list[np.argmin(hyper_scores)] # print the best parameters save_path = os.path.join(model_path, "best_params.json") best_str = "\n ".join([f"{key}: {val}" for key, val in best_params.items()]) fprint(f"Best parameters are {best_str}") fprint(f"Saving to {save_path}") # save them with open(save_path, "w") as f: json.dump(best_params, f, indent=4, sort_keys=True)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def set_optimal_parameters(self):\n # Getting the best trial based on the test errors\n idx = self.trial_losses.index(min(self.trial_losses))\n self.best_trial = self.trial_list[idx]\n self.objective.parse_trial(self.best_trial)", "def optimize_parameters(self):\n pass", "def...
[ "0.6838676", "0.6757881", "0.6757881", "0.6757881", "0.6701749", "0.6567907", "0.6534331", "0.6523155", "0.6520775", "0.6517323", "0.65010434", "0.64957666", "0.6460189", "0.6451601", "0.639737", "0.6354237", "0.63056695", "0.6299728", "0.62912434", "0.62902164", "0.62139994"...
0.6462199
12
Sample hyperparmeters and save scores for each combination.
def main(job_path, model_path, options, num_samples, metric, score_file, param_names, prop_name, param_types, seed, **kwargs): dic_path = os.path.join(model_path, score_file) space = get_space(options=options, param_types=param_types, names=param_names) objective = make_objective(model_path=model_path, param_names=param_names, param_types=param_types, job_path=job_path, prop_name=prop_name, metric=metric, dic_path=dic_path) # sample hyperparameters with the aim to minimize the # result of `objective` fmin(objective, space, algo=tpe.suggest, max_evals=num_samples, rstate=np.random.RandomState(seed)) # save best results save_best(dic_path, metric, model_path)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _sample_hyperparameters(self):\n\t\tconfig = {}\n\t\tfor attr, option in self._config_options.items():\n\t\t\tprint('Sampling', attr)\n\t\t\tconfig[attr] = option.sample()\n\t\treturn config", "def __init__(self):\n self.param_names = []\n self.param_values = []\n self.param_settings = [...
[ "0.62443453", "0.58079064", "0.57170784", "0.57169795", "0.5709108", "0.5601513", "0.55566067", "0.5552902", "0.5533448", "0.5526824", "0.54794496", "0.54682755", "0.544979", "0.5448814", "0.5426104", "0.5412882", "0.541072", "0.5403978", "0.53949046", "0.53916514", "0.538766...
0.0
-1
Construct generalized extreme value distribution. The parameters `loc`, `scale`, and `concentration` must be shaped in a way that supports broadcasting (e.g. `loc + scale` + `concentration` is valid).
def __init__(self, loc, scale, concentration, validate_args=False, allow_nan_stats=True, name='GeneralizedExtremeValue'): parameters = dict(locals()) with tf.name_scope(name) as name: dtype = dtype_util.common_dtype([loc, scale, concentration], dtype_hint=tf.float32) loc = tensor_util.convert_nonref_to_tensor( loc, name='loc', dtype=dtype) scale = tensor_util.convert_nonref_to_tensor( scale, name='scale', dtype=dtype) concentration = tensor_util.convert_nonref_to_tensor( concentration, name='concentration', dtype=dtype) dtype_util.assert_same_float_dtype([loc, scale, concentration]) # Positive scale is asserted by the incorporated GEV bijector. self._gev_bijector = gev_cdf_bijector.GeneralizedExtremeValueCDF( loc=loc, scale=scale, concentration=concentration, validate_args=validate_args) # Because the uniform sampler generates samples in `[0, 1)` this would # cause samples to lie in `(inf, -inf]` instead of `(inf, -inf)`. To fix # this, we use `np.finfo(dtype_util.as_numpy_dtype(self.dtype).tiny` # because it is the smallest, positive, 'normal' number. super(GeneralizedExtremeValue, self).__init__( distribution=uniform.Uniform( low=np.finfo(dtype_util.as_numpy_dtype(dtype)).tiny, high=tf.ones([], dtype=dtype), allow_nan_stats=allow_nan_stats), # The GEV bijector encodes the CDF function as the forward, # and hence needs to be inverted. bijector=invert_bijector.Invert( self._gev_bijector, validate_args=validate_args), parameters=parameters, name=name)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __call__(self, loc=0, scale=1, size=None, **kwargs):\n return super().__call__(loc, scale, size=size, **kwargs)", "def __call__(self, loc=0.0, scale=1.0, size=None, **kwargs):\n return super().__call__(loc, scale, size=size, **kwargs)", "def __call__(self, loc=0.0, scale=1.0, size=None, **kwa...
[ "0.5140067", "0.51391375", "0.51391375", "0.51391375", "0.51391375", "0.51391375", "0.51385653", "0.512212", "0.51002985", "0.5092538", "0.5085862", "0.5006036", "0.49219593", "0.49213806", "0.4891641", "0.48677793", "0.48438725", "0.4842382", "0.48329198", "0.48204932", "0.4...
0.6448586
0
Distribution parameter for the location.
def loc(self): return self._gev_bijector.loc
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def distribution(self) -> str:\n return pulumi.get(self, \"distribution\")", "def loc(self):\n return self.distribution.loc", "def get_distribution_parameters(self):\r\n return \"UNDEFINED\"", "def distribution(self, env):\n pass", "def _handleInput(self, paramInput):\n super()._...
[ "0.65867454", "0.62829775", "0.62012964", "0.59412557", "0.57245076", "0.56689125", "0.5637412", "0.5567886", "0.5564207", "0.55510134", "0.5550806", "0.55264115", "0.5516382", "0.550923", "0.5505646", "0.5505646", "0.5499564", "0.5482442", "0.5477142", "0.54546994", "0.54109...
0.0
-1
Distribution parameter for scale.
def scale(self): return self._gev_bijector.scale
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def scale(self):\n return self.distribution.scale", "def scale_parameter(self):\n return self._scale_parameter", "def get_scale_parameter(self):\n\n shape_in_gamma_func = float(1 + (1 / self._shape_parameter))\n gamma_func = special.gamma(shape_in_gamma_func)\n self._scale_parame...
[ "0.83170885", "0.75846076", "0.7424819", "0.7398855", "0.7397794", "0.704038", "0.7032206", "0.7026145", "0.7016287", "0.69452536", "0.6886023", "0.6884829", "0.68717456", "0.6735917", "0.6735917", "0.67252976", "0.6618296", "0.65950215", "0.65737295", "0.65534216", "0.653268...
0.7008766
9
Distribution parameter for shape.
def concentration(self): return self._gev_bijector.concentration
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __call__(self, shape):\n return np.random.uniform(low=self.minval, high=self.maxval, size=shape)", "def weight(self, shape, name=\"\"):\n return tf.Variable(tf.truncated_normal(shape, stddev=0.1), name=name)", "def __call__(self, shape):\n return np.random.normal(loc=self.mean, scale=s...
[ "0.66089565", "0.61828715", "0.6138457", "0.61047345", "0.60195476", "0.6013357", "0.59687215", "0.5935368", "0.5908499", "0.589005", "0.5882569", "0.5881735", "0.58765745", "0.5872159", "0.5871932", "0.58504355", "0.58504355", "0.58361685", "0.58349097", "0.5757327", "0.5756...
0.0
-1
Processor File Import statements
def get_imports(self) -> str: imports = [ "_ = require('lodash');", "stream = require('stream');", f"const hookRegister = require('./{settings.ARTILLERY_HOOK_FILE}').hookRegister;", f"hook = require('./{settings.ARTILLERY_LIB_FOLDER}/hooks').hook;", f"utils = require('./{settings.ARTILLERY_LIB_FOLDER}/providers');", f"settings = require('./{settings.ARTILLERY_LIB_FOLDER}/settings');", f"StatsCollector = require('./{settings.ARTILLERY_LIB_FOLDER}/statsCollector').StatsCollector;", f"profiles = require('./{settings.ARTILLERY_LIB_FOLDER}/profiles').profiles;", f"influx = require('./{settings.ARTILLERY_LIB_FOLDER}/influx').client;", ] return "\n".join(imports)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def importer():\n pass", "def file_import(self):\r\n\r\n try:\r\n self.process_file_import()\r\n except InputError as ex:\r\n print(ex)\r\n self.file_import()", "def test_import_process(self):\r\n good_file = self._get_file()\r\n imp = Importer(go...
[ "0.72246414", "0.72070956", "0.6955379", "0.6755924", "0.6729011", "0.66933364", "0.6478454", "0.646348", "0.6388376", "0.6222997", "0.61884964", "0.6172685", "0.5980641", "0.59624255", "0.5938535", "0.59262383", "0.59066707", "0.5905204", "0.5884838", "0.58748347", "0.584964...
0.0
-1
Processor File Global statements
def get_global_vars(self) -> str: return templates.GLOBAL_STATEMENTS
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def preprocess_main():", "def process_file(file_name):\n pass # delete this line and replace with your code here", "def pre_processor(self):", "def main():\n processor.custom_config = parse_arguments()\n processor.process()\n logger.info(processor.statistics)\n logger.info(processor.custom_co...
[ "0.6421695", "0.62486196", "0.61764765", "0.5911357", "0.58984786", "0.57821095", "0.5671686", "0.56631225", "0.5623473", "0.56146", "0.5594075", "0.5566961", "0.5538859", "0.5524859", "0.5524859", "0.5524859", "0.5524859", "0.5524859", "0.55061376", "0.5503649", "0.5500372",...
0.0
-1
Construct Artillery YAML configuration
def set_yaml_config(self) -> None: # LT-248: We can pick Artillery Phase configuration from conf file self.yaml_config = { "config": { "target": self.get_swagger_url(), "processor": f"./{self.OUT_FILE}", "phases": [ { "duration": settings.DURATION or 1, "arrivalRate": settings.SPAWN_RATE or 1 } ] }, "scenarios": self.task_set.yaml_flow }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def yamlConfigForParsingPlugins():\n parameters = \"\"\"\njoinPaths: !joinPaths\n - a\n - b\n - \"c\"\nrunPageTemplates: !findRunPageTemplates\n - \"templates\"\nbcrypt: !bcrypt\n bcryptLogRounds: 12\n user: \"pass\"\nbcryptNoUser: !bcrypt\n bcryptLogRounds: 12\n null: null\nsecretKey: !...
[ "0.6141873", "0.6054223", "0.6019494", "0.5994903", "0.59923637", "0.5968164", "0.59273314", "0.57849234", "0.5761136", "0.57510424", "0.57198846", "0.5717234", "0.57150394", "0.5667676", "0.5636936", "0.56257606", "0.55977577", "0.55945677", "0.55880404", "0.55880404", "0.55...
0.69550043
0
Write to YAML and JS files the final constructed configurations
def write_to_file(self, file_name=None, sub_path=None) -> None: super().write_to_file(file_name, settings.ARTILLERY_FOLDER) self.set_yaml_config() self.write_file_to_output( settings.ARTILLERY_YAML, self.yaml_config, append_mode=False, project_sub_folder=settings.ARTILLERY_FOLDER )
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def save(self):\n for p, c in self.configs_:\n c.write(p)", "def _save_configuration_to_yml(self):\n data = self.get_configuration_data()\n timestamp = self.model.timestamp\n with open(os.path.join(CHECKPOINTS_DIR, timestamp, 'config_{}.yml'.format(timestamp)), 'w') as outf...
[ "0.68511325", "0.66506356", "0.6543113", "0.64862216", "0.6447968", "0.6264091", "0.61741364", "0.6169828", "0.61404073", "0.61322165", "0.6058652", "0.604859", "0.60388285", "0.6029666", "0.60256445", "0.60251164", "0.6015038", "0.60138613", "0.6009589", "0.59702086", "0.595...
0.5634283
71
Tell if a person if allergic to the given allergen.
def is_allergic_to(self, allergen): return allergen in self.list
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def is_allergen(self, is_allergen):\n\n self._is_allergen = is_allergen", "def in_garden(obj):\n print(\"Searching the garden's random objects\")\n return obj in _random_objects", "def allergies(self, allergies):\n\n self.logger.debug(\"In 'allergies' setter.\")\n\n self._allergies =...
[ "0.6099033", "0.5558612", "0.5521234", "0.5301362", "0.5294011", "0.5216652", "0.5088434", "0.507583", "0.5070816", "0.50542706", "0.5041537", "0.50312674", "0.49993923", "0.49899283", "0.49749395", "0.49660623", "0.49616873", "0.49227342", "0.49170405", "0.49064264", "0.4897...
0.77161974
0
Initialise an allergy storage with the given allergy score.
def __init__(self, score): self.score = score self.list = [candidate[0] for candidate in self._allergens if candidate[1] & self.score]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _krls_init(self, iALDth=1e-4, iMaxDict=1e3):\n \n dAldKRLS = {} # Initialize dictionary with data for aldkrls algorithm\n \n # Store all the parameters in the dictionary\n dAldKRLS['iALDth'] = iALDth; # ALD threshold\n dAldKRLS['iMaxDt'] = iMaxDict; # M...
[ "0.5347252", "0.5322024", "0.5263044", "0.5225015", "0.5212653", "0.51022935", "0.5069073", "0.50057083", "0.50024194", "0.49871403", "0.49801096", "0.49767306", "0.49670827", "0.49553522", "0.4951048", "0.49419042", "0.4933451", "0.48849487", "0.48819917", "0.48739007", "0.4...
0.5045687
7
Gets the header of the explog.yml file. the returned text is as below.
def getExplogHeader(FolderID, NumberofExps): HeaderLines = [] HeaderLines.append("ExpFolderID: {ExpDirID}".format(ExpDirID=FolderID)) HeaderLines.append("NumberofEntries: {NumExps}".format(NumExps=NumberofExps)) HeaderLines.append("ExpEntries: ") return "\n".join(HeaderLines)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_header():\n try:\n yml_iter = cfg.yml_config[\"header\"]\n except:\n # Probably no \"comments\" section in the yml-file.\n return \"\"\n\n return (\"\\n\".join(yml_iter) + \"\\n\\n\") if yml_iter is not None else \"\\n\"", "def _get_compose_header(ctx):\n return get_artif...
[ "0.76283085", "0.68693167", "0.6808511", "0.65722984", "0.6551671", "0.654237", "0.639567", "0.6334269", "0.62707156", "0.6265091", "0.62361425", "0.62100714", "0.618234", "0.617842", "0.61768436", "0.61641693", "0.6152005", "0.61499393", "0.61389565", "0.6129883", "0.6125649...
0.62574416
10
This returns a single entry corresponding to the Directory Entity referred to by FolderEntityData. The returned string is given below (between Start and End) Start
def getFolderEntry(FolderEntityData): if FolderEntityData.Type not in ['IntermediateDir', 'ExperimentDir']: errprint('\nThe given EntityData does not represent the data of a directory') raise ValueError OutputLines = [] OutputLines.append("FolderID : {UID}".format(UID=FolderEntityData.ID)) OutputLines.append("ParentFolderID : {UID}".format(UID=FolderEntityData.ParentID)) OutputLines.append("FolderType : {Type}".format(Type=FolderEntityData.Type)) OutputLines.append("FolderTitle : {Title}".format(Title=FolderEntityData.Title)) OutputLines.append("FolderDescription: |-2") OutputLines += [" "+Line for Line in FolderEntityData.Description.splitlines()] OutputLines.append("") return "\n".join(OutputLines)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def getFolderItemName(self) -> unicode:\n ...", "def getFolderPath(self) -> unicode:\n ...", "def directory_id(self) -> pulumi.Output[str]:\n return pulumi.get(self, \"directory_id\")", "def get(self):\n return self.directory_name", "def metadataDirectory(self):\n guid_ha...
[ "0.5994919", "0.56029546", "0.5287925", "0.52766377", "0.5237696", "0.52345103", "0.5213454", "0.5185664", "0.517336", "0.51614946", "0.51094973", "0.51090777", "0.50988936", "0.50865364", "0.50664777", "0.5054286", "0.50433457", "0.5036197", "0.50105923", "0.4974974", "0.497...
0.7627963
0
This returns a single entry corresponding to the Experiment Entity referred to by ExpEntityData. The returned string is given below (between Start and End) Start
def getExperimentEntry(ExpEntityData): # Validate that ExpEntityData actually corresponds to an Experiment Entity if ExpEntityData.Type != 'Experiment': errprint("\nThe Entity Data does not represent the data of an experiment") raise ValueError OutputLines = [] OutputLines.append("") OutputLines.append("- ID : {ID}".format(ID=ExpEntityData.ID)) OutputLines.append(" Title : {Title}".format(Title=ExpEntityData.Title)) OutputLines.append(" Description: |-2") OutputLines += [" "+Line for Line in ExpEntityData.Description.splitlines()] OutputLines.append("") OutputLines.append( "{0:#<100}".format("## End of Experiment {UID} ".format(UID=ExpEntityData.ID))) return "\n".join(OutputLines)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _get_full_entity(entity: spacy.tokens.Token) -> str:\n entity_string = SpacyEventExtractor._get_chunk(entity)\n\n word = entity\n while True:\n prep, word = SpacyEventExtractor._get_prep_with_word(word)\n if word is None:\n break\n entity_str...
[ "0.6376407", "0.5688458", "0.56678385", "0.5637462", "0.5474638", "0.5404834", "0.5358794", "0.53286546", "0.5274664", "0.5274664", "0.52555805", "0.5246036", "0.51556396", "0.51428646", "0.51405764", "0.51387566", "0.51039517", "0.5103533", "0.5092884", "0.5080785", "0.50753...
0.81062454
0
a constructor for an EmployeeAccess object
def __init__(self): self.dbconnect = dbConnection.connection
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __init__(self, employee_id, name, supervisor_id, lft, rgt):\n self.employee_id = employee_id\n self.name = name\n self.supervisor_id = supervisor_id\n self.lft = lft\n self.rgt = rgt", "def __init__(self,name,empid,designation,experience):\n self.name = name\n ...
[ "0.6591341", "0.65801567", "0.616899", "0.61554563", "0.6011643", "0.5887966", "0.58608353", "0.58440644", "0.5821259", "0.581591", "0.5810037", "0.5808263", "0.57878995", "0.57751787", "0.57714325", "0.57638586", "0.57473", "0.5722684", "0.5716975", "0.57147384", "0.5699858"...
0.0
-1
get all the employees out of the database
def get_employees(self): from Employee import Employee cursor = self.dbconnect.get_cursor() cursor.execute('select * from employee') employees = list() for row in cursor: employee = Employee(row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8]) employees.append(employee) return employees
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get(self):\n resultado = EmployeeModel.query.all()\n return resultado", "def get_employees(self, active_only):\n cursor = self.dbconnect.get_cursor()\n\n if active_only:\n cursor.execute(\n 'SELECT id, name, email, office, extra_info, picture_location, re...
[ "0.7986589", "0.78798616", "0.7810305", "0.7761145", "0.771737", "0.7529015", "0.7422921", "0.722801", "0.7137951", "0.71137774", "0.7091648", "0.7014968", "0.6984071", "0.6906787", "0.6850874", "0.67577934", "0.6755647", "0.67153805", "0.66789347", "0.6564769", "0.65336215",...
0.8586788
0
this function gets all the admins from the database
def get_admins(self): from Employee import Employee admins = list() cursorRoles = self.dbconnect.get_cursor() cursorRoles.execute('select * from employeeRoles where role=\'admin\'') for row in cursorRoles: admins.append(self.get_employee(row[0])) return admins
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_admins():\n users = get_users()\n admins = []\n for user in users:\n if user[\"approval_level\"] == \"admin\":\n admins.append(user)\n\n return admins", "def get_admins(name):\n obj = DataService.objects(name=name).first()\n if obj is None:\n return []\n retu...
[ "0.77166426", "0.76271695", "0.76095897", "0.7580871", "0.75705355", "0.7568923", "0.74572515", "0.7428086", "0.7204757", "0.7203195", "0.7175435", "0.70761865", "0.70348865", "0.70129657", "0.69840354", "0.6977274", "0.69340014", "0.6931243", "0.6885563", "0.6853746", "0.684...
0.81468296
0
gets a single employee out the database on an id
def get_employee(self, id): from Employee import Employee cursor = self.dbconnect.get_cursor() cursor.execute('SELECT * FROM employee WHERE employeeID=%s ', (id,)) row = cursor.fetchone() return Employee(row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8])
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get(self, id):\n resultado = EmployeeModel.query.filter_by(employee_id=id).first()\n if resultado:\n return resultado\n api.abort(404)", "def get(id_: int):\n logger.debug('Retrieving employee by id %i.', id_)\n try:\n query = db.session.query(Employee)\n e...
[ "0.8462909", "0.8436909", "0.8286135", "0.8277989", "0.795276", "0.7786417", "0.75786275", "0.7489491", "0.7484681", "0.73151207", "0.7233033", "0.6973724", "0.6964095", "0.6891466", "0.68717116", "0.6806852", "0.66826135", "0.6661457", "0.6648924", "0.6645056", "0.66137886",...
0.8603124
0
gets a single employee out the database on a name
def get_employeeOnName(self, name): from Employee import Employee cursor = self.dbconnect.get_cursor() cursor.execute('SELECT * FROM employee WHERE name=%s ', (name,)) if (cursor.rowcount != 0): row = cursor.fetchone() return Employee(row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8]) else: return None
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_employee_by_name(self, name):\n cursor = self.dbconnect.get_cursor()\n cursor.execute('SELECT id, name, email, office, extra_info, picture_location, research_group, title, is_external,'\n ' is_admin, is_active FROM employee WHERE name=%s', (name,))\n row = cursor....
[ "0.75500387", "0.7348031", "0.7300037", "0.72360134", "0.7058836", "0.7009213", "0.6654517", "0.66495013", "0.66377455", "0.65564954", "0.6541405", "0.6435797", "0.6376785", "0.6338932", "0.61743134", "0.61031044", "0.60764945", "0.60599095", "0.59950364", "0.5983809", "0.597...
0.8025803
0
adds an employee to the database
def add_employee(self, empl): cursor = self.dbconnect.get_cursor() try: cursor.execute('INSERT INTO employee values(default,%s,%s,%s,%s,%s,%s,%s,%s)', (empl.name, empl.email, empl.office, empl.research_group, empl.title, empl.internOrExtern, empl.active, empl.promotor)) cursor.execute('SELECT LASTVAL()') eid = cursor.fetchone()[0] empl.id = eid # get id and return updated object self.dbconnect.commit() except(Exception, self.dbconnect.get_error()) as error: self.dbconnect.rollback() raise Exception('\nUnable to save Employee!\n(%s)' % (error))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def add_employee(self, obj):\n cursor = self.dbconnect.get_cursor()\n try:\n cursor.execute('INSERT INTO employee(id, name, email, office, extra_info, picture_location, research_group, '\n 'title, is_external, is_admin, is_active) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s...
[ "0.8205563", "0.7556254", "0.74963003", "0.74677837", "0.74195415", "0.71267223", "0.7027136", "0.68783706", "0.6761403", "0.6604914", "0.6410982", "0.63886535", "0.6380282", "0.6344615", "0.6239359", "0.6239359", "0.6229492", "0.6211725", "0.618129", "0.61335653", "0.6131431...
0.7959675
1
removes an emplouee out the database
def remove_employee(self, id): cursor = self.dbconnect.get_cursor() try: cursor.execute('DELETE FROM employee WHERE employeeID=%s', (id,)) self.dbconnect.commit() except(Exception, self.dbconnect.get_error()) as error: self.dbconnect.rollback() raise Exception('\nUnable to remove Employee!\n(%s)' % (error))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def delete():", "def remove():\n\n db_remove()", "def remove(name):\n del person_database[name]", "def remove_data(self):\n db.session.delete(self)\n db.session.commit( )", "def remove():", "def remove(self):", "def delete(self, name):\n if name in self._dict:\n se...
[ "0.67720187", "0.67416126", "0.66954815", "0.6653715", "0.6581915", "0.65473205", "0.65393317", "0.6538599", "0.6497466", "0.6485631", "0.6443768", "0.6437587", "0.6437587", "0.6437587", "0.6437587", "0.64256126", "0.6419886", "0.64053607", "0.6392454", "0.6385016", "0.636547...
0.6492649
9
does a filter on all the employees in the database
def filter_employees(self, searchQuery="", researchGroup="", promotor=0, ): from Employee import Employee try: cursor = self.dbconnect.get_cursor() sql = 'select * from employee e INNER JOIN researchGroup r ON r.groupID=e.researchGroup WHERE ' \ 'e.name LIKE %(searchQueryQ)s' if researchGroup != "": sql += "AND r.name = %(researchGroupQ)s" if promotor == 1: sql += 'AND e.promotor = TRUE' if promotor == 2: sql += 'AND e.promotor = FALSE' cursor.execute(sql, dict(searchQueryQ="%" + searchQuery + "%", researchGroupQ=researchGroup)) employees = list() for row in cursor: employee = Employee(row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8]) employees.append(employee) return employees except: self.dbconnect.rollback() raise Exception('unable to filter employees')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def show_all_employees(self):\n try:\n employees = self.admin_repository.show_all_employees()\n if employees:\n for employee in employees:\n print(\"Employee Id : {}\".format(employee[0]))\n print(\"Name : {}\".format(employee[1]))\n...
[ "0.6927609", "0.6896321", "0.6624646", "0.6393193", "0.63894564", "0.6377485", "0.63540703", "0.6346314", "0.62784153", "0.6278148", "0.6203518", "0.6151426", "0.61103714", "0.6102392", "0.60782236", "0.60275084", "0.5902977", "0.58386964", "0.5763383", "0.5734938", "0.573440...
0.6596226
3
adds a role to an employee
def add_employeeRole(self, id, role): cursor = self.dbconnect.get_cursor() try: cursor.execute('INSERT INTO employeeRoles values(%s,%s)', (id, role)) # get id and return updated object self.dbconnect.commit() except(Exception, self.dbconnect.get_error()) as error: self.dbconnect.rollback() raise Exception('\nUnable to save EmployeeRole!\n(%s)' % (error))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def add_role():\n role = roles.find_or_create_role(request.values.get('role_name', ''))\n user = users.get_or_404(int(request.values.get('user_id', '')))\n if not users.add_role_to_user(user, role):\n return {}, 500\n return {}", "def test_add_role(self):\n pass", "def add_role(role):...
[ "0.7416667", "0.73289865", "0.72949153", "0.72568375", "0.7244213", "0.71598387", "0.7032163", "0.699969", "0.6978381", "0.69690233", "0.6907972", "0.68849903", "0.687573", "0.6826044", "0.6823985", "0.6823678", "0.67929417", "0.67829245", "0.6731767", "0.6684479", "0.6680996...
0.80732065
0
gets al the roles of an employee
def get_employeeRoles(self, id): cursor = self.dbconnect.get_cursor() cursor.execute('select * from employeeRoles where employee=%s', (id,)) roles = list() for row in cursor: roles.append(row[1]) return roles
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_roles(role):", "def getRoles(self):", "def getRoles(self):\n return [self.getRole(), {\"roleName\":\"policajti\", \"roleTitle\":\"Svestky\"}]", "def roles(self):\n params = {\n \"f\" : \"json\"\n }\n uURL = self._url + \"/roles\"\n return self._con.get(path=u...
[ "0.7949602", "0.77490324", "0.7219508", "0.7100693", "0.70895886", "0.70715743", "0.6987245", "0.6968574", "0.6919542", "0.6890405", "0.6882044", "0.6865154", "0.6842712", "0.67842984", "0.67706275", "0.67660475", "0.6756659", "0.673916", "0.6718372", "0.6637145", "0.66315967...
0.81541693
0
changes the data of an employee
def change_employee(self, employee): cursor = self.dbconnect.get_cursor() try: if employee.id == None: raise Exception('no id given') cursor.execute('select * from employee where employeeID=%s', (str(employee.id),)) if cursor.rowcount == 0: raise Exception('no employee found with that id') cursor.execute( 'update employee set name= %s,email= %s,office= %s,title= %s,INTernORextern= %s,active= %s,promotor= %s where employeeID=%s', (employee.name, employee.email, employee.office, employee.title, employee.internOrExtern, employee.active, employee.promotor, employee.id)) self.dbconnect.commit() except: self.dbconnect.rollback() raise Exception('unable to change employee')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def update_employee(self, obj):\n cursor = self.dbconnect.get_cursor()\n try:\n cursor.execute('UPDATE employee '\n 'SET name = %s, email = %s, office = %s, extra_info = %s, picture_location = %s, '\n 'research_group = %s, title = %s, is_...
[ "0.7302678", "0.718177", "0.7112663", "0.7027216", "0.7005247", "0.68823713", "0.6850561", "0.67905223", "0.6775437", "0.6432232", "0.6327525", "0.6219686", "0.61889017", "0.6159903", "0.61581737", "0.6071851", "0.60707927", "0.597288", "0.5945182", "0.58981615", "0.5867029",...
0.7703579
0
get all the projects of an employee IMPORTANT not all fields will be completed only the fields in the project table and that of the activeYears
def get_employeeProjects(self, id): from Project import Project cursor = self.dbconnect.get_cursor() cursor.execute('select project from projectpromotor where employee=%s', (id,)) projectsId = list() for row in cursor: projectsId.append(row[0]) projects = list() for projId in projectsId: cursor.execute('select * from project where projectID=%s', (projId,)) # returns exactly one row from the table row = cursor.fetchone() project = Project(row[0], row[1], row[2], row[3]) cursor.execute('select year from projectYearConnection where projectID=%s', (projId,)) years = list() for row in cursor: years.append(row[0]) project.activeYear = years projects.append(project) return projects
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_projects():\n if current_user.get_id() is None:\n return\n with database.engine.begin() as connection:\n result = connection.execute(select(\n [models.projects.c.project_id, models.projects.c.name, models.projects.c.path, models.projects.c.creation_date, models.projects.c.use...
[ "0.6504841", "0.6427155", "0.6327203", "0.6314313", "0.6288553", "0.62257266", "0.62068164", "0.6192607", "0.6165686", "0.6157085", "0.6130755", "0.61147606", "0.61008775", "0.60764706", "0.60260594", "0.60055494", "0.5962676", "0.5942284", "0.5927183", "0.58933854", "0.58909...
0.72116566
0
Relative Strength Index Is a momentum indicator, measuring the magnitude of recent price changes. 70 is overbought 30 is oversold
def RelativeStrengthIndex(self, timeperiod=14): return ta.RSI(self.data.close,timeperiod)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def calculateRelativeStrengthIndex(self, series, interval=14):\n\n if not isinstance(series, pd.Series):\n raise TypeError('Pandas Series required.')\n\n if not isinstance(interval, int):\n raise TypeError('Interval integer required.')\n\n if(len(series) < interval):\n ...
[ "0.6922888", "0.6838217", "0.6272428", "0.61821586", "0.5993364", "0.5774363", "0.5760759", "0.5744267", "0.57409", "0.5716144", "0.5701222", "0.57010186", "0.56948054", "0.5676221", "0.56436366", "0.5643337", "0.5643337", "0.5614214", "0.55853677", "0.55841684", "0.5581936",...
0.655698
2
MACD Moving Average Convergence/Divergence
def MovingAverageConvergenceDivergence(self, fastperiod=12, slowperiod=26,signalperiod=9): df = pd.DataFrame() df['macd'], df['signal'], df['history'] = ta.MACDFIX(self.data.close, 9) return df[-30:]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def computeMACD(x, slow=26, fast=12):\n emaslow = ExpMovingAverage(x, slow)\n emafast = ExpMovingAverage(x, fast)\n return emaslow, emafast, emafast - emaslow", "def computeMACD(x, slow=26, fast=12):\n emaslow = ExpMovingAverage(x, slow)\n emafast = ExpMovingAverage(x, fast)\n return (emaslow, ...
[ "0.6501676", "0.64562273", "0.6412754", "0.61223274", "0.6114551", "0.6047385", "0.5973728", "0.5865776", "0.5864788", "0.5819191", "0.575621", "0.5704251", "0.5700242", "0.5680569", "0.56672055", "0.56551254", "0.56424147", "0.56197876", "0.5551434", "0.5538618", "0.553018",...
0.56003624
18
The Simple Moving Average (SMA) is calculated by adding the price of an instrument over a number of time periods and then dividing the sum by the number of time periods. The SMA is basically the average price of the given time period, with equal weighting given to the price of each period. Simple Moving Average SMA = ( Sum ( Price, n ) ) / n
def SimpleMovingAverage(self, timeperiod = 14): return ta.SMA(self.data.close,timeperiod)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def SMA(serie, n):\r\n\r\n return serie.rolling(window=n).mean()", "def get_SMA(values, window=20):\n\treturn values.rolling(window, center=False).mean()", "def sma(matrix, interval):\n\n # declare empty SMA numpy array\n s = np.zeros((matrix.shape[0] - interval))\n\n # calculate the value of each ...
[ "0.7370013", "0.73070514", "0.72123134", "0.72123134", "0.71889323", "0.71044785", "0.69947493", "0.6878451", "0.6826726", "0.67439926", "0.6694565", "0.6685296", "0.6657218", "0.6633062", "0.6631047", "0.6587248", "0.6556056", "0.6541206", "0.6492296", "0.64602447", "0.64139...
0.8110601
0
Average True Range Is a lagging indicator, used to provide insights into volatility.
def AverageTrueRange(self, timeperiod = 14): return ta.ATR(self.data.high, self.data.low, self.data.close, timeperiod)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def average_true_range(self, period=14):\n tr = self._true_range_computation(period=period * 2)\n return pd.Series(tr.rolling(center=False, window=period,\n min_periods=period - 1).mean(),\n name='{} day ATR Ticker: {}'.format(period,\n ...
[ "0.6600089", "0.6148675", "0.6051582", "0.59976155", "0.57290894", "0.5724756", "0.5678576", "0.56369007", "0.55565417", "0.5463608", "0.5455246", "0.5452944", "0.54398197", "0.5430366", "0.5412434", "0.53751826", "0.5327749", "0.5327182", "0.5326094", "0.52998155", "0.527575...
0.6382062
1
Average True Range Is a lagging indicator, used to provide insights into volatility.
def AverageTrueRangeStopLoss(self, timeperiod = 14, multiplier = 2): stopLoss = ta.ATR(self.data.high, self.data.low, self.data.close, timeperiod) plus_dm = ta.PLUS_DM(self.data.high,self.data.low, timeperiod) minus_dm = ta.MINUS_DM(self.data.high,self.data.low, timeperiod) if plus_dm > minus_dm: stopLoss = self.data.close - multiplier * stopLoss else: stopLoss = self.data.close + multiplier * stopLoss stopLoss.dropna(inplace=True) return stopLoss
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def average_true_range(self, period=14):\n tr = self._true_range_computation(period=period * 2)\n return pd.Series(tr.rolling(center=False, window=period,\n min_periods=period - 1).mean(),\n name='{} day ATR Ticker: {}'.format(period,\n ...
[ "0.6598846", "0.6380403", "0.61479884", "0.6053863", "0.59975517", "0.57305396", "0.56783205", "0.56357294", "0.5556505", "0.54646796", "0.54572976", "0.54534125", "0.5439065", "0.54316556", "0.5413024", "0.53748345", "0.5328688", "0.53281933", "0.532751", "0.5298861", "0.527...
0.5725855
6
100 LOG10( SUM(ATR(1), n) / ( MaxHi(n) MinLo(n) ) ) / LOG10(n) n = User defined period length. LOG10(n) = base10 LOG of n ATR(1) = Average True Range (Period of 1) SUM(ATR(1), n) = Sum of the Average True Range over past n bars MaxHi(n) = The highest high over past n bars
def ChoppinessIndex(self, timeperiod = 14): return ta.C
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def ATR(df, n):\n HML = abs(df['High'] - df['Low'])\n HMPC= abs(df['High'] - df['Close'].shift(1))\n LMPC= abs(df['Low'] - df['Close'].shift(1))\n TR = pd.concat([HML, HMPC, LMPC], axis=1).max(axis=1, skipna=False)\n return TR.rolling(n).mean()", "def ATR(stockData , ticker, n):\n start = dt....
[ "0.63604623", "0.629991", "0.6296152", "0.61950475", "0.605709", "0.5966973", "0.5952976", "0.59012014", "0.5847547", "0.5821448", "0.5785486", "0.575912", "0.5732089", "0.5712802", "0.5695987", "0.5627515", "0.5604428", "0.5594196", "0.55866754", "0.55238754", "0.5521845", ...
0.0
-1
Schaff Trend Cycle (STC) STC indicator is a forwardlooking leading indicator combining moving averages (MACD) with oscillator (stochastic).
def Schaff(self, shortPeriod=23, longPeriod=50): shortEMAClose = ta.EMA(self.data.close, timeperiod=shortPeriod) longEMAClose = ta.EMA(self.data.close, timeperiod=longPeriod) macdClose = shortEMAClose - longEMAClose shortEMALow = ta.EMA(self.data.low, timeperiod=shortPeriod) longEMALow = ta.EMA(self.data.low, timeperiod=longPeriod) macdLow = shortEMALow - longEMALow shortEMAHigh = ta.EMA(self.data.high, timeperiod=shortPeriod) longEMAHigh = ta.EMA(self.data.high, timeperiod=longPeriod) macdHigh = shortEMAHigh - longEMAHigh fastk, fastd = ta.STOCHF(macdHigh, macdLow, macdClose, fastk_period=10, fastd_period=10, fastd_matype=0) return 100 * ((macdClose - fastk) / (fastd - fastk))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def one_transition_spectrum_cd(self,tr):\n \n\n ta = tr[\"ta\"] # TimeAxis\n rr = tr[\"rr\"] # transition dipole strength\n om = tr[\"om\"] # frequency - rwa\n gg = tr[\"gg\"] # natural broadening (constant or time dependent)\n fwhm = tr[\"fwhm\"] # Additional gaussian bro...
[ "0.55765706", "0.5497741", "0.5477658", "0.5466189", "0.54562336", "0.54297197", "0.53879595", "0.5304885", "0.5280067", "0.52764845", "0.5274857", "0.52428555", "0.5241364", "0.51811355", "0.5174693", "0.51709056", "0.5167392", "0.5165704", "0.5157772", "0.51531", "0.5118141...
0.4891067
52
Calculates the variational expectations used by an SVGP model.
def variational_expectations(self, Fmu, Fvar, Y): # Y must be in (-1, +1), not (0, 1) assert_01 = tf.Assert(tf.reduce_all((Y == 0.0) | (Y == 1.0)), [Y]) with tf.control_dependencies([assert_01]): Y = Y * 2.0 - 1.0 c2 = Fmu ** 2 + Fvar c = tf.sqrt(c2) theta = tf.tanh(c / 2) / (2 * c) varexp = 0.5 * (Y * Fmu - theta * c2) return varexp - PolyaGammaBernoulli.kl_term(c) - np.log(2.0)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_var_exp(self):\n with self.test_context() as session:\n test_setups, F, feed = self.prepare()\n for test_setup in test_setups:\n l = test_setup.likelihood\n y = test_setup.Y\n l.compile()\n r1 = session.run(l.logp(F, ...
[ "0.72795737", "0.66067874", "0.62614894", "0.6069039", "0.60592204", "0.6042628", "0.6035716", "0.60188943", "0.5992968", "0.5962066", "0.591116", "0.58926576", "0.58375585", "0.58221173", "0.58154273", "0.57872385", "0.5785738", "0.5771455", "0.57044655", "0.56976736", "0.56...
0.6047066
5
Creates a logger of given level and saves logs to a file
def create_logger( project_name: str, level: str = "INFO", log_dir: str = "/tmp/logs", file_name: Optional[str] = None, do_print: bool = True, simple_logging: bool = False, log_to_file: bool = False, rich_logging: bool = False, time_zone: Optional[str] = None, ): import __main__ if file_name is None: try: file_name = ntpath.basename(__main__.__file__).split(".")[0] except: file_name = "logs" logger = logging.getLogger(file_name) logger.handlers.clear() logger.setLevel(getattr(logging, level)) if time_zone: from pytz import timezone, utc def time_formatter(*args): # TODO: Doesnt work with rich formatter utc_dt = utc.localize(datetime.datetime.utcnow()) my_tz = timezone(time_zone) converted = utc_dt.astimezone(my_tz) return converted.timetuple() logging.Formatter.converter = time_formatter if rich_logging: from rich.logging import RichHandler stream_format = f"{project_name}:%(module)s:%(funcName)s: %(message)s" stream_handler = RichHandler(omit_repeated_times=False) else: stream_format = f"%(asctime)s:%(levelname)s:{project_name}:%(module)s:%(funcName)s: %(message)s" stream_handler = logging.StreamHandler() file_formatter = stream_formatter = logging.Formatter( stream_format, "%Y-%m-%d %H:%M:%S" ) if simple_logging: file_formatter = logging.Formatter("%(message)s") stream_formatter = logging.Formatter("%(message)s") if log_to_file: date = datetime.date.today() date = "%s-%s-%s" % (date.day, date.month, date.year) log_file_path = os.path.join(log_dir, "%s-%s.log" % (file_name, date)) create_folder(log_dir) file_handler = logging.FileHandler(log_file_path) file_handler.setFormatter(file_formatter) logger.addHandler(file_handler) if do_print: stream_handler.setFormatter(stream_formatter) logger.addHandler(stream_handler) logger.propagate = False return logger
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def logger(level, log_info):\n log_path = getconfig(\"log\", \"LOG_PATH\")\n log_level = getconfig(\"log\", \"LOG_LEVEL\")\n log_enable = getconfig(\"log\", \"LOG_ENABLE\")\n log_fname = getconfig(\"log\", \"LOG_FNAME\")\n if not os.path.exists(log_path):\n os.makedirs(log_path)\n log_file...
[ "0.8126159", "0.76459956", "0.684709", "0.68146396", "0.6813477", "0.6811436", "0.6630617", "0.6629015", "0.6616148", "0.65982366", "0.65957934", "0.65776724", "0.6575906", "0.657348", "0.6556677", "0.6537464", "0.6526564", "0.65043306", "0.64900917", "0.6485572", "0.64745295...
0.63525015
42
Initialize the cell to only point to itself. header is the column header for the cell
def __init__(self, header, name): self.up = self self.down = self self.left = self self.right = self self.header = header self.name = name
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __init__(self):\n\n self.reset_row()", "def __init__(cell, value):\n\t\tcell.value = value\n\t\tcell.parent = None\n\t\tcell.visited = False", "def __init__(self, numcols):\n # Start by making a root cell\n # This isn't part of the matrix, but it gives an entry point to the matrix\n ...
[ "0.6575508", "0.6537204", "0.6273338", "0.62425", "0.6164589", "0.61148554", "0.6096474", "0.59903026", "0.59864986", "0.5979671", "0.597449", "0.58925885", "0.58822554", "0.5868053", "0.58567417", "0.58472", "0.5832728", "0.5818981", "0.58085716", "0.5777822", "0.57610726", ...
0.5778897
19
Initialize the sum to zero
def __init__(self, name): super(Column, self).__init__(self, name) self.sum = 0
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def reset_sum(self):\n self.sum_e = 0", "def initial(self):\n return zero", "def zero(self):\n raise NotImplementedError(\"Not implemented yet.\")", "def reset_sum(self):\n self._error_sum = 0", "def zero_sum(list):\n if not list:\n return 0\n else:\n return ...
[ "0.7703882", "0.71630156", "0.69994444", "0.6945991", "0.6897512", "0.67463124", "0.6605019", "0.65537924", "0.653141", "0.65299124", "0.6520557", "0.65204495", "0.6479404", "0.6479189", "0.6431233", "0.64236397", "0.6403008", "0.63670397", "0.63195443", "0.62968844", "0.6264...
0.0
-1
Initialize the dancling links matrix with a given number of columns
def __init__(self, numcols): # Start by making a root cell # This isn't part of the matrix, but it gives an entry point to the matrix # root.right is the first column header, root.left is the last # root.up and root.down just wrap around to itself root = Column("root") self.root = root self.numcols = numcols self.numrows = 0 # Now make all of the column headers for col in range(numcols): c = Column("header-" + str(col)) # Insert this column to the right side of the matrix root.left.right = c c.left = root.left c.right = root root.left = c
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __init__(self, n):\n self.row = [0]*n\n self.col =[0]*n\n self.diagonal = 0\n self.antidiag = 0\n self.n = n", "def setup(self, length):\n self.matrix = [None] * length\n for x in range(0,length):\n self.matrix[x] = [None] * length\n self.i =...
[ "0.6169552", "0.61102796", "0.6080898", "0.5925205", "0.5843429", "0.5816062", "0.5752628", "0.5748185", "0.57156444", "0.57052106", "0.56688374", "0.5662722", "0.5662606", "0.5644519", "0.564434", "0.5636628", "0.56212884", "0.5586612", "0.5582982", "0.5580839", "0.554456", ...
0.5835481
5
Add a row to the matrix. cols is a sorted list of the column numbers that have a 1, indexed from 0.
def add_row(self, cols, name=None): def get_header(col_current, col_shift): """ Starting at the current column header, shift to the right col_shift times """ header = col_current for i in range(col_shift): header = header.right return header # Update the number of rows self.numrows += 1 if name is None: name = self.numrows # Get the first column header head = self.root.right head = get_header(head, cols[0]) # Place the first cell cell = Cell(head, name) cell.up = head.up cell.down = head head.up.down = cell head.up = cell head.sum += 1 oldcell = cell oldcol = cols[0] # Loop over all of the other entries for col in cols[1:]: # Shift to get the header head = get_header(head, col - oldcol) # Add in the cell cell = Cell(head, name) cell.up = head.up cell.down = head head.up.down = cell head.up = cell # Now add the left/right links cell.left = oldcell cell.right = oldcell.right cell.right.left = cell cell.left.right = cell # Add to the header sum head.sum += 1 # Keep the old cell for reference oldcell = cell oldcol = col
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def add_row(matrix):\n\tl = len(matrix[0])\n\ttemp = matrix[:]\n\ttemp += [[0]*l]\n\treturn temp", "def add_row(matrix):\n import numpy as np\n shape = np.shape(matrix)\n if matrix is np.zeros(shape):\n return matrix.append(np.zeros(shape[0]))", "def addRow(self, row):\n nc = len(row)\n ...
[ "0.7198061", "0.716274", "0.6843265", "0.6479029", "0.6377876", "0.6279669", "0.62465566", "0.6215555", "0.62106025", "0.62064993", "0.6145421", "0.6095104", "0.60865563", "0.6051224", "0.6049674", "0.6012048", "0.59923834", "0.5945139", "0.5912783", "0.58509195", "0.58039695...
0.6547947
3
Starting at the current column header, shift to the right col_shift times
def get_header(col_current, col_shift): header = col_current for i in range(col_shift): header = header.right return header
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def shift_column(self, coords, direction):\n self.shift_cells(self.get_column(coords, direction), direction)", "def rollback(self) -> None:\n for k in self._moved_cols:\n self._cols[k].move_back()", "def shift_right(self):\n self.pointer = (self.pointer + 1) % len(self.data)", ...
[ "0.6121716", "0.59776706", "0.5851196", "0.5847812", "0.57968843", "0.5760453", "0.566838", "0.5658573", "0.558538", "0.5567467", "0.5556038", "0.5546835", "0.55436087", "0.5541556", "0.5532854", "0.5511011", "0.5500459", "0.5493521", "0.5485904", "0.54635084", "0.5462295", ...
0.69813544
0
Remove the specified column header from the header chain All rows that appear in this column are also removed
def remove_col(self, col_header): # Remove the column header from the header chain col_header.right.left = col_header.left col_header.left.right = col_header.right # Loop down through the column and remove the rows cell = col_header.down while cell != col_header: row_cell = cell.right # Move through all cells in this row and update their up/down links while row_cell != cell: row_cell.down.up = row_cell.up row_cell.up.down = row_cell.down row_cell.header.sum -= 1 # Move on to the next cell in the row row_cell = row_cell.right # Move on to the next row cell = cell.down
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def unremove_col(self, col_header):\n # Add the column head back into the chain\n col_header.right.left = col_header\n col_header.left.right = col_header\n # Loop up through the column and add the rows back in\n # Doing this in exactly the reverse order of the removing ensures th...
[ "0.7807759", "0.7441563", "0.71072763", "0.67735565", "0.6634205", "0.6594297", "0.6533182", "0.6480123", "0.6172724", "0.6143548", "0.6119587", "0.6100099", "0.60919523", "0.6055784", "0.60248214", "0.60123044", "0.60102904", "0.5948839", "0.5927248", "0.5872746", "0.5860796...
0.80928975
0
Adds the specified column header back into the header chain Also adds all rows that this column removed back in
def unremove_col(self, col_header): # Add the column head back into the chain col_header.right.left = col_header col_header.left.right = col_header # Loop up through the column and add the rows back in # Doing this in exactly the reverse order of the removing ensures that we return # to the state we were in before the removal cell = col_header.up while cell != col_header: row_cell = cell.left # Move through all cells in this row and update their up/down links while row_cell != cell: row_cell.down.up = row_cell row_cell.up.down = row_cell row_cell.header.sum += 1 # Move on to the next cell in the row row_cell = row_cell.left # Move on to the next row cell = cell.up
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def remove_col(self, col_header):\n # Remove the column header from the header chain\n col_header.right.left = col_header.left\n col_header.left.right = col_header.right\n # Loop down through the column and remove the rows\n cell = col_header.down\n while cell != col_heade...
[ "0.71142775", "0.6889686", "0.65644413", "0.6336859", "0.608312", "0.60671866", "0.6046899", "0.6015363", "0.5942229", "0.58050436", "0.5728618", "0.57080615", "0.5686853", "0.5644749", "0.55979675", "0.5594624", "0.5594624", "0.5585846", "0.5558042", "0.5540971", "0.55384934...
0.73550874
0
Find the column that has the minimum number of cells in it to minimize branching Returning a column with 0 cells in it is ok this gets dealt with in the solving loop
def get_minimum_column(self): min_col = self.root.right current_col = min_col.right while current_col != self.root: if current_col.sum < min_col.sum: min_col = current_col # Move on to the next column current_col = current_col.right return min_col
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def min_reduce_nb(col, a, *args):\n return np.nanmin(a)", "def find_smallest(self):\n # add max value to covered rows and columns to ignore the covered cells\n maxval = self.C.max()\n C = self.C + self.row_cover[:, np.newaxis]*maxval\n C += self.col_cover*maxval\n # return t...
[ "0.6645709", "0.6558186", "0.64990723", "0.6368767", "0.63344336", "0.6301566", "0.6237791", "0.6110719", "0.60172206", "0.60031587", "0.59943664", "0.59906703", "0.5983194", "0.59770536", "0.5949309", "0.5948226", "0.59324056", "0.592747", "0.5884803", "0.58845806", "0.58685...
0.69948006
0
Solve the exact cover problem recursively
def solve(self, solution_rows): # Are we out of columns? # Can only occur if each column has been removed through row selection if self.root.right == self.root: # Construct a tuple of the rows in this solution soln = [] for row in solution_rows: soln.append(row.name) # Add it to the list of solutions self.solutions.append(tuple(sorted(soln))) return # Choose the column with the minimum sum col = self.get_minimum_column() # Remove the column self.remove_col(col) # print("Chosen to remove column " + str(col.name)) # Try adding each row in this column to the solution, one at a time row = col.down while row != col: # If there are no rows in this column, there is nothing to loop over here # Add to the solution solution_rows.append(row) # print("Trying row " + str(row.name)) # Every column on this row needs to be removed cell = row.right while cell != row: self.remove_col(cell.header) cell = cell.right # Now try to solve self.solve(solution_rows) # Now add that row back in cell = row.left while cell != row: self.unremove_col(cell.header) cell = cell.left # Remove this row from the solution solution_rows.pop() # print("Removing row " + str(row.name)) # Move on to the next row row = row.down # Add the column back in self.unremove_col(col)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_cover():\n # D corresponds to the items and the transactions in which they appear, it is the standard code table\n D = {\n \"B\": Bitmap([0, 1, 2]),\n \"A\": Bitmap([0, 1]),\n \"C\": Bitmap([0, 2]),\n \"D\": Bitmap([2])\n }\n # ct corresponds to the itemsets on whic...
[ "0.6313552", "0.6258296", "0.6128886", "0.57589465", "0.5733039", "0.57001925", "0.5643672", "0.55785424", "0.5561169", "0.5516535", "0.5466868", "0.5454839", "0.5434189", "0.5430339", "0.5400842", "0.5336104", "0.5285302", "0.5259781", "0.52392155", "0.5232197", "0.5226537",...
0.0
-1
Find the minimum volume ellipsoid which holds all the points Based on work by Nima Moshtagh
def getMinVolEllipse(P, tolerance=0.01): (N, d) = np.shape(P) d = float(d) # Q will be our working array Q = np.vstack([np.copy(P.T), np.ones(N)]) QT = Q.T # initializations err = 1.0 + tolerance u = (1.0 / N) * np.ones(N) # Khachiyan Algorithm while err > tolerance: V = np.dot(Q, np.dot(np.diag(u), QT)) M = np.diag(np.dot(QT , np.dot(linalg.inv(V), Q))) # M the diagonal vector of an NxN matrix j = np.argmax(M) maximum = M[j] step_size = (maximum - d - 1.0) / ((d + 1.0) * (maximum - 1.0)) new_u = (1.0 - step_size) * u new_u[j] += step_size err = np.linalg.norm(new_u - u) u = new_u # center of the ellipse center = np.dot(P.T, u) # the A matrix for the ellipse A = linalg.inv( np.dot(P.T, np.dot(np.diag(u), P)) - np.array([[a * b for b in center] for a in center]) ) / d # Get the values we'd like to return U, s, rotation = linalg.svd(A) radii = 1.0/np.sqrt(s) rot_err = linalg.norm(np.identity(3)-abs(rotation)) if(rot_err > 0.05): radii = np.array([radii[1],radii[0],radii[2]]) return radii
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def generate_sphere_full():\n \n num_voxels = 31\n c = (15.0, 15.0, 15.0)\n\n data_x = []\n data_y = []\n data_z = []\n data_intensity = []\n\n volume = numpy.zeros((num_voxels, num_voxels, num_voxels))\n\n for x in range(num_voxels):\n for y in range(num_voxels):\n for...
[ "0.62986", "0.62653875", "0.5862462", "0.5844809", "0.5837435", "0.58371854", "0.5790067", "0.5785195", "0.5721557", "0.5710913", "0.56959003", "0.5689655", "0.5679842", "0.56546134", "0.56341815", "0.56135213", "0.5597461", "0.55802417", "0.5576471", "0.55697113", "0.5559904...
0.6222927
2
Method called to collect data and send to Prometheus
def get_commit_time(self, metric): session = requests.Session() session.verify = False logging.debug("metric.repo_project %s" % (metric.repo_project)) logging.debug("metric.git_api %s" % (self._git_api)) git_server = self._git_api if ( "github" in git_server or "bitbucket" in git_server or "gitlab" in git_server or "gitea" in git_server ): logging.warn("Skipping non Azure DevOps server, found %s" % (git_server)) return None # Private or personal token # Fill in with your personal access token and org URL personal_access_token = self._token organization_url = self._git_api # Create a connection to the org credentials = BasicAuthentication("", personal_access_token) connection = Connection(base_url=organization_url, creds=credentials) # Get a client (the "git" client provides access to commits) git_client = connection.clients.get_git_client() commit = git_client.get_commit( commit_id=metric.commit_hash, repository_id=metric.repo_project, project=metric.repo_project, ) logging.debug("Commit %s" % ((commit.committer.date).isoformat("T", "auto"))) if hasattr(commit, "innerExepction"): # This will occur when trying to make an API call to non-Github logging.warning( "Unable to retrieve commit time for build: %s, hash: %s, url: %s. Got http code: %s" % ( metric.build_name, metric.commit_hash, metric.repo_url, str(commit.message), ) ) else: try: metric.commit_time = commit.committer.date.isoformat("T", "auto") logging.info("metric.commit_time %s" % (str(metric.commit_time)[:19])) logging.info("self._timedate_format %s" % (self._timedate_format)) metric.commit_timestamp = pelorus.convert_date_time_to_timestamp( (str(metric.commit_time)[:19]), self._timedate_format ) except Exception: logging.error( "Failed processing commit time for build %s" % metric.build_name, exc_info=True, ) logging.debug(commit) raise return metric
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def run(self):\r\n self.collect_data()", "def _collect_data(self) -> None:\n self.set_websocket_data()\n self.set_stratum_data()\n self.set_cache_data()\n self.collect_peer_connection_metrics()\n self.set_tx_storage_data()", "def fetch(self):\n\n\n # Update Prom...
[ "0.74755186", "0.72660923", "0.69965476", "0.68536365", "0.67639965", "0.66526055", "0.6617369", "0.63650906", "0.62632084", "0.6253866", "0.62457424", "0.62276083", "0.6208388", "0.61819595", "0.61701816", "0.61203456", "0.611145", "0.6091151", "0.60695875", "0.60637254", "0...
0.0
-1
requires class model name
def __init__(self, model, idx=0, seed=None): self.__logger.info("Synthesizer init") self.__logger.debug("DEBUG Message") self.fake = Faker(seed) # First initialization of Faker self.__reccntr = idx # ?? Unknown variable self.add_providers() # Add providers to the faker self.schema = [] self.is_dependent = [] for field in model.info.schema.info.fields: self.schema.append(field.name) if field.info.aux.dependent == "": self.is_dependent.append(False) else: self.is_dependent.append(True) # Cache the generator functions once self.generator_fcns = {} self.set_generators_from_proto(model) # Following extension for generating duplicate records self.__dupcntr = 0 self.__maxdup = 0 self.__dupdist = [] # List of duplicate counts self._original = [] self.duplicate = False self._expect_duplicate = False self.nduplicate_weights = None self.wrg = None self.mod = None # Generator counters/stats self.stats = {"Total": 0, "Original": 0, "Duplicate": 0} # self.h_dupdist = Histogram1D(range(10)) if model.info.aux.HasField("duplicate"): self.duplicate = True self.duplicate_cfg = dict() self.duplicate_cfg["Prob_duplicate"] = model.info.aux.duplicate.probability self.duplicate_cfg["Dist_duplicate"] = model.info.aux.duplicate.distribution self.duplicate_cfg["Max_duplicate"] = model.info.aux.duplicate.maximum self.nduplicate_weights = self.generate_duplicate_pdf() if model.info.aux.HasField("record_modifier"): self.mod = Modifier( self.fake, self.generator_fcns, self.schema, model.info.aux.record_modifier, ) self.__logger.info("") self.__logger.info("Synthesizer configured") self.__logger.info("Model: %s" % model) self.__logger.info("Schema:") self.__logger.info(pformat(self.schema)) self.__logger.info("Dataset record index: %d" % idx) if seed: self.__logger.info("Seed set: %d" % seed) self.__logger.info("Generate duplicate records:") self.__logger.info(pformat(self.duplicate)) if self.duplicate: self.__logger.info("Duplicate record probabilities") self.__logger.info(pformat(self.duplicate_cfg)) self.__logger.info("Duplicate PDF") self.__logger.info(pformat(self.nduplicate_weights)) self.__logger.info("Record modifier configuration") self.__logger.info(model.info.aux.record_modifier)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def modelClass(self):\n raise NotImplementedError", "def get_model(params):\r\n module_name, class_name = params.model.name.rsplit('.', 1)\r\n i = importlib.import_module(module_name)\r\n return getattr(i, class_name)", "def model(self) -> str:\n ...", "def test_valid_model(self):\n ...
[ "0.7560292", "0.6874529", "0.684144", "0.6818532", "0.68008655", "0.6774673", "0.67614686", "0.67368454", "0.6727387", "0.6721594", "0.6721594", "0.6721594", "0.6721594", "0.6721594", "0.6679806", "0.66507953", "0.66507953", "0.66507953", "0.66507953", "0.6616141", "0.6581579...
0.0
-1
This method swaps out the numpy instance in the module, should it have one, to the one in the fake instance we have here.
def _swap_numpy(self, module): # Check to make sure this is not one of the string options from the YAML if not isinstance(module, str): if hasattr(module, 'numpy'): # Check if it has a self.numpy object # TODO: Replace this with the correct variable module.numpy = self.fake.numpy # Swap out with the class's instance of numpy return module # Return out the mutated module
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_reference_to_array(self):\n arr = numpy.arange(0.0, 10.0, 0.1)\n arr = numpy.reshape(arr, (25, 4))\n vtk_arr = array_handler.array2vtk(arr)\n arr1 = array_handler.vtk2array(vtk_arr)\n # Now make sure these are using the same memory.\n arr[0][0] = 100.0\n s...
[ "0.60902596", "0.58744705", "0.5683738", "0.5663783", "0.5609355", "0.5535437", "0.5494269", "0.54620075", "0.54172635", "0.5362005", "0.5362005", "0.5336442", "0.5305379", "0.530221", "0.5182793", "0.51734614", "0.5172819", "0.51510024", "0.51288235", "0.5113124", "0.5095370...
0.765654
0
This method injects in the providers to the faker instance.
def add_providers(self): str_providers = PROVIDERS[0] # Providers, called by name live_providers = PROVIDERS[1] # Providers, provided as a live module for providers in PROVIDERS: # Iterate over the types of providers for provider in providers: # Iterate over all the methods # Inject those into faker, and swap the numpy instance self.fake.add_faker(self._swap_numpy(provider[0]), provider[1])
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __init__(self, config: Config) -> None:\n self.config = config\n\n faker_config = self.config.faker\n self.faker = Faker(locale=faker_config.locale)\n\n self.fakes = {}", "def setup_provider(self):\n pass", "def add_providers_deped(self):\n # This gives direct acce...
[ "0.63692963", "0.6351762", "0.61550707", "0.6035626", "0.5997692", "0.5795709", "0.57771325", "0.57227266", "0.55226743", "0.54858613", "0.5434935", "0.54322845", "0.53593737", "0.5339375", "0.5336239", "0.53179175", "0.529026", "0.5267008", "0.52436227", "0.52424914", "0.520...
0.77991426
0
Add custom providers, Now depricated to to allow for the injection of the new methods.
def add_providers_deped(self): # This gives direct access to the module's main class called Provider. klasses = [ provider.Provider for provider in PROVIDERS] # Accessing the PROVIDERS. Check this method out, see how it operates. for k in klasses: self.fake.add_provider(k)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def add_providers(self):\n str_providers = PROVIDERS[0] # Providers, called by name\n live_providers = PROVIDERS[1] # Providers, provided as a live module\n for providers in PROVIDERS: # Iterate over the types of providers\n for provider in providers: # Iterate over all the meth...
[ "0.763159", "0.6670083", "0.66017246", "0.6336766", "0.62416", "0.60363275", "0.5885727", "0.5830474", "0.57857096", "0.5718912", "0.56462735", "0.56242216", "0.5617124", "0.5603441", "0.56022394", "0.5557451", "0.55536884", "0.5521999", "0.55216455", "0.55036163", "0.5493164...
0.64158905
3
Convert field parameters to/from a message to python type parameters which do not contain Fields are converted to python type
def get_field_parameters(self, in_parms): if len(in_parms) == 0: # Check if there are params return None # If that's the case, return None values = [] # Empty values is_msg = False # Check if the param is a message for parm in in_parms: # Loop over params if parm.type == "Field": # If it is a message is_msg = True # Set is_message to true continue # Go to top of loop _type = eval(parm.type) # create a type object value = _type(parm.value) # Create the value, and cast it to the type values.append(value) # Add that into the parameters if is_msg is True: # check if is a message return in_parms # Return input params elif len(values) == 1: # If there is only one element return values[-1] # Return just that element else: # Otherwise return values # Return the params
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def convert_type(self, value, schema_type, **kwargs):", "def _ConvertFieldValuePair(self, js, message, path):\n names = []\n message_descriptor = message.DESCRIPTOR\n fields_by_json_name = dict((f.json_name, f)\n for f in message_descriptor.fields)\n for name in js:\n ...
[ "0.5889569", "0.58535415", "0.5846825", "0.5840448", "0.58211553", "0.5739531", "0.5697468", "0.5670201", "0.5669158", "0.558879", "0.5576237", "0.5560981", "0.5541033", "0.5484416", "0.5465832", "0.54647964", "0.54605037", "0.5457013", "0.54551595", "0.54478323", "0.5439084"...
0.5692826
7
This method sets the generators from a protocol buffer. This does... not sure yet
def set_generators_from_proto(self, table): self.__logger.info("Setting Generator functions from Msg") # Let us know for field in table.info.schema.info.fields: # Iterate over the fields in the proto # Let us know what field is being accessed self.__logger.info("Gathering fakers %s", field.name) if field.info.aux.dependent != "": # If the aux.dependent field is empty continue # Goto the top of the loop if the above is the case self.__logger.info("Independent field %s", field) # Getting the field # Get the parameters out of the generator parms = self.get_field_parameters( field.info.aux.generator.parameters) # Grab our params # Load this data into the system, associate field with params and generator self.generator_fcns[field.name] = (field.info.aux.generator.name, parms) self.__logger.debug(parms) # Tell us self.__logger.debug(field.info.aux.generator.name) # Tell us self.__logger.debug(self.generator_fcns[field.name]) # Tell us
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def set_generator(self, gen):\n self.generator = gen", "def setGenerators(self):\n shape = (self.input_shape[0],self.input_shape[1])\n self.trainGen,self.validateGen = getBatchGenerators(self.batch_size,\n self.dataPath,\n ...
[ "0.6843186", "0.6817292", "0.623496", "0.61516976", "0.5911144", "0.5882668", "0.5799233", "0.56797016", "0.5637793", "0.561574", "0.560835", "0.5581869", "0.55451405", "0.5529971", "0.552042", "0.5490284", "0.54892546", "0.5484604", "0.54761255", "0.54730356", "0.5460637", ...
0.6150093
4
Create a map of duplicates and probabilities according to a pdf, i.e. uniform and store for reuse on each original event current version taken directly from FEBRL needs review b/c number of duplicates stored starts at 2?
def generate_duplicate_pdf(self): num_dup = 1 prob_sum = 0.0 prob_list = [(num_dup, prob_sum)] max_dups = self.duplicate_cfg["Max_duplicate"] uniform_val = 1.0 / float(max_dups) for i in range(max_dups - 1): num_dup += 1 prob_list.append((num_dup, uniform_val + prob_list[-1][1])) return prob_list
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def multinomial_pmf(sample, probabilities):\r\n # TODO\r\n a=[]\r\n b=[]\r\n i=0\r\n key_list=[]\r\n value_list=[]\r\n for key,value in sample.items():\r\n key_list.append(key)\r\n value_list.append(value)\r\n b=list(sample)\r\n while i< len(b):\r\n a.append(probabil...
[ "0.6266391", "0.6231039", "0.6222904", "0.6209188", "0.62075746", "0.60514987", "0.60154533", "0.59842813", "0.59767723", "0.5969421", "0.5939433", "0.58987904", "0.58945656", "0.58854735", "0.58664787", "0.5817961", "0.57828134", "0.5771365", "0.5759954", "0.5755793", "0.573...
0.74976236
0
Setter method for original
def reset_original(self): self._original = [] # Empty out self._originals
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def setOriginal(self,neworiginal):\n\t\tself.original = neworiginal;", "def original(self, original):\n self._original = original", "def original(self) -> Any:\n raise NotImplementedError", "def __init__(self, orig):\n self.orig = orig", "def update_original_data(self):\n pass",...
[ "0.8130244", "0.8047649", "0.7397236", "0.730968", "0.6972755", "0.68666035", "0.6818994", "0.67645526", "0.67645526", "0.6702549", "0.6689829", "0.6665114", "0.6546259", "0.6500433", "0.64820886", "0.64437467", "0.6417436", "0.6361053", "0.63502926", "0.6325794", "0.6284538"...
0.5829867
57
Create an orriginal record.
def generate_original(self): fakers = self.schema # Get the schema; Not sure what this is self.reset_original() # Set the self._original value to be empty self.__logger.debug("generate_original()") # Let us know self.__logger.debug("Event ID %d" % self.record_count) # Let us know darr = [] # Data array for i, fake in enumerate(fakers): # Enumerate the fakers if self.is_dependent[i] is True: # Skip over if there is a dependent continue # Skipper if self.generator_fcns[fake][1] is None: # Check if there are params value = self.fake.fake( self.generator_fcns[fake][0], params=None) # Create fake datum darr.append(value) # Append the data to the list else: # If there are self.__logger.info(self.generator_fcns[fake][1]) value = self.fake.fake( self.generator_fcns[fake][0], self.generator_fcns[fake][1]) # Create fake datum if isinstance(value, list): # If it is a list darr.extend(value) # Extend else: # Otherwise if value not in darr: darr.append(value) # Just append the value self.record_counter() # Count the number of records self.cache_original(darr) # Cache the results return darr # Return the data array
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def createRecord(self):\n self.dto.getRecord().append(self.controller.createNewObj())\n print(\"Record added.\")", "def _inmate_record_get_or_create(self):\n raise NotImplementedError('_inmate_record_get_or_create needs to be implemented with the new format')", "def create_record(self, zon...
[ "0.66684353", "0.6392694", "0.61336666", "0.6101538", "0.6050459", "0.6033388", "0.5997482", "0.5970368", "0.5938527", "0.59184444", "0.5904673", "0.5903052", "0.58274496", "0.5815766", "0.5784867", "0.57735556", "0.57151145", "0.5684695", "0.5666976", "0.5666811", "0.5662072...
0.0
-1
Determines whether original record will be duplicated Gets the maximum number of duplicated records to generate
def expect_duplicate(self): # Reset everything for this record self._expect_duplicate = False self.__dupcntr = 0 self.__maxdup = 0 # Get the probability to generate duplicate for next record if self.fake.random.random() < self.duplicate_cfg["Prob_duplicate"]: self._expect_duplicate = True self.__maxdup = self.random_select_ndups() else: self._expect_duplicate = False self.__maxdup = 0 self.__logger.debug("expect_duplicate ndups: %d", self.__maxdup)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def is_duplicate(self):\n return bool(self.duplicated)", "def isRepeated(self):\n return self._field.label == FieldDescriptor.LABEL_REPEATED", "def is_duplicate(self, **kwargs):\n return len(list(self.c.select(**kwargs))) > 0", "def process_duplicate_rows(self):\n pass", "def is...
[ "0.675923", "0.63455653", "0.6291391", "0.5996474", "0.59781253", "0.5973371", "0.59171003", "0.5903125", "0.5873092", "0.58724254", "0.5841418", "0.58190286", "0.5798888", "0.5789265", "0.5784065", "0.57638514", "0.5761442", "0.57307065", "0.5723805", "0.5719764", "0.5711496...
0.7407912
0
Load data if data have been created. Create data otherwise.
def load_data(): if 'data' not in os.listdir('.'): os.mkdir('data') if 'id_to_word.pkl' not in os.listdir('data'): print('Loading data...') (x_train, y_train), (x_val, y_val) = imdb.load_data(num_words=max_features, skip_top=20, index_from=3) word_to_id = imdb.get_word_index() word_to_id ={k:(v+3) for k,v in word_to_id.items()} word_to_id["<PAD>"] = 0 word_to_id["<START>"] = 1 word_to_id["<UNK>"] = 2 id_to_word = {value:key for key,value in word_to_id.items()} print(len(x_train), 'train sequences') print(len(x_val), 'test sequences') print('Pad sequences (samples x time)') x_train = sequence.pad_sequences(x_train, maxlen=maxlen) x_val = sequence.pad_sequences(x_val, maxlen=maxlen) y_train = np.eye(2)[y_train] y_val = np.eye(2)[y_val] np.save('./data/x_train.npy', x_train) np.save('./data/y_train.npy', y_train) np.save('./data/x_val.npy', x_val) np.save('./data/y_val.npy', y_val) with open('data/id_to_word.pkl','wb') as f: pickle.dump(id_to_word, f) else: x_train, y_train, x_val, y_val = np.load('data/x_train.npy'),np.load('data/y_train.npy'),np.load('data/x_val.npy'),np.load('data/y_val.npy') with open('data/id_to_word.pkl','rb') as f: id_to_word = pickle.load(f) return x_train, y_train, x_val, y_val, id_to_word
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def load_data(self) -> None:", "def load_data(self):", "def load_data(self):\n raise NotImplementedError()", "def _load(self):\n if self.file_path.exists():\n with open(self.file_path) as fid:\n self.data = json.load(fid)", "def _load_data(self):\n if self._ap...
[ "0.6876719", "0.65628785", "0.6523932", "0.64879066", "0.644452", "0.6407347", "0.62683874", "0.6245403", "0.6236588", "0.6224349", "0.62203705", "0.61988556", "0.61792195", "0.6178383", "0.61401325", "0.6105626", "0.608856", "0.608699", "0.6083278", "0.60767114", "0.6059067"...
0.0
-1
Build the original model to be explained.
def create_original_model(): model = Sequential() model.add(Embedding(max_features, embedding_dims, input_length=maxlen)) model.add(Dropout(0.2)) model.add(Conv1D(filters, kernel_size, padding='valid', activation='relu', strides=1)) model.add(GlobalMaxPooling1D()) model.add(Dense(hidden_dims)) model.add(Dropout(0.2)) model.add(Activation('relu')) model.add(Dense(2)) model.add(Activation('softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) return model
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def build_model():", "def build_model(self):\n pass", "def build_model(self):\n pass", "def build_model(self):\n raise NotImplementedError", "def _build_model(self):\n raise NotImplementedError()", "def build_model(self) -> nn.Module:\n pass", "def _build_model(self, ...
[ "0.76988584", "0.7433274", "0.7433274", "0.7323292", "0.71259195", "0.69584244", "0.6808802", "0.6758032", "0.66716534", "0.65664864", "0.64607084", "0.6417122", "0.63994056", "0.6390134", "0.6358464", "0.6354998", "0.62842834", "0.62842834", "0.6279981", "0.6247293", "0.6068...
0.0
-1
Generate the predictions of the original model on training and validation datasets. The original model is also trained if train = True.
def generate_original_preds(train = True): x_train, y_train, x_val, y_val, id_to_word = load_data() model = create_original_model() if train: filepath="models/original.hdf5" checkpoint = ModelCheckpoint(filepath, monitor='val_acc', verbose=1, save_best_only=True, mode='max') callbacks_list = [checkpoint] model.fit(x_train, y_train, validation_data=(x_val, y_val),callbacks = callbacks_list, epochs=epochs, batch_size=batch_size) model.load_weights('./models/original.hdf5', by_name=True) pred_train = model.predict(x_train,verbose = 1, batch_size = 1000) pred_val = model.predict(x_val,verbose = 1, batch_size = 1000) if not train: print('The val accuracy is {}'.format(calculate_acc(pred_val,y_val))) print('The train accuracy is {}'.format(calculate_acc(pred_train,y_train))) np.save('data/pred_train.npy', pred_train) np.save('data/pred_val.npy', pred_val)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def fit_predict(self):\n self.classifier = self.model\n self.classifier.fit(self.X_sample, self.y_sample)\n self.y_pred = self.classifier.predict(self.X_test)", "def get_predictions(fitted_model_filename):\n click.echo(\"Mode: predicting probabilities.\\n\")\n defaults = get_defaults()...
[ "0.6959041", "0.6904541", "0.6858206", "0.674883", "0.6679141", "0.65974444", "0.654767", "0.65204763", "0.64544606", "0.6438485", "0.6437152", "0.64298964", "0.6410104", "0.640449", "0.640449", "0.6369408", "0.63413376", "0.63313776", "0.62701774", "0.6262735", "0.6240748", ...
0.7165115
0
Build the L2X model for selecting words.
def construct_gumbel_selector(X_ph, num_words, embedding_dims, maxlen): emb_layer = Embedding(num_words, embedding_dims, input_length = maxlen, name = 'emb_gumbel') emb = emb_layer(X_ph) #(400, 50) net = Dropout(0.2, name = 'dropout_gumbel')(emb) net = emb first_layer = Conv1D(100, kernel_size, padding='same', activation='relu', strides=1, name = 'conv1_gumbel')(net) # bs, 400, 100 # global info net_new = GlobalMaxPooling1D(name = 'new_global_max_pooling1d_1')(first_layer) # bs, 100 global_info = Dense(100, name = 'new_dense_1', activation='relu')(net_new) # bs, 100 # local info net = Conv1D(100, 3, padding='same', activation='relu', strides=1, name = 'conv2_gumbel')(first_layer) # bs, 400, 100 local_info = Conv1D(100, 3, padding='same', activation='relu', strides=1, name = 'conv3_gumbel')(net) # bs, 400, 100 combined = Concatenate()([global_info,local_info]) net = Dropout(0.2, name = 'new_dropout_2')(combined) net = Conv1D(100, 1, padding='same', activation='relu', strides=1, name = 'conv_last_gumbel')(net) logits_T = Conv1D(1, 1, padding='same', activation=None, strides=1, name = 'conv4_gumbel')(net) # bs, 400, 1 # wanna make it bs, maxlen*num_groups squeeze_layer = Lambda(lambda x:tf.squeeze(x), output_shape=lambda x:x[:-1]) logits_T_grp = Dense(maxlen*num_groups)(squeeze_layer(logits_T)) #print(logits_T_grp.shape) return logits_T_grp # bs, 400* num_groups
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def build_model_from_inputs(self):\n if self.term_list is None:\n # no supplied token list -- use vocabulary of the training dataset\n # self.term_list = self.vocabulary\n # info(\"Setting bag dimension to {} from input vocabulary.\".format(len(self.term_list)))\n ...
[ "0.64706546", "0.628739", "0.61955893", "0.6154911", "0.6109166", "0.60060537", "0.5975403", "0.59434366", "0.5934024", "0.588384", "0.58455455", "0.58168155", "0.58109325", "0.57811666", "0.5767697", "0.56962854", "0.56701654", "0.56225514", "0.56121624", "0.5598342", "0.559...
0.0
-1
Generate scores on features on validation by L2X. Train the L2X model with variational approaches if train = True.
def L2X(train = True): print('Loading dataset...') x_train, y_train, x_val, y_val, id_to_word = load_data() #pred_train = np.load('data/pred_train.npy') #pred_val = np.load('data/pred_val.npy') print('Creating model...') # P(S|X) with tf.variable_scope('selection_model'): X_ph = Input(shape=(maxlen,), dtype='int32') logits_T_grp = construct_gumbel_selector(X_ph, max_features, embedding_dims, maxlen) # bs, max_len * num_groups tau = 0.5 T = Sample_Concrete(tau, k, num_feature=maxlen, num_groups=num_groups)(logits_T_grp) T = Reshape((maxlen, num_groups))(T) T = Permute((2, 1))(T) # bs, num_groups, max_len # q(X_S) with tf.variable_scope('prediction_model'): emb2 = Embedding(max_features, embedding_dims, input_length=maxlen)(X_ph) # emb2 bs, max_len, 50 # apply the matrix trick as before # here the output size of matmul layer is different from before net = matmul_layer([T, emb2]) # bs, num_groups, 50 #print(net.shape) net = Conv1D(1, 1, padding='same', activation=None, strides=1, name = 'merge_channel')(net) # bs, num_groups, 1 # net = Mean(net) # bs, 50 input_group = Flatten()(net) # bs, num_groups # num_groups = K.int_shape(input_group)[1] # here we add instance wise f-s again!!!! net = Dense(100, activation='relu', name = 's/dense1', kernel_regularizer=regularizers.l2(1e-3))(input_group) net = Dense(100, activation='relu', name = 's/dense2', kernel_regularizer=regularizers.l2(1e-3))(net) logits = Dense(num_groups)(net) # A tensor of shape, [batch_size, max_sents, 100] samples = Sample_Concrete_Original(tau, num_vital_group, name='group_importance')(logits) new_input_group = Multiply()([input_group, samples]) net = Dense(hidden_dims, activation='relu')(new_input_group) preds = Dense(2, activation='softmax', name = 'new_dense')(net) model = Model(inputs=X_ph, outputs=preds) model.summary() model.compile(loss='categorical_crossentropy', optimizer='rmsprop',#optimizer, metrics=['acc']) #train_acc = np.mean(np.argmax(pred_train, axis = 1)==np.argmax(y_train, axis = 1)) #val_acc = np.mean(np.argmax(pred_val, axis = 1)==np.argmax(y_val, axis = 1)) #print('The train and validation accuracy of the original model is {} and {}'.format(train_acc, val_acc)) if train: filepath="models/l2x.hdf5" checkpoint = ModelCheckpoint(filepath, monitor='val_acc', verbose=1, save_best_only=True, mode='max') callbacks_list = [checkpoint] st = time.time() model.fit(x_train, y_train, validation_data=(x_val, y_val), callbacks = callbacks_list, epochs=epochs, batch_size=batch_size) duration = time.time() - st print('Training time is {}'.format(duration)) model.load_weights('models/l2x.hdf5', by_name=True) pred_model = Model(X_ph, [T, samples]) pred_model.summary() pred_model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['acc']) st = time.time() #scores = pred_model.predict(x_val, # verbose = 1, batch_size = batch_size)[:,:,0] #scores = np.reshape(scores, [scores.shape[0], maxlen]) scores_t, group_importances_t = pred_model.predict(x_train, verbose = 1, batch_size = batch_size) scores_v, group_importances_v = pred_model.predict(x_val, verbose = 1, batch_size = batch_size) return scores_t, group_importances_t, scores_v, group_importances_v, x_val
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def train(self,features,y):\r\n \r\n if self.learn_type == \"nn\":\r\n #generate supervised dataset\r\n return(self.learner.train_on_batch(features,y))\r\n elif self.learn_type == \"linear\":\r\n grad = 0\r\n n = len(features)\r\n for i in...
[ "0.654589", "0.64421695", "0.63593584", "0.63469756", "0.62618685", "0.62167436", "0.6188725", "0.6184751", "0.6142719", "0.6141688", "0.60937035", "0.60724396", "0.6038608", "0.6014961", "0.5990709", "0.59876823", "0.59866655", "0.59690255", "0.5963425", "0.5955654", "0.5946...
0.0
-1
Generate the predictions of the original model on training and validation datasets. The original model is also trained if train = True.
def generate_post_preds(train = True): x_train, y_train, x_val, y_val = np.load('data/x_train_new.npy'),np.load('data/y_train.npy'),np.load('data/x_val_new.npy'),np.load('data/y_val.npy') with open('data/id_to_word.pkl','rb') as f: id_to_word = pickle.load(f) model = create_original_model() if train: filepath="./models/post.hdf5" checkpoint = ModelCheckpoint(filepath, monitor='val_acc', verbose=1, save_best_only=True, mode='max') callbacks_list = [checkpoint] model.fit(x_train, y_train, validation_data=(x_val, y_val),callbacks = callbacks_list, epochs=epochs, batch_size=batch_size) model.load_weights('./models/post.hdf5', by_name=True) pred_train = model.predict(x_train,verbose = 1, batch_size = 1000) pred_val = model.predict(x_val,verbose = 1, batch_size = 1000) if not train: print('The val accuracy is {}'.format(calculate_acc(pred_val,y_val))) print('The train accuracy is {}'.format(calculate_acc(pred_train,y_train)))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def generate_original_preds(train = True):\n x_train, y_train, x_val, y_val, id_to_word = load_data() \n model = create_original_model()\n\n if train:\n filepath=\"models/original.hdf5\"\n checkpoint = ModelCheckpoint(filepath, monitor='val_acc', \n verbose=1, save_best_only=True,...
[ "0.7163424", "0.69594693", "0.6906497", "0.6859476", "0.67500716", "0.6679552", "0.6597463", "0.654829", "0.65226644", "0.6456303", "0.643875", "0.6437849", "0.6430144", "0.6410656", "0.6405512", "0.6405512", "0.6370887", "0.6341422", "0.63307375", "0.6271287", "0.6262299", ...
0.6127523
40
Compose the largest number out of a set of integers.
def largest_number(digits): res = "" while digits: max_digit = None for digit in digits: if max_digit is None or \ is_greater_or_equal_than(digit, max_digit): max_digit = digit res += max_digit digits.remove(max_digit) return res
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def largest_int(numbers):\n\n if numbers == []:\n return \n max_int = numbers[0]\n for number in numbers:\n if number > max_int:\n max_int = number\n \n return max_int", "def max_(lst: Iterable[int]) -> int:\n return reduce(lambda x, y: x if x > y else y, lst)", "def ...
[ "0.7238424", "0.68917364", "0.6735405", "0.66264164", "0.66255736", "0.6614427", "0.66113424", "0.65993583", "0.6570257", "0.6552687", "0.65461093", "0.65238184", "0.64182717", "0.63805205", "0.63039565", "0.6295779", "0.62524813", "0.6228118", "0.6196727", "0.61448497", "0.6...
0.6804858
2
A function to build the neural network of the required size using the weights and biases provided. Instead of doing this, can we use a simple constructor method and initalize them post the construction? That would be sensible and faster.
def neural_net(self, layers): model = nn.Sequential() for l in range(0, len(layers) - 1): model.add_module("layer_"+str(l), nn.Linear(layers[l],layers[l+1], bias=True)) if l != len(layers) - 2: model.add_module("tanh_"+str(l), nn.Tanh()) return model
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __init__(self, sizes):\r\n self.num_layers = len(sizes)\r\n self.sizes = sizes\r\n self.biases = [np.random.randn(y, 1) for y in sizes[1:]]\r\n self.weights = [np.random.randn(y, x)\r\n for x, y in zip(sizes[:-1], sizes[1:])]", "def __init__(self, sizes):\n ...
[ "0.7550142", "0.7535491", "0.75056463", "0.74940723", "0.7493714", "0.7344416", "0.7279779", "0.7265629", "0.7218069", "0.72046214", "0.71778685", "0.71470296", "0.7120793", "0.70849985", "0.7019694", "0.70176697", "0.69794846", "0.69722265", "0.6920543", "0.6879415", "0.6876...
0.0
-1
Initialize the neural network with the required layers, the weights and the biases. The input "layers" in an array that contains the number of nodes (neurons) in each layer.
def initialize_NN(self, m): if type(m) == nn.Linear: nn.init.xavier_uniform_(m.weight) # print(m.weight)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __init__(self, layerNeurons, initialWeights = None, layerTypes=None, **kwargs):\r\n \r\n # Ensure that there is at-least one input and one output layer in the network\r\n assert len(layerNeurons)>1, \"At least one input layer and one output layer is needed\"\r\n \r\n # Get th...
[ "0.7665592", "0.75891453", "0.7549877", "0.7288455", "0.7238649", "0.72074854", "0.7202781", "0.71520114", "0.7109726", "0.70575273", "0.6969205", "0.69633704", "0.68633807", "0.6848898", "0.6821339", "0.68000925", "0.677125", "0.67679054", "0.6746093", "0.6742651", "0.672905...
0.0
-1
Forward pass through the network to obtain the U field.
def net_u(self, x, t): u = self.model(torch.cat((x,t),1)) return u
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def U(self):\n return self._U", "def forward(self, u):\n self.pop(u)\n return self.read(1.)", "def get_U(self):\n if self.U is not None:\n return self.U\n return self.calc_Uiso()", "def forward(self, inputs):\n\n down0 = self.layer_0(inputs=inputs)\n ...
[ "0.6244465", "0.6143601", "0.61348015", "0.60307336", "0.5914714", "0.586357", "0.5847307", "0.5737416", "0.57315356", "0.5697165", "0.5688825", "0.5688825", "0.5688825", "0.56794524", "0.56679034", "0.5638842", "0.5594738", "0.55896443", "0.5576749", "0.5571661", "0.5566135"...
0.58103776
7
The providerassigned unique ID for this managed resource.
def id(self) -> str: return pulumi.get(self, "id")
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def provider_id(self):\n return self.get('_id')", "def provider_id(self):\n raise NotImplementedError", "def id(self):\n return self.raw_resource.uuid", "def healthcare_provider_id(self):\n return self._healthcare_provider_id", "def unique_identifier(self) -> str:\n retur...
[ "0.8193033", "0.78504187", "0.77109545", "0.7604915", "0.74777704", "0.74738747", "0.74738747", "0.74738747", "0.7426179", "0.7379609", "0.73721254", "0.73721254", "0.73721254", "0.73721254", "0.73721254", "0.73721254", "0.73721254", "0.73721254", "0.7357793", "0.7357793", "0...
0.0
-1
The managed object reference ID of the root resource pool for the cluster.
def resource_pool_id(self) -> str: return pulumi.get(self, "resource_pool_id")
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def pool_id ( self ):\n return self._pool_id", "def managed_object_id(self):\n o = self._data[\"managed_object\"]\n if type(o) in (int, long):\n return o\n return o.id", "def identity_pool_id(self) -> pulumi.Output[str]:\n return pulumi.get(self, \"identity_pool_id\"...
[ "0.71896243", "0.66001445", "0.65141094", "0.6471181", "0.6368429", "0.6354283", "0.634698", "0.6305942", "0.62388986", "0.62217504", "0.6184611", "0.61742735", "0.61742735", "0.61742735", "0.61742735", "0.61742735", "0.61529875", "0.6127469", "0.6123672", "0.61147434", "0.61...
0.74713767
0
The `ComputeCluster` data source can be used to discover the ID of a cluster in vSphere. This is useful to fetch the ID of a cluster that you want to use for virtual machine placement via the `VirtualMachine` resource, allowing to specify the cluster's root resource pool directly versus using the alias available through the `ResourcePool` data source. > You may also wish to see the `ComputeCluster` resource for more information about clusters and how to managed the resource in this provider. Example Usage ```python import pulumi import pulumi_vsphere as vsphere datacenter = vsphere.get_datacenter(name="dc01") compute_cluster = vsphere.get_compute_cluster(name="cluster01", datacenter_id=datacenter.id) ```
def get_compute_cluster(datacenter_id: Optional[str] = None, name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetComputeClusterResult: __args__ = dict() __args__['datacenterId'] = datacenter_id __args__['name'] = name opts = pulumi.InvokeOptions.merge(_utilities.get_invoke_opts_defaults(), opts) __ret__ = pulumi.runtime.invoke('vsphere:index/getComputeCluster:getComputeCluster', __args__, opts=opts, typ=GetComputeClusterResult).value return AwaitableGetComputeClusterResult( datacenter_id=pulumi.get(__ret__, 'datacenter_id'), id=pulumi.get(__ret__, 'id'), name=pulumi.get(__ret__, 'name'), resource_pool_id=pulumi.get(__ret__, 'resource_pool_id'))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_cluster_id(options):\n cluster = options.cluster\n datacenter = get_datacenter(options)\n for item in datacenter.hostFolder.childEntity:\n if (item.name == cluster):\n return item._GetMoId()", "def get_compute_cluster_output(datacenter_id: Optional[pulumi.Input[Optional[str]]] = N...
[ "0.70518404", "0.70052683", "0.67735595", "0.6768537", "0.6736824", "0.6736824", "0.6736824", "0.6736824", "0.6736824", "0.66624004", "0.66624004", "0.66624004", "0.66624004", "0.6613303", "0.660601", "0.660601", "0.6474703", "0.6474703", "0.6474703", "0.63924193", "0.6386118...
0.72311264
0