body_hash
stringlengths
64
64
body
stringlengths
23
109k
docstring
stringlengths
1
57k
path
stringlengths
4
198
name
stringlengths
1
115
repository_name
stringlengths
7
111
repository_stars
float64
0
191k
lang
stringclasses
1 value
body_without_docstring
stringlengths
14
108k
unified
stringlengths
45
133k
8bd46412e03f2c40e3ecdce251cb9cf1719c84c8e9a51305d73f8d606f897d54
def else_scope(self): 'Create an else scope.\n\n This can only be used right after an if scope.\n\n Returns\n -------\n else_scope : WithScope\n The result else scope.\n\n Examples\n --------\n .. code-block:: python\n\n ib = tvm.ir_builder.creat...
Create an else scope. This can only be used right after an if scope. Returns ------- else_scope : WithScope The result else scope. Examples -------- .. code-block:: python ib = tvm.ir_builder.create() i = tvm.var("i") x = ib.pointer("float32") with ib.if_scope((i % 2) == 0): x[i] = x[i - ...
third_party/incubator-tvm/python/tvm/ir_builder.py
else_scope
tianjiashuo/akg
286
python
def else_scope(self): 'Create an else scope.\n\n This can only be used right after an if scope.\n\n Returns\n -------\n else_scope : WithScope\n The result else scope.\n\n Examples\n --------\n .. code-block:: python\n\n ib = tvm.ir_builder.creat...
def else_scope(self): 'Create an else scope.\n\n This can only be used right after an if scope.\n\n Returns\n -------\n else_scope : WithScope\n The result else scope.\n\n Examples\n --------\n .. code-block:: python\n\n ib = tvm.ir_builder.creat...
45504d0aef957530ca1e21ddda5b2830c87c149562db00b6e421c498e8935b1e
def new_scope(self): 'Create new scope,\n\n this is useful to set boundary of attr and allocate.\n\n Returns\n -------\n new_scope : WithScope\n The result new scope.\n ' self._seq_stack.append([]) def _exit_cb(): self.emit(self._pop_seq()) return Wi...
Create new scope, this is useful to set boundary of attr and allocate. Returns ------- new_scope : WithScope The result new scope.
third_party/incubator-tvm/python/tvm/ir_builder.py
new_scope
tianjiashuo/akg
286
python
def new_scope(self): 'Create new scope,\n\n this is useful to set boundary of attr and allocate.\n\n Returns\n -------\n new_scope : WithScope\n The result new scope.\n ' self._seq_stack.append([]) def _exit_cb(): self.emit(self._pop_seq()) return Wi...
def new_scope(self): 'Create new scope,\n\n this is useful to set boundary of attr and allocate.\n\n Returns\n -------\n new_scope : WithScope\n The result new scope.\n ' self._seq_stack.append([]) def _exit_cb(): self.emit(self._pop_seq()) return Wi...
65f8a8361cbb0712bb4166d6eacd48baa50a76db90c16f8a16152b21c6d09675
def allocate(self, dtype, shape, name='buf', scope=None): 'Create a allocate statement.\n\n Parameters\n ----------\n dtype : str\n The content data type.\n\n shape : tuple of Expr\n The shape of array to be allocated.\n\n name : str, optional\n Th...
Create a allocate statement. Parameters ---------- dtype : str The content data type. shape : tuple of Expr The shape of array to be allocated. name : str, optional The name of the buffer. scope : str, optional The scope of the buffer. Returns ------- buffer : BufferVar The buffer var represent...
third_party/incubator-tvm/python/tvm/ir_builder.py
allocate
tianjiashuo/akg
286
python
def allocate(self, dtype, shape, name='buf', scope=None): 'Create a allocate statement.\n\n Parameters\n ----------\n dtype : str\n The content data type.\n\n shape : tuple of Expr\n The shape of array to be allocated.\n\n name : str, optional\n Th...
def allocate(self, dtype, shape, name='buf', scope=None): 'Create a allocate statement.\n\n Parameters\n ----------\n dtype : str\n The content data type.\n\n shape : tuple of Expr\n The shape of array to be allocated.\n\n name : str, optional\n Th...
6180f8bd53da51d688ef403a8404f7a62f194645841057d213bebd5d869b78a0
def pointer(self, content_type, name='ptr'): 'Create pointer variable with content type.\n\n Parameters\n ----------\n content_type : str\n The content data type.\n\n name : str, optional\n The name of the pointer.\n\n Returns\n -------\n ptr : ...
Create pointer variable with content type. Parameters ---------- content_type : str The content data type. name : str, optional The name of the pointer. Returns ------- ptr : BufferVar The buffer var representing the buffer.
third_party/incubator-tvm/python/tvm/ir_builder.py
pointer
tianjiashuo/akg
286
python
def pointer(self, content_type, name='ptr'): 'Create pointer variable with content type.\n\n Parameters\n ----------\n content_type : str\n The content data type.\n\n name : str, optional\n The name of the pointer.\n\n Returns\n -------\n ptr : ...
def pointer(self, content_type, name='ptr'): 'Create pointer variable with content type.\n\n Parameters\n ----------\n content_type : str\n The content data type.\n\n name : str, optional\n The name of the pointer.\n\n Returns\n -------\n ptr : ...
a02ac6dd2a394f72c6f860e16305ace59a78b7d6520cfdc9be090d520905c4b0
def buffer_ptr(self, buf): 'Create pointer variable corresponds to buffer ptr.\n\n Parameters\n ----------\n buf : Buffer\n The buffer to be extracted.\n\n Returns\n -------\n ptr : BufferVar\n The buffer var representing the buffer.\n ' ret...
Create pointer variable corresponds to buffer ptr. Parameters ---------- buf : Buffer The buffer to be extracted. Returns ------- ptr : BufferVar The buffer var representing the buffer.
third_party/incubator-tvm/python/tvm/ir_builder.py
buffer_ptr
tianjiashuo/akg
286
python
def buffer_ptr(self, buf): 'Create pointer variable corresponds to buffer ptr.\n\n Parameters\n ----------\n buf : Buffer\n The buffer to be extracted.\n\n Returns\n -------\n ptr : BufferVar\n The buffer var representing the buffer.\n ' ret...
def buffer_ptr(self, buf): 'Create pointer variable corresponds to buffer ptr.\n\n Parameters\n ----------\n buf : Buffer\n The buffer to be extracted.\n\n Returns\n -------\n ptr : BufferVar\n The buffer var representing the buffer.\n ' ret...
6f94160edbabeab2751680b90fbfa58aa0d479ee634dc4b42cf7aea9c3eeb453
def likely(self, expr): 'Add likely tag for expression.\n Parameters\n ----------\n expr : Expr\n The expression. Usually a condition expression.\n Returns\n -------\n expr : Expr\n The expression will likely tag.\n ' return _make.Call(expr....
Add likely tag for expression. Parameters ---------- expr : Expr The expression. Usually a condition expression. Returns ------- expr : Expr The expression will likely tag.
third_party/incubator-tvm/python/tvm/ir_builder.py
likely
tianjiashuo/akg
286
python
def likely(self, expr): 'Add likely tag for expression.\n Parameters\n ----------\n expr : Expr\n The expression. Usually a condition expression.\n Returns\n -------\n expr : Expr\n The expression will likely tag.\n ' return _make.Call(expr....
def likely(self, expr): 'Add likely tag for expression.\n Parameters\n ----------\n expr : Expr\n The expression. Usually a condition expression.\n Returns\n -------\n expr : Expr\n The expression will likely tag.\n ' return _make.Call(expr....
bd1083309733bbb5d80242dd60835f3b42204d662c4ee3672eb7c5257608bdf7
def get(self): 'Return the builded IR.\n\n Returns\n -------\n stmt : Stmt\n The result statement.\n ' seq = self._pop_seq() if self._seq_stack: raise RuntimeError('cannot call get inside construction scope') return seq
Return the builded IR. Returns ------- stmt : Stmt The result statement.
third_party/incubator-tvm/python/tvm/ir_builder.py
get
tianjiashuo/akg
286
python
def get(self): 'Return the builded IR.\n\n Returns\n -------\n stmt : Stmt\n The result statement.\n ' seq = self._pop_seq() if self._seq_stack: raise RuntimeError('cannot call get inside construction scope') return seq
def get(self): 'Return the builded IR.\n\n Returns\n -------\n stmt : Stmt\n The result statement.\n ' seq = self._pop_seq() if self._seq_stack: raise RuntimeError('cannot call get inside construction scope') return seq<|docstring|>Return the builded IR. Re...
64885cfb1baee8e81f41d3400e53337333b508e3d39684c059b6f41f9a783f92
def ret_code_is_suspend(self, ret_code): 'docstring for ret_code_is_suspend' return (ret_code == self.FCS_STATE_SUSPEND_PROCESS)
docstring for ret_code_is_suspend
code/freecell_solver/__init__.py
ret_code_is_suspend
shlomif/python-freecell_solver
1
python
def ret_code_is_suspend(self, ret_code): return (ret_code == self.FCS_STATE_SUSPEND_PROCESS)
def ret_code_is_suspend(self, ret_code): return (ret_code == self.FCS_STATE_SUSPEND_PROCESS)<|docstring|>docstring for ret_code_is_suspend<|endoftext|>
54ae38ce0b93fc2b1ef5df910c5d3c7275d6a855be04a85e2124f04bce416ade
def fastq_generate(num_sequences=100, seq_length=75, gzip_output=True, random_seed=42, target_file=None, alphabet=DEFAULT_NUCLEOTIDE_ALPHABET, probabilities=None): '\n Generate a random FASTQ file. PHRED scores will be illumina (+33).\n\n :param num_sequences: Number of separate sequence records to include in...
Generate a random FASTQ file. PHRED scores will be illumina (+33). :param num_sequences: Number of separate sequence records to include in the file. Defaults to 100 records :type num_sequences: int, optional :param seq_length: Length in bases of each individual record in the file, Defaults to 75 bases per record :type...
bio_test_artifacts/generate/fastq.py
fastq_generate
asistradition/bio-test-artifacts
0
python
def fastq_generate(num_sequences=100, seq_length=75, gzip_output=True, random_seed=42, target_file=None, alphabet=DEFAULT_NUCLEOTIDE_ALPHABET, probabilities=None): '\n Generate a random FASTQ file. PHRED scores will be illumina (+33).\n\n :param num_sequences: Number of separate sequence records to include in...
def fastq_generate(num_sequences=100, seq_length=75, gzip_output=True, random_seed=42, target_file=None, alphabet=DEFAULT_NUCLEOTIDE_ALPHABET, probabilities=None): '\n Generate a random FASTQ file. PHRED scores will be illumina (+33).\n\n :param num_sequences: Number of separate sequence records to include in...
9b490e18b888df636a441c25a7f333e68ba4752dc6f03cd4f2d64c83804e594e
def generateData(n, N, filename='filename', data_size=256, dtype='float32'): '\n generateData simulates ftnmr.spectrometer.measure and saves its output as hdf5 files\n \n Parameters\n ----------\n n: int\n n-th data block file index used for hdf5 file naming\n m: int\n Total number o...
generateData simulates ftnmr.spectrometer.measure and saves its output as hdf5 files Parameters ---------- n: int n-th data block file index used for hdf5 file naming m: int Total number of data blocks filename: str Saved data file name without hdf5 extension (default filename) data_size: int Mininum f...
scripts/data.py
generateData
sejin8642/projnmr
0
python
def generateData(n, N, filename='filename', data_size=256, dtype='float32'): '\n generateData simulates ftnmr.spectrometer.measure and saves its output as hdf5 files\n \n Parameters\n ----------\n n: int\n n-th data block file index used for hdf5 file naming\n m: int\n Total number o...
def generateData(n, N, filename='filename', data_size=256, dtype='float32'): '\n generateData simulates ftnmr.spectrometer.measure and saves its output as hdf5 files\n \n Parameters\n ----------\n n: int\n n-th data block file index used for hdf5 file naming\n m: int\n Total number o...
f684edb2fe6258a137001bf7617bf9ab8afbcb319045cb490f0503d9d702948f
def wordBreak(self, s, words): '\n :type s: str\n :type wordDict: List[str]\n :rtype: bool\n ' ok = [True] max_len = max(([0] + map(len, words))) words = set(words) for i in range(1, (len(s) + 1)): ok += (any(((ok[j] and (s[j:i] in words)) for j in range(max(0, (i...
:type s: str :type wordDict: List[str] :rtype: bool
leetcode/139. Word Break.py
wordBreak
isaiahnields/algorithms
0
python
def wordBreak(self, s, words): '\n :type s: str\n :type wordDict: List[str]\n :rtype: bool\n ' ok = [True] max_len = max(([0] + map(len, words))) words = set(words) for i in range(1, (len(s) + 1)): ok += (any(((ok[j] and (s[j:i] in words)) for j in range(max(0, (i...
def wordBreak(self, s, words): '\n :type s: str\n :type wordDict: List[str]\n :rtype: bool\n ' ok = [True] max_len = max(([0] + map(len, words))) words = set(words) for i in range(1, (len(s) + 1)): ok += (any(((ok[j] and (s[j:i] in words)) for j in range(max(0, (i...
d61d06740bda6f8f470c775bf8881469e091d6a47390d630601052711819dea9
def test_statdist(): '``statdist`` should return the stationary distribution.' gen1 = np.array([[(- 1), (2 / 3), (1 / 3)], [(1 / 3), (- 1), (2 / 3)], [(2 / 3), (1 / 3), (- 1)]]) dist1 = np.array([1.0, 1.0, 1.0]) assert np.allclose(statdist(gen1), dist1) gen2 = np.array([[((- 2) / 3), (2 / 3), 0], [(...
``statdist`` should return the stationary distribution.
tests/test_utils.py
test_statdist
dbdr/choix
117
python
def test_statdist(): gen1 = np.array([[(- 1), (2 / 3), (1 / 3)], [(1 / 3), (- 1), (2 / 3)], [(2 / 3), (1 / 3), (- 1)]]) dist1 = np.array([1.0, 1.0, 1.0]) assert np.allclose(statdist(gen1), dist1) gen2 = np.array([[((- 2) / 3), (2 / 3), 0], [(1 / 3), (- 1), (2 / 3)], [0, (1 / 3), ((- 1) / 3)]]) ...
def test_statdist(): gen1 = np.array([[(- 1), (2 / 3), (1 / 3)], [(1 / 3), (- 1), (2 / 3)], [(2 / 3), (1 / 3), (- 1)]]) dist1 = np.array([1.0, 1.0, 1.0]) assert np.allclose(statdist(gen1), dist1) gen2 = np.array([[((- 2) / 3), (2 / 3), 0], [(1 / 3), (- 1), (2 / 3)], [0, (1 / 3), ((- 1) / 3)]]) ...
f90a51d4efad716910a8c41ffbfd1171751b517f6b95e36fad8b9e5cb29c918d
def test_statdist_single_absorbing_class(): '\n ``statdist`` should work when the graph is not strongly connected, but has\n a single absorbing class.\n ' gen = np.array([[(- 1), 1, 0, 0], [1, (- 2), 1, 0], [0, 0, (- 1), 1], [0, 0, 1, (- 1)]], dtype=float) dist = np.array([0.0, 0.0, 2.0, 2.0]) ...
``statdist`` should work when the graph is not strongly connected, but has a single absorbing class.
tests/test_utils.py
test_statdist_single_absorbing_class
dbdr/choix
117
python
def test_statdist_single_absorbing_class(): '\n ``statdist`` should work when the graph is not strongly connected, but has\n a single absorbing class.\n ' gen = np.array([[(- 1), 1, 0, 0], [1, (- 2), 1, 0], [0, 0, (- 1), 1], [0, 0, 1, (- 1)]], dtype=float) dist = np.array([0.0, 0.0, 2.0, 2.0]) ...
def test_statdist_single_absorbing_class(): '\n ``statdist`` should work when the graph is not strongly connected, but has\n a single absorbing class.\n ' gen = np.array([[(- 1), 1, 0, 0], [1, (- 2), 1, 0], [0, 0, (- 1), 1], [0, 0, 1, (- 1)]], dtype=float) dist = np.array([0.0, 0.0, 2.0, 2.0]) ...
b51a220cd73f237617b2dea211a48d09bdded001867a5c5c327b304bbf1d4812
def test_statdist_two_absorbing_classes(): '\n ``statdist`` should fail when the graph is disconnected or has more than\n one absorbing class.\n ' gen1 = np.array([[(- 1), 1, 0, 0, 0], [1, (- 1), 0, 0, 0], [0, 1, (- 2), 1, 0], [0, 0, 0, (- 1), 1], [0, 0, 0, 1, (- 1)]], dtype=float) with pytest.rais...
``statdist`` should fail when the graph is disconnected or has more than one absorbing class.
tests/test_utils.py
test_statdist_two_absorbing_classes
dbdr/choix
117
python
def test_statdist_two_absorbing_classes(): '\n ``statdist`` should fail when the graph is disconnected or has more than\n one absorbing class.\n ' gen1 = np.array([[(- 1), 1, 0, 0, 0], [1, (- 1), 0, 0, 0], [0, 1, (- 2), 1, 0], [0, 0, 0, (- 1), 1], [0, 0, 0, 1, (- 1)]], dtype=float) with pytest.rais...
def test_statdist_two_absorbing_classes(): '\n ``statdist`` should fail when the graph is disconnected or has more than\n one absorbing class.\n ' gen1 = np.array([[(- 1), 1, 0, 0, 0], [1, (- 1), 0, 0, 0], [0, 1, (- 2), 1, 0], [0, 0, 0, (- 1), 1], [0, 0, 0, 1, (- 1)]], dtype=float) with pytest.rais...
78eefed258895d0bb20766761db85fc49b618cd0b4f6bd4440407f0ebef25af9
def test_softmax(): '``softmax`` should work as expected.' params1 = np.array([0, 0, 0]) params2 = np.array([1000, 1000, 2000]) assert np.allclose(softmax(params1), [(1 / 3), (1 / 3), (1 / 3)]) assert np.allclose(softmax(params2), [0, 0, 1])
``softmax`` should work as expected.
tests/test_utils.py
test_softmax
dbdr/choix
117
python
def test_softmax(): params1 = np.array([0, 0, 0]) params2 = np.array([1000, 1000, 2000]) assert np.allclose(softmax(params1), [(1 / 3), (1 / 3), (1 / 3)]) assert np.allclose(softmax(params2), [0, 0, 1])
def test_softmax(): params1 = np.array([0, 0, 0]) params2 = np.array([1000, 1000, 2000]) assert np.allclose(softmax(params1), [(1 / 3), (1 / 3), (1 / 3)]) assert np.allclose(softmax(params2), [0, 0, 1])<|docstring|>``softmax`` should work as expected.<|endoftext|>
4e6ea4b6ee772b470a2fbc67730ee3316f0281d726bb88095bd7f44366a0a1cf
def test_normal_cdf(): '``normal_cdf`` should return the value of the normal CDF.' for x in (3 * RND.randn(10)): np.allclose(normal_cdf(x), sps.norm.cdf(x))
``normal_cdf`` should return the value of the normal CDF.
tests/test_utils.py
test_normal_cdf
dbdr/choix
117
python
def test_normal_cdf(): for x in (3 * RND.randn(10)): np.allclose(normal_cdf(x), sps.norm.cdf(x))
def test_normal_cdf(): for x in (3 * RND.randn(10)): np.allclose(normal_cdf(x), sps.norm.cdf(x))<|docstring|>``normal_cdf`` should return the value of the normal CDF.<|endoftext|>
69e8ef5c106bb214696b672475e2a553d945dd0cd51e7c1f466050a34da95215
def test_normal_pdf(): '``normal_pdf`` should return the value of the normal PDF.' for x in (3 * RND.randn(10)): np.allclose(normal_pdf(x), sps.norm.pdf(x))
``normal_pdf`` should return the value of the normal PDF.
tests/test_utils.py
test_normal_pdf
dbdr/choix
117
python
def test_normal_pdf(): for x in (3 * RND.randn(10)): np.allclose(normal_pdf(x), sps.norm.pdf(x))
def test_normal_pdf(): for x in (3 * RND.randn(10)): np.allclose(normal_pdf(x), sps.norm.pdf(x))<|docstring|>``normal_pdf`` should return the value of the normal PDF.<|endoftext|>
df2c21cafd0e6c85dceb00c2b608a3dc3a5fca65b8a965eb5e5bf9ab1565fa73
def test_inv_posdef(): '``inv_posdef`` should return the correct inverse.' mat = RND.randn(8, 8) mat = mat.dot(mat.T) assert np.allclose(inv_posdef(mat), inv(mat))
``inv_posdef`` should return the correct inverse.
tests/test_utils.py
test_inv_posdef
dbdr/choix
117
python
def test_inv_posdef(): mat = RND.randn(8, 8) mat = mat.dot(mat.T) assert np.allclose(inv_posdef(mat), inv(mat))
def test_inv_posdef(): mat = RND.randn(8, 8) mat = mat.dot(mat.T) assert np.allclose(inv_posdef(mat), inv(mat))<|docstring|>``inv_posdef`` should return the correct inverse.<|endoftext|>
34863a7472bf27b416406e0f0066a5d1d49f32549f06046566ab5b03367574de
def test_generate_params(): '``generate_params`` should work as expected.' params1 = generate_params(10) assert (len(params1) == 10) params2 = generate_params(10, ordered=True) assert (params2.tolist() == sorted(params2))
``generate_params`` should work as expected.
tests/test_utils.py
test_generate_params
dbdr/choix
117
python
def test_generate_params(): params1 = generate_params(10) assert (len(params1) == 10) params2 = generate_params(10, ordered=True) assert (params2.tolist() == sorted(params2))
def test_generate_params(): params1 = generate_params(10) assert (len(params1) == 10) params2 = generate_params(10, ordered=True) assert (params2.tolist() == sorted(params2))<|docstring|>``generate_params`` should work as expected.<|endoftext|>
288ece5e245bba2411d24163ef2d32d8dff3ca11dd007a367c5e4caa53e8e445
def test_generate_pairwise(): '``generate_pairwise`` should work as expected.' params = np.exp(RND.rand(10)) for num in RND.choice(20, size=3, replace=False): data = generate_pairwise(params, num) assert (np.array(data).shape == (num, 2))
``generate_pairwise`` should work as expected.
tests/test_utils.py
test_generate_pairwise
dbdr/choix
117
python
def test_generate_pairwise(): params = np.exp(RND.rand(10)) for num in RND.choice(20, size=3, replace=False): data = generate_pairwise(params, num) assert (np.array(data).shape == (num, 2))
def test_generate_pairwise(): params = np.exp(RND.rand(10)) for num in RND.choice(20, size=3, replace=False): data = generate_pairwise(params, num) assert (np.array(data).shape == (num, 2))<|docstring|>``generate_pairwise`` should work as expected.<|endoftext|>
325ae5717e4b125411972d3b6a008f6815c1a221ec1353536f86503c23c0517d
def test_generate_rankings(): '``generate_rankings`` should work as expected.' n_items = 10 params = np.exp(RND.rand(n_items)) for num in RND.choice(20, size=3, replace=False): size = (1 + RND.choice((n_items - 1))) print(params, num, size) data = generate_rankings(params, num, s...
``generate_rankings`` should work as expected.
tests/test_utils.py
test_generate_rankings
dbdr/choix
117
python
def test_generate_rankings(): n_items = 10 params = np.exp(RND.rand(n_items)) for num in RND.choice(20, size=3, replace=False): size = (1 + RND.choice((n_items - 1))) print(params, num, size) data = generate_rankings(params, num, size=size) assert (np.array(data).shape =...
def test_generate_rankings(): n_items = 10 params = np.exp(RND.rand(n_items)) for num in RND.choice(20, size=3, replace=False): size = (1 + RND.choice((n_items - 1))) print(params, num, size) data = generate_rankings(params, num, size=size) assert (np.array(data).shape =...
752f04782d86e21e391e8357587a5c9acdac83ece0b9dba6b11bc0086fb4462f
def test_compare_choice(): '``compare`` should work as expected for choices.' params1 = np.array([0, 100, (- 100), (- 100), (- 100)]) x1 = compare((3, 0, 2, 4), params1) assert (x1 == 0) x2 = compare((3, 0, 1, 4), params1) assert (x2 == 1) params2 = np.zeros(10) for _ in range(10): ...
``compare`` should work as expected for choices.
tests/test_utils.py
test_compare_choice
dbdr/choix
117
python
def test_compare_choice(): params1 = np.array([0, 100, (- 100), (- 100), (- 100)]) x1 = compare((3, 0, 2, 4), params1) assert (x1 == 0) x2 = compare((3, 0, 1, 4), params1) assert (x2 == 1) params2 = np.zeros(10) for _ in range(10): items = RND.choice(10, size=3, replace=False) ...
def test_compare_choice(): params1 = np.array([0, 100, (- 100), (- 100), (- 100)]) x1 = compare((3, 0, 2, 4), params1) assert (x1 == 0) x2 = compare((3, 0, 1, 4), params1) assert (x2 == 1) params2 = np.zeros(10) for _ in range(10): items = RND.choice(10, size=3, replace=False) ...
c68b1f134c6e10ca53938ca3e51597d1896b61f7cdbb69618d2f146aaba5cbfa
def test_compare_rankings(): '``compare`` should work as expected for rankings.' params = np.array([0, 100, (- 100), (- 100), (- 100)]) x1 = compare((3, 0), params, rank=True) assert np.array_equal(x1, np.array([0, 3])) x2 = compare((3, 0, 1), params, rank=True) assert np.array_equal(x2, np.arra...
``compare`` should work as expected for rankings.
tests/test_utils.py
test_compare_rankings
dbdr/choix
117
python
def test_compare_rankings(): params = np.array([0, 100, (- 100), (- 100), (- 100)]) x1 = compare((3, 0), params, rank=True) assert np.array_equal(x1, np.array([0, 3])) x2 = compare((3, 0, 1), params, rank=True) assert np.array_equal(x2, np.array([1, 0, 3]))
def test_compare_rankings(): params = np.array([0, 100, (- 100), (- 100), (- 100)]) x1 = compare((3, 0), params, rank=True) assert np.array_equal(x1, np.array([0, 3])) x2 = compare((3, 0, 1), params, rank=True) assert np.array_equal(x2, np.array([1, 0, 3]))<|docstring|>``compare`` should work a...
f6934bc2a649e425eae3565bfe210608624e149349c3b10154b1fb221e4f4dd9
def test_probabilities(): '``probabilities`` should work as expected.' params = np.log([1, 2, 3, 4]) assert np.allclose(probabilities([0, 2, 3], params), [(1 / 8), (3 / 8), (4 / 8)]) assert np.allclose(probabilities([1, 0], params), [(2 / 3), (1 / 3)])
``probabilities`` should work as expected.
tests/test_utils.py
test_probabilities
dbdr/choix
117
python
def test_probabilities(): params = np.log([1, 2, 3, 4]) assert np.allclose(probabilities([0, 2, 3], params), [(1 / 8), (3 / 8), (4 / 8)]) assert np.allclose(probabilities([1, 0], params), [(2 / 3), (1 / 3)])
def test_probabilities(): params = np.log([1, 2, 3, 4]) assert np.allclose(probabilities([0, 2, 3], params), [(1 / 8), (3 / 8), (4 / 8)]) assert np.allclose(probabilities([1, 0], params), [(2 / 3), (1 / 3)])<|docstring|>``probabilities`` should work as expected.<|endoftext|>
abeedeef18c37504feaa36379614c22e7bcea478de077ba529387f045afdb485
def _eval(self, context: RuleContext) -> Optional[LintResult]: 'Do not use special characters in object names.' self.quoted_identifiers_policy: str self.unquoted_identifiers_policy: str self.allow_space_in_identifier: bool self.additional_allowed_characters: str self.ignore_words: str self.i...
Do not use special characters in object names.
src/sqlfluff/rules/L057.py
_eval
R7L208/sqlfluff
173
python
def _eval(self, context: RuleContext) -> Optional[LintResult]: self.quoted_identifiers_policy: str self.unquoted_identifiers_policy: str self.allow_space_in_identifier: bool self.additional_allowed_characters: str self.ignore_words: str self.ignore_words_regex: str if (context.segment.n...
def _eval(self, context: RuleContext) -> Optional[LintResult]: self.quoted_identifiers_policy: str self.unquoted_identifiers_policy: str self.allow_space_in_identifier: bool self.additional_allowed_characters: str self.ignore_words: str self.ignore_words_regex: str if (context.segment.n...
9f9e475560ac19f7c70cb03abd7df8a8c1381439ea92d8982db3ae93c1455a2b
def _init_ignore_words_list(self): 'Called first time rule is evaluated to fetch & cache the policy.' ignore_words_config: str = str(getattr(self, 'ignore_words')) if (ignore_words_config and (ignore_words_config != 'None')): self.ignore_words_list = self.split_comma_separated_string(ignore_words_co...
Called first time rule is evaluated to fetch & cache the policy.
src/sqlfluff/rules/L057.py
_init_ignore_words_list
R7L208/sqlfluff
173
python
def _init_ignore_words_list(self): ignore_words_config: str = str(getattr(self, 'ignore_words')) if (ignore_words_config and (ignore_words_config != 'None')): self.ignore_words_list = self.split_comma_separated_string(ignore_words_config.lower()) else: self.ignore_words_list = [] re...
def _init_ignore_words_list(self): ignore_words_config: str = str(getattr(self, 'ignore_words')) if (ignore_words_config and (ignore_words_config != 'None')): self.ignore_words_list = self.split_comma_separated_string(ignore_words_config.lower()) else: self.ignore_words_list = [] re...
a5882d181bdbfaa8121bbbc997a3bf6e700b30ffe37d33472b36bf2bceeb23cf
def load_commute_volume(filename, date_range): 'Loads commute data and clips or extends date range' commute_raw = pd.read_csv(filename, index_col='date') commute_raw.index = pd.to_datetime(commute_raw.index, format='%Y-%m-%d') commute_raw.sort_index(axis=0, inplace=True) commute = pd.DataFrame(index...
Loads commute data and clips or extends date range
covid/pydata.py
load_commute_volume
claudiofronterre/covid19uk
0
python
def load_commute_volume(filename, date_range): commute_raw = pd.read_csv(filename, index_col='date') commute_raw.index = pd.to_datetime(commute_raw.index, format='%Y-%m-%d') commute_raw.sort_index(axis=0, inplace=True) commute = pd.DataFrame(index=np.arange(date_range[0], date_range[1], np.timedelt...
def load_commute_volume(filename, date_range): commute_raw = pd.read_csv(filename, index_col='date') commute_raw.index = pd.to_datetime(commute_raw.index, format='%Y-%m-%d') commute_raw.sort_index(axis=0, inplace=True) commute = pd.DataFrame(index=np.arange(date_range[0], date_range[1], np.timedelt...
37d5a6d85e269f60b3c4ffd48d0daf77f53d646ed3792d4700c91e215b4b9ece
def group_ages(df): '\n Sums age groups\n :param df: a dataframe with columns 0,1,2,...,90\n :return: a dataframe with 5-year age groups\n ' ages = np.arange(90).reshape([(90 // 5), 5]).astype(np.str) grouped_ages = pd.DataFrame() for age_group in ages: grouped_ages[f'[{age_group[0]}...
Sums age groups :param df: a dataframe with columns 0,1,2,...,90 :return: a dataframe with 5-year age groups
covid/pydata.py
group_ages
claudiofronterre/covid19uk
0
python
def group_ages(df): '\n Sums age groups\n :param df: a dataframe with columns 0,1,2,...,90\n :return: a dataframe with 5-year age groups\n ' ages = np.arange(90).reshape([(90 // 5), 5]).astype(np.str) grouped_ages = pd.DataFrame() for age_group in ages: grouped_ages[f'[{age_group[0]}...
def group_ages(df): '\n Sums age groups\n :param df: a dataframe with columns 0,1,2,...,90\n :return: a dataframe with 5-year age groups\n ' ages = np.arange(90).reshape([(90 // 5), 5]).astype(np.str) grouped_ages = pd.DataFrame() for age_group in ages: grouped_ages[f'[{age_group[0]}...
0e5556e75cac08b339d5753fed74ea6e740bf716f856446045e98bc47e72639f
def collapse_commute_data(flow_file): 'Collapses LTLA-based commuting data in England to UTLA areas.\n\n Merges commuting data at LTLA areal basis onto modified UTLA Dec 2019 area.\n\n Modifications:\n E06000052, E06000053 combined\n E09000001, E09000033 combined\n ' filedir = os.path.dirname(os....
Collapses LTLA-based commuting data in England to UTLA areas. Merges commuting data at LTLA areal basis onto modified UTLA Dec 2019 area. Modifications: E06000052, E06000053 combined E09000001, E09000033 combined
covid/pydata.py
collapse_commute_data
claudiofronterre/covid19uk
0
python
def collapse_commute_data(flow_file): 'Collapses LTLA-based commuting data in England to UTLA areas.\n\n Merges commuting data at LTLA areal basis onto modified UTLA Dec 2019 area.\n\n Modifications:\n E06000052, E06000053 combined\n E09000001, E09000033 combined\n ' filedir = os.path.dirname(os....
def collapse_commute_data(flow_file): 'Collapses LTLA-based commuting data in England to UTLA areas.\n\n Merges commuting data at LTLA areal basis onto modified UTLA Dec 2019 area.\n\n Modifications:\n E06000052, E06000053 combined\n E09000001, E09000033 combined\n ' filedir = os.path.dirname(os....
363e0a1a535a90ed987bd6e9fadcba7d99a685fb52405020968623e51c525f25
def collapse_pop(pop_file): 'Aggregates LTLA2019 population data to UTLA2019 and 5-year age groups to 80+' filedir = os.path.dirname(os.path.abspath(__file__)) pop = pd.read_csv(pop_file) pop = pop[pop['lad19cd'].str.startswith('E')] lt_map = pd.read_csv((filedir + '/../data/Lower_Tier_Local_Authori...
Aggregates LTLA2019 population data to UTLA2019 and 5-year age groups to 80+
covid/pydata.py
collapse_pop
claudiofronterre/covid19uk
0
python
def collapse_pop(pop_file): filedir = os.path.dirname(os.path.abspath(__file__)) pop = pd.read_csv(pop_file) pop = pop[pop['lad19cd'].str.startswith('E')] lt_map = pd.read_csv((filedir + '/../data/Lower_Tier_Local_Authority_to_Upper_Tier_Local_Authority_April_2019_Lookup_in_England_and_Wales.csv'))...
def collapse_pop(pop_file): filedir = os.path.dirname(os.path.abspath(__file__)) pop = pd.read_csv(pop_file) pop = pop[pop['lad19cd'].str.startswith('E')] lt_map = pd.read_csv((filedir + '/../data/Lower_Tier_Local_Authority_to_Upper_Tier_Local_Authority_April_2019_Lookup_in_England_and_Wales.csv'))...
213c264c2ce32af05619f4bf9ce89ece3f96fc9e3720eac8d1e5a1971b061051
def main(cfg): 'Runs main training procedure.' seed_everything(seed=cfg['seed']) neptune.init(project_qualified_name=cfg['neptune_project_name'], api_token=cfg['neptune_api_token']) neptune.create_experiment(name=cfg['neptune_experiment'], params=cfg) print('Preparing model and data...') print('...
Runs main training procedure.
src/train.py
main
DIAGNijmegen/pathology-artifact-detection
6
python
def main(cfg): seed_everything(seed=cfg['seed']) neptune.init(project_qualified_name=cfg['neptune_project_name'], api_token=cfg['neptune_api_token']) neptune.create_experiment(name=cfg['neptune_experiment'], params=cfg) print('Preparing model and data...') print('Using SMP version:', smp.__vers...
def main(cfg): seed_everything(seed=cfg['seed']) neptune.init(project_qualified_name=cfg['neptune_project_name'], api_token=cfg['neptune_api_token']) neptune.create_experiment(name=cfg['neptune_experiment'], params=cfg) print('Preparing model and data...') print('Using SMP version:', smp.__vers...
3e10afe97415905e982c04a94b1d8b1d701fec39443b14db6e91356042dad08d
def parse_servers(result: Sequence[Tuple[(str, str, List[str])]]) -> Dict[(str, dict)]: 'Convert servers list (from protocol method "server.peers.subscribe") into dict format.\n Also validate values, such as IP addresses and ports.\n ' servers = {} for item in result: host = item[1] ou...
Convert servers list (from protocol method "server.peers.subscribe") into dict format. Also validate values, such as IP addresses and ports.
electrum/network.py
parse_servers
Jesusown/electrum
5,905
python
def parse_servers(result: Sequence[Tuple[(str, str, List[str])]]) -> Dict[(str, dict)]: 'Convert servers list (from protocol method "server.peers.subscribe") into dict format.\n Also validate values, such as IP addresses and ports.\n ' servers = {} for item in result: host = item[1] ou...
def parse_servers(result: Sequence[Tuple[(str, str, List[str])]]) -> Dict[(str, dict)]: 'Convert servers list (from protocol method "server.peers.subscribe") into dict format.\n Also validate values, such as IP addresses and ports.\n ' servers = {} for item in result: host = item[1] ou...
112d77a8d19e39f7f2863d590d435447e3318a9ecbc071722ff378435976eff0
def filter_protocol(hostmap, *, allowed_protocols: Iterable[str]=None) -> Sequence[ServerAddr]: 'Filters the hostmap for those implementing protocol.' if (allowed_protocols is None): allowed_protocols = {PREFERRED_NETWORK_PROTOCOL} eligible = [] for (host, portmap) in hostmap.items(): fo...
Filters the hostmap for those implementing protocol.
electrum/network.py
filter_protocol
Jesusown/electrum
5,905
python
def filter_protocol(hostmap, *, allowed_protocols: Iterable[str]=None) -> Sequence[ServerAddr]: if (allowed_protocols is None): allowed_protocols = {PREFERRED_NETWORK_PROTOCOL} eligible = [] for (host, portmap) in hostmap.items(): for protocol in allowed_protocols: port = po...
def filter_protocol(hostmap, *, allowed_protocols: Iterable[str]=None) -> Sequence[ServerAddr]: if (allowed_protocols is None): allowed_protocols = {PREFERRED_NETWORK_PROTOCOL} eligible = [] for (host, portmap) in hostmap.items(): for protocol in allowed_protocols: port = po...
b4796b7e3d639790a3062896b6889b14994d422cede45d2aaab9d8867ab2669b
def has_internet_connection(self) -> bool: 'Our guess whether the device has Internet-connectivity.' return self._has_ever_managed_to_connect_to_server
Our guess whether the device has Internet-connectivity.
electrum/network.py
has_internet_connection
Jesusown/electrum
5,905
python
def has_internet_connection(self) -> bool: return self._has_ever_managed_to_connect_to_server
def has_internet_connection(self) -> bool: return self._has_ever_managed_to_connect_to_server<|docstring|>Our guess whether the device has Internet-connectivity.<|endoftext|>
51e47406c9e50266a5a18ea01e2e657547146f0fe4e8f113c4f26a92726c043f
def get_interfaces(self) -> List[ServerAddr]: 'The list of servers for the connected interfaces.' with self.interfaces_lock: return list(self.interfaces)
The list of servers for the connected interfaces.
electrum/network.py
get_interfaces
Jesusown/electrum
5,905
python
def get_interfaces(self) -> List[ServerAddr]: with self.interfaces_lock: return list(self.interfaces)
def get_interfaces(self) -> List[ServerAddr]: with self.interfaces_lock: return list(self.interfaces)<|docstring|>The list of servers for the connected interfaces.<|endoftext|>
501a9dc75e591d8f95ac17540b9a94495ff3c6593cf2d8547df7a2f11d7c482a
async def _switch_to_random_interface(self): 'Switch to a random connected server other than the current one' servers = self.get_interfaces() if (self.default_server in servers): servers.remove(self.default_server) if servers: (await self.switch_to_interface(random.choice(servers)))
Switch to a random connected server other than the current one
electrum/network.py
_switch_to_random_interface
Jesusown/electrum
5,905
python
async def _switch_to_random_interface(self): servers = self.get_interfaces() if (self.default_server in servers): servers.remove(self.default_server) if servers: (await self.switch_to_interface(random.choice(servers)))
async def _switch_to_random_interface(self): servers = self.get_interfaces() if (self.default_server in servers): servers.remove(self.default_server) if servers: (await self.switch_to_interface(random.choice(servers)))<|docstring|>Switch to a random connected server other than the curre...
1747cedc5d43829c2a8d0bea62f0ecd19569208d07c48b09a828c955bf84005d
async def switch_lagging_interface(self): 'If auto_connect and lagging, switch interface (only within fork).' if (self.auto_connect and (await self._server_is_lagging())): best_header = self.blockchain().header_at_tip() with self.interfaces_lock: interfaces = list(self.interfaces.val...
If auto_connect and lagging, switch interface (only within fork).
electrum/network.py
switch_lagging_interface
Jesusown/electrum
5,905
python
async def switch_lagging_interface(self): if (self.auto_connect and (await self._server_is_lagging())): best_header = self.blockchain().header_at_tip() with self.interfaces_lock: interfaces = list(self.interfaces.values()) filtered = list(filter((lambda iface: (iface.tip_hea...
async def switch_lagging_interface(self): if (self.auto_connect and (await self._server_is_lagging())): best_header = self.blockchain().header_at_tip() with self.interfaces_lock: interfaces = list(self.interfaces.values()) filtered = list(filter((lambda iface: (iface.tip_hea...
2b10fc6cd65c14fbbf27d04b6a4886e64cc52fec064aefbd402848d02fb44cff
async def switch_unwanted_fork_interface(self) -> None: 'If auto_connect, maybe switch to another fork/chain.' if ((not self.auto_connect) or (not self.interface)): return with self.interfaces_lock: interfaces = list(self.interfaces.values()) pref_height = self._blockchain_preferred_bloc...
If auto_connect, maybe switch to another fork/chain.
electrum/network.py
switch_unwanted_fork_interface
Jesusown/electrum
5,905
python
async def switch_unwanted_fork_interface(self) -> None: if ((not self.auto_connect) or (not self.interface)): return with self.interfaces_lock: interfaces = list(self.interfaces.values()) pref_height = self._blockchain_preferred_block['height'] pref_hash = self._blockchain_preferred...
async def switch_unwanted_fork_interface(self) -> None: if ((not self.auto_connect) or (not self.interface)): return with self.interfaces_lock: interfaces = list(self.interfaces.values()) pref_height = self._blockchain_preferred_block['height'] pref_hash = self._blockchain_preferred...
61dd56058c5daf6114799d63dbb253e341da76213a9a3110ec3ee470f2b964f5
async def switch_to_interface(self, server: ServerAddr): 'Switch to server as our main interface. If no connection exists,\n queue interface to be started. The actual switch will\n happen when the interface becomes ready.\n ' self.default_server = server old_interface = self.interface ...
Switch to server as our main interface. If no connection exists, queue interface to be started. The actual switch will happen when the interface becomes ready.
electrum/network.py
switch_to_interface
Jesusown/electrum
5,905
python
async def switch_to_interface(self, server: ServerAddr): 'Switch to server as our main interface. If no connection exists,\n queue interface to be started. The actual switch will\n happen when the interface becomes ready.\n ' self.default_server = server old_interface = self.interface ...
async def switch_to_interface(self, server: ServerAddr): 'Switch to server as our main interface. If no connection exists,\n queue interface to be started. The actual switch will\n happen when the interface becomes ready.\n ' self.default_server = server old_interface = self.interface ...
a14d62b01839a055b27fdfa2a97cd755d7cdb033b120b7189b2ece0f5cd31638
async def connection_down(self, interface: Interface): 'A connection to server either went down, or was never made.\n We distinguish by whether it is in self.interfaces.' if (not interface): return if (interface.server == self.default_server): self._set_status('disconnected') (awa...
A connection to server either went down, or was never made. We distinguish by whether it is in self.interfaces.
electrum/network.py
connection_down
Jesusown/electrum
5,905
python
async def connection_down(self, interface: Interface): 'A connection to server either went down, or was never made.\n We distinguish by whether it is in self.interfaces.' if (not interface): return if (interface.server == self.default_server): self._set_status('disconnected') (awa...
async def connection_down(self, interface: Interface): 'A connection to server either went down, or was never made.\n We distinguish by whether it is in self.interfaces.' if (not interface): return if (interface.server == self.default_server): self._set_status('disconnected') (awa...
487487eda4ecdf4b346b57e52fa07c3aa7f21a8ec06d6a34b2785be14b5eed51
def get_server_height(self) -> int: 'Length of header chain, as claimed by main interface.' interface = self.interface return (interface.tip if interface else 0)
Length of header chain, as claimed by main interface.
electrum/network.py
get_server_height
Jesusown/electrum
5,905
python
def get_server_height(self) -> int: interface = self.interface return (interface.tip if interface else 0)
def get_server_height(self) -> int: interface = self.interface return (interface.tip if interface else 0)<|docstring|>Length of header chain, as claimed by main interface.<|endoftext|>
db33a6c105a1ab3f7e6d7472eec61e983d43044e299ae997efa88dc8fdf42e33
def get_local_height(self): 'Length of header chain, POW-verified.\n In case of a chain split, this is for the branch the main interface is on,\n but it is the tip of that branch (even if main interface is behind).\n ' return self.blockchain().height()
Length of header chain, POW-verified. In case of a chain split, this is for the branch the main interface is on, but it is the tip of that branch (even if main interface is behind).
electrum/network.py
get_local_height
Jesusown/electrum
5,905
python
def get_local_height(self): 'Length of header chain, POW-verified.\n In case of a chain split, this is for the branch the main interface is on,\n but it is the tip of that branch (even if main interface is behind).\n ' return self.blockchain().height()
def get_local_height(self): 'Length of header chain, POW-verified.\n In case of a chain split, this is for the branch the main interface is on,\n but it is the tip of that branch (even if main interface is behind).\n ' return self.blockchain().height()<|docstring|>Length of header chain, PO...
d1d8c5095a6cf1b73daf3ef93a197756da179079a18da0d3a8fcfb5c8871f700
def export_checkpoints(self, path): 'Run manually to generate blockchain checkpoints.\n Kept for console use only.\n ' cp = self.blockchain().get_checkpoints() with open(path, 'w', encoding='utf-8') as f: f.write(json.dumps(cp, indent=4))
Run manually to generate blockchain checkpoints. Kept for console use only.
electrum/network.py
export_checkpoints
Jesusown/electrum
5,905
python
def export_checkpoints(self, path): 'Run manually to generate blockchain checkpoints.\n Kept for console use only.\n ' cp = self.blockchain().get_checkpoints() with open(path, 'w', encoding='utf-8') as f: f.write(json.dumps(cp, indent=4))
def export_checkpoints(self, path): 'Run manually to generate blockchain checkpoints.\n Kept for console use only.\n ' cp = self.blockchain().get_checkpoints() with open(path, 'w', encoding='utf-8') as f: f.write(json.dumps(cp, indent=4))<|docstring|>Run manually to generate blockchain...
83b709fded9e1538a436dea6c5d4fb321835520da95649a25584eb8a3e55e783
def start(self, jobs: Iterable=None): 'Schedule starting the network, along with the given job co-routines.\n\n Note: the jobs will *restart* every time the network restarts, e.g. on proxy\n setting changes.\n ' self._jobs = (jobs or []) asyncio.run_coroutine_threadsafe(self._start(), s...
Schedule starting the network, along with the given job co-routines. Note: the jobs will *restart* every time the network restarts, e.g. on proxy setting changes.
electrum/network.py
start
Jesusown/electrum
5,905
python
def start(self, jobs: Iterable=None): 'Schedule starting the network, along with the given job co-routines.\n\n Note: the jobs will *restart* every time the network restarts, e.g. on proxy\n setting changes.\n ' self._jobs = (jobs or []) asyncio.run_coroutine_threadsafe(self._start(), s...
def start(self, jobs: Iterable=None): 'Schedule starting the network, along with the given job co-routines.\n\n Note: the jobs will *restart* every time the network restarts, e.g. on proxy\n setting changes.\n ' self._jobs = (jobs or []) asyncio.run_coroutine_threadsafe(self._start(), s...
32bde37d01af77f9ba86ff20605caa085f5fbde678def981d0f0a13eebe0643c
def perform_destroy(self, instance): '\n perform_destroy is used to performance a logic delete\n ' instance.is_active = (not instance.is_active) instance.save()
perform_destroy is used to performance a logic delete
apps/inventory/viewsets/batch_viewset.py
perform_destroy
luishgranja/superdrogas
8
python
def perform_destroy(self, instance): '\n \n ' instance.is_active = (not instance.is_active) instance.save()
def perform_destroy(self, instance): '\n \n ' instance.is_active = (not instance.is_active) instance.save()<|docstring|>perform_destroy is used to performance a logic delete<|endoftext|>
0f1c790a82724e92ab7ed9e208b3e6f17397e69b11c090ef39b2a7657ae7ff3f
@pytest.mark.parametrize('linter_name, input_msg, output_error, output_warning, output_other', MSG) def test_split_warnings_errors(linter_name, input_msg, output_error, output_warning, output_other): '\n Given:\n - linter name releated to input_msg which was returned from this specific linter.\n\n...
Given: - linter name releated to input_msg which was returned from this specific linter. When: - Running split_warnings_errors on the given inupt. Then: - Ensure that the error, warning, other return values equal to expected.
demisto_sdk/commands/lint/tests/helper_test.py
test_split_warnings_errors
guiguitodelperuu/demisto-sdk
42
python
@pytest.mark.parametrize('linter_name, input_msg, output_error, output_warning, output_other', MSG) def test_split_warnings_errors(linter_name, input_msg, output_error, output_warning, output_other): '\n Given:\n - linter name releated to input_msg which was returned from this specific linter.\n\n...
@pytest.mark.parametrize('linter_name, input_msg, output_error, output_warning, output_other', MSG) def test_split_warnings_errors(linter_name, input_msg, output_error, output_warning, output_other): '\n Given:\n - linter name releated to input_msg which was returned from this specific linter.\n\n...
9abc369714c276cdc1fcb96cc303e5aca54df43344277e8c3201d44ccae34464
def download_blob(source_blob_name: str, destination_file_name: str, project_id: str, bucket_name: str) -> None: 'Downloads a blob from the bucket.' storage_client = storage.Client(project=project_id) bucket = storage_client.bucket(bucket_name) blob = bucket.blob(source_blob_name) blob.download_to_f...
Downloads a blob from the bucket.
torchlit/cloud/gcloud.py
download_blob
himanshu-dutta/torchlit
1
python
def download_blob(source_blob_name: str, destination_file_name: str, project_id: str, bucket_name: str) -> None: storage_client = storage.Client(project=project_id) bucket = storage_client.bucket(bucket_name) blob = bucket.blob(source_blob_name) blob.download_to_filename(destination_file_name) ...
def download_blob(source_blob_name: str, destination_file_name: str, project_id: str, bucket_name: str) -> None: storage_client = storage.Client(project=project_id) bucket = storage_client.bucket(bucket_name) blob = bucket.blob(source_blob_name) blob.download_to_filename(destination_file_name) ...
dc5cfa01ec8877a79e3b45be06efd5b936d13a91014c5cf198d5959bd9a50375
def download_gcs_to_local_directory(source_path: str, project_id: str, bucket_name: str) -> None: 'Downloads a blob from the bucket.' storage_client = storage.Client(project=project_id) bucket = storage_client.get_bucket(bucket_name) blobs = bucket.list_blobs(prefix=source_path) for blob in tqdm(blo...
Downloads a blob from the bucket.
torchlit/cloud/gcloud.py
download_gcs_to_local_directory
himanshu-dutta/torchlit
1
python
def download_gcs_to_local_directory(source_path: str, project_id: str, bucket_name: str) -> None: storage_client = storage.Client(project=project_id) bucket = storage_client.get_bucket(bucket_name) blobs = bucket.list_blobs(prefix=source_path) for blob in tqdm(blobs): if blob.name.endswith(...
def download_gcs_to_local_directory(source_path: str, project_id: str, bucket_name: str) -> None: storage_client = storage.Client(project=project_id) bucket = storage_client.get_bucket(bucket_name) blobs = bucket.list_blobs(prefix=source_path) for blob in tqdm(blobs): if blob.name.endswith(...
08250fcfb54049137f89dd4ae457325e9820005ce588d6101b00d30b9b7e32a8
def list_blobs(source_path: str, project_id: str, bucket_name: str) -> None: 'Downloads a blob from the bucket.' storage_client = storage.Client(project=project_id) bucket = storage_client.get_bucket(bucket_name) blobs = bucket.list_blobs(prefix=source_path) for blob in blobs: print(blob.nam...
Downloads a blob from the bucket.
torchlit/cloud/gcloud.py
list_blobs
himanshu-dutta/torchlit
1
python
def list_blobs(source_path: str, project_id: str, bucket_name: str) -> None: storage_client = storage.Client(project=project_id) bucket = storage_client.get_bucket(bucket_name) blobs = bucket.list_blobs(prefix=source_path) for blob in blobs: print(blob.name)
def list_blobs(source_path: str, project_id: str, bucket_name: str) -> None: storage_client = storage.Client(project=project_id) bucket = storage_client.get_bucket(bucket_name) blobs = bucket.list_blobs(prefix=source_path) for blob in blobs: print(blob.name)<|docstring|>Downloads a blob fro...
0dfe53e5ea3bcf79a81650c9d5a1c5822bc49e431fe6201b4e301c9528b479e4
def max_element(l: list): 'Return maximum element in the list.\n >>> max_element([1, 2, 3])\n 3\n >>> max_element([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10])\n 123\n ' m = l[0] for e in l: if (e > m): m = e return m
Return maximum element in the list. >>> max_element([1, 2, 3]) 3 >>> max_element([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) 123
human_eval/max.py
max_element
LaudateCorpus1/code-align-evals-data
3
python
def max_element(l: list): 'Return maximum element in the list.\n >>> max_element([1, 2, 3])\n 3\n >>> max_element([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10])\n 123\n ' m = l[0] for e in l: if (e > m): m = e return m
def max_element(l: list): 'Return maximum element in the list.\n >>> max_element([1, 2, 3])\n 3\n >>> max_element([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10])\n 123\n ' m = l[0] for e in l: if (e > m): m = e return m<|docstring|>Return maximum element in the list. >>> max_...
5811ae805357900f7fde7fb8d5a75314a5deaa9dc3ca42575c5ff797c8b09cfd
def ParseAmInstrumentRawOutput(raw_output): 'Parses the output of an |am instrument -r| call.\n\n Args:\n raw_output: the output of an |am instrument -r| call as a list of lines\n Returns:\n A 3-tuple containing:\n - the instrumentation code as an integer\n - the instrumentation result as a list o...
Parses the output of an |am instrument -r| call. Args: raw_output: the output of an |am instrument -r| call as a list of lines Returns: A 3-tuple containing: - the instrumentation code as an integer - the instrumentation result as a list of lines - the instrumentation statuses received as a list of 2-t...
build/android/pylib/instrumentation/instrumentation_test_instance.py
ParseAmInstrumentRawOutput
Cela-Inc/WebARonARCore
777
python
def ParseAmInstrumentRawOutput(raw_output): 'Parses the output of an |am instrument -r| call.\n\n Args:\n raw_output: the output of an |am instrument -r| call as a list of lines\n Returns:\n A 3-tuple containing:\n - the instrumentation code as an integer\n - the instrumentation result as a list o...
def ParseAmInstrumentRawOutput(raw_output): 'Parses the output of an |am instrument -r| call.\n\n Args:\n raw_output: the output of an |am instrument -r| call as a list of lines\n Returns:\n A 3-tuple containing:\n - the instrumentation code as an integer\n - the instrumentation result as a list o...
046b1504ab4282e296e6bb530ac9ab1c461fd01a939da1dbae54aba1027c1702
def GenerateTestResults(result_code, result_bundle, statuses, start_ms, duration_ms): 'Generate test results from |statuses|.\n\n Args:\n result_code: The overall status code as an integer.\n result_bundle: The summary bundle dump as a dict.\n statuses: A list of 2-tuples containing:\n - the status c...
Generate test results from |statuses|. Args: result_code: The overall status code as an integer. result_bundle: The summary bundle dump as a dict. statuses: A list of 2-tuples containing: - the status code as an integer - the bundle dump as a dict mapping string keys to string values Note that this i...
build/android/pylib/instrumentation/instrumentation_test_instance.py
GenerateTestResults
Cela-Inc/WebARonARCore
777
python
def GenerateTestResults(result_code, result_bundle, statuses, start_ms, duration_ms): 'Generate test results from |statuses|.\n\n Args:\n result_code: The overall status code as an integer.\n result_bundle: The summary bundle dump as a dict.\n statuses: A list of 2-tuples containing:\n - the status c...
def GenerateTestResults(result_code, result_bundle, statuses, start_ms, duration_ms): 'Generate test results from |statuses|.\n\n Args:\n result_code: The overall status code as an integer.\n result_bundle: The summary bundle dump as a dict.\n statuses: A list of 2-tuples containing:\n - the status c...
6b9bc8b6a609f5383b6cca6a91fd08d57f2fb47ab836565cc0908d98a4092439
def ParseCommandLineFlagParameters(annotations): 'Determines whether the test is parameterized to be run with different\n command-line flags.\n\n Args:\n annotations: The annotations of the test.\n\n Returns:\n If the test is parameterized, returns a list of named tuples\n with lists of flags, e.g.:\...
Determines whether the test is parameterized to be run with different command-line flags. Args: annotations: The annotations of the test. Returns: If the test is parameterized, returns a list of named tuples with lists of flags, e.g.: [(add=['--flag-to-add']), (remove=['--flag-to-remove']), ()] That ...
build/android/pylib/instrumentation/instrumentation_test_instance.py
ParseCommandLineFlagParameters
Cela-Inc/WebARonARCore
777
python
def ParseCommandLineFlagParameters(annotations): 'Determines whether the test is parameterized to be run with different\n command-line flags.\n\n Args:\n annotations: The annotations of the test.\n\n Returns:\n If the test is parameterized, returns a list of named tuples\n with lists of flags, e.g.:\...
def ParseCommandLineFlagParameters(annotations): 'Determines whether the test is parameterized to be run with different\n command-line flags.\n\n Args:\n annotations: The annotations of the test.\n\n Returns:\n If the test is parameterized, returns a list of named tuples\n with lists of flags, e.g.:\...
e4602128d0ab4ab953a56a9984486c0d7c3ce1084d0ef9aa9648176212721d0d
def FilterTests(tests, test_filter=None, annotations=None, excluded_annotations=None): 'Filter a list of tests\n\n Args:\n tests: a list of tests. e.g. [\n {\'annotations": {}, \'class\': \'com.example.TestA\', \'methods\':[]},\n {\'annotations": {}, \'class\': \'com.example.TestB\', \'metho...
Filter a list of tests Args: tests: a list of tests. e.g. [ {'annotations": {}, 'class': 'com.example.TestA', 'methods':[]}, {'annotations": {}, 'class': 'com.example.TestB', 'methods':[]}] test_filter: googletest-style filter string. annotations: a dict of wanted annotations for test methods. ...
build/android/pylib/instrumentation/instrumentation_test_instance.py
FilterTests
Cela-Inc/WebARonARCore
777
python
def FilterTests(tests, test_filter=None, annotations=None, excluded_annotations=None): 'Filter a list of tests\n\n Args:\n tests: a list of tests. e.g. [\n {\'annotations": {}, \'class\': \'com.example.TestA\', \'methods\':[]},\n {\'annotations": {}, \'class\': \'com.example.TestB\', \'metho...
def FilterTests(tests, test_filter=None, annotations=None, excluded_annotations=None): 'Filter a list of tests\n\n Args:\n tests: a list of tests. e.g. [\n {\'annotations": {}, \'class\': \'com.example.TestA\', \'methods\':[]},\n {\'annotations": {}, \'class\': \'com.example.TestB\', \'metho...
d59a5204c6b1fe8337a35b38798c6c0c59e0b0c706ed71e88479a0a53a92a7ae
def GetTestName(test, sep='#'): 'Gets the name of the given test.\n\n Note that this may return the same name for more than one test, e.g. if a\n test is being run multiple times with different parameters.\n\n Args:\n test: the instrumentation test dict.\n sep: the character(s) that should join the class n...
Gets the name of the given test. Note that this may return the same name for more than one test, e.g. if a test is being run multiple times with different parameters. Args: test: the instrumentation test dict. sep: the character(s) that should join the class name and the method name. Returns: The test name as a...
build/android/pylib/instrumentation/instrumentation_test_instance.py
GetTestName
Cela-Inc/WebARonARCore
777
python
def GetTestName(test, sep='#'): 'Gets the name of the given test.\n\n Note that this may return the same name for more than one test, e.g. if a\n test is being run multiple times with different parameters.\n\n Args:\n test: the instrumentation test dict.\n sep: the character(s) that should join the class n...
def GetTestName(test, sep='#'): 'Gets the name of the given test.\n\n Note that this may return the same name for more than one test, e.g. if a\n test is being run multiple times with different parameters.\n\n Args:\n test: the instrumentation test dict.\n sep: the character(s) that should join the class n...
1891ace1eafd530e7e6f1a4d3b1661876a2f267ae151192b5e2c9919abb387bb
def GetUniqueTestName(test, sep='#'): 'Gets the unique name of the given test.\n\n This will include text to disambiguate between tests for which GetTestName\n would return the same name.\n\n Args:\n test: the instrumentation test dict.\n sep: the character(s) that should join the class name and the method...
Gets the unique name of the given test. This will include text to disambiguate between tests for which GetTestName would return the same name. Args: test: the instrumentation test dict. sep: the character(s) that should join the class name and the method name. Returns: The unique test name as a string.
build/android/pylib/instrumentation/instrumentation_test_instance.py
GetUniqueTestName
Cela-Inc/WebARonARCore
777
python
def GetUniqueTestName(test, sep='#'): 'Gets the unique name of the given test.\n\n This will include text to disambiguate between tests for which GetTestName\n would return the same name.\n\n Args:\n test: the instrumentation test dict.\n sep: the character(s) that should join the class name and the method...
def GetUniqueTestName(test, sep='#'): 'Gets the unique name of the given test.\n\n This will include text to disambiguate between tests for which GetTestName\n would return the same name.\n\n Args:\n test: the instrumentation test dict.\n sep: the character(s) that should join the class name and the method...
72efb1887c58b38e2aebc715b15d4efa56805f88d0c064bd1f91a4417cbcb3ce
def generate_cache_key(observable: 'ace.analysis.Observable', amt: 'ace.analysis.AnalysisModuleType') -> str: 'Returns the key that should be used for caching the result of the\n analysis generated by this analysis module type against this observable.' if (observable is None): return None if (amt...
Returns the key that should be used for caching the result of the analysis generated by this analysis module type against this observable.
ace/system/caching.py
generate_cache_key
ace-ecosystem/ace2-core
0
python
def generate_cache_key(observable: 'ace.analysis.Observable', amt: 'ace.analysis.AnalysisModuleType') -> str: 'Returns the key that should be used for caching the result of the\n analysis generated by this analysis module type against this observable.' if (observable is None): return None if (amt...
def generate_cache_key(observable: 'ace.analysis.Observable', amt: 'ace.analysis.AnalysisModuleType') -> str: 'Returns the key that should be used for caching the result of the\n analysis generated by this analysis module type against this observable.' if (observable is None): return None if (amt...
1f7fb20d0aa3f48c3b4447a642c289eac034cc073b73877d7c60bdcb094b95f4
def __init__(self, data_url, citation, url, **kwargs): '\n Args:\n data_url: `string`, url to download the zip file from.\n citation: `string`, citation for the data set.\n url: `string`, url for information about the data set.\n **kwargs: keyword arguments forwarded to super.\n ...
Args: data_url: `string`, url to download the zip file from. citation: `string`, citation for the data set. url: `string`, url for information about the data set. **kwargs: keyword arguments forwarded to super.
datasets/bnl_newspapers/bnl_newspapers.py
__init__
Jebrankhan/datasets
2
python
def __init__(self, data_url, citation, url, **kwargs): '\n Args:\n data_url: `string`, url to download the zip file from.\n citation: `string`, citation for the data set.\n url: `string`, url for information about the data set.\n **kwargs: keyword arguments forwarded to super.\n ...
def __init__(self, data_url, citation, url, **kwargs): '\n Args:\n data_url: `string`, url to download the zip file from.\n citation: `string`, citation for the data set.\n url: `string`, url for information about the data set.\n **kwargs: keyword arguments forwarded to super.\n ...
ba659e418a7f2dbb7734e7aa3c29f9007fe88a310aa73c2b645e04435ae61f00
def _split_generators(self, dl_manager): 'Returns SplitGenerators.' _URL = self.config.data_url data_dir = dl_manager.download_and_extract(_URL) return [datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={'dirpath': data_dir})]
Returns SplitGenerators.
datasets/bnl_newspapers/bnl_newspapers.py
_split_generators
Jebrankhan/datasets
2
python
def _split_generators(self, dl_manager): _URL = self.config.data_url data_dir = dl_manager.download_and_extract(_URL) return [datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={'dirpath': data_dir})]
def _split_generators(self, dl_manager): _URL = self.config.data_url data_dir = dl_manager.download_and_extract(_URL) return [datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={'dirpath': data_dir})]<|docstring|>Returns SplitGenerators.<|endoftext|>
c13fbb3c9101386e4a0a4d1ce4e11180b064ae18d8f66fed2c0956566060f433
def _generate_examples(self, dirpath): 'Yields examples as (key, example) tuples.' ns = {'': 'http://www.openarchives.org/OAI/2.0/', 'xsi': 'http://www.w3.org/2001/XMLSchema-instance', 'oai_dc': 'http://www.openarchives.org/OAI/2.0/oai_dc/', 'dc': 'http://purl.org/dc/elements/1.1/', 'dcterms': 'http://purl.org/...
Yields examples as (key, example) tuples.
datasets/bnl_newspapers/bnl_newspapers.py
_generate_examples
Jebrankhan/datasets
2
python
def _generate_examples(self, dirpath): ns = {: 'http://www.openarchives.org/OAI/2.0/', 'xsi': 'http://www.w3.org/2001/XMLSchema-instance', 'oai_dc': 'http://www.openarchives.org/OAI/2.0/oai_dc/', 'dc': 'http://purl.org/dc/elements/1.1/', 'dcterms': 'http://purl.org/dc/terms/'} for (id_, xml) in enumerate(P...
def _generate_examples(self, dirpath): ns = {: 'http://www.openarchives.org/OAI/2.0/', 'xsi': 'http://www.w3.org/2001/XMLSchema-instance', 'oai_dc': 'http://www.openarchives.org/OAI/2.0/oai_dc/', 'dc': 'http://purl.org/dc/elements/1.1/', 'dcterms': 'http://purl.org/dc/terms/'} for (id_, xml) in enumerate(P...
d3ecd98f20b28a718624a0f30e2088f27ac25c2cac20aa9c6e68214202be5e72
def apk(actual, predicted, k=10): "\n Computes the average precision at k.\n This function computes the average prescision at k between two lists of\n items.\n Parameters\n ----------\n actual : list\n A list of elements that are to be predicted (order doesn't matter)\n predicted : ...
Computes the average precision at k. This function computes the average prescision at k between two lists of items. Parameters ---------- actual : list A list of elements that are to be predicted (order doesn't matter) predicted : list A list of predicted elements (order does matter) k : int, optio...
src/metrics.py
apk
ivallesp/corporacionfavorita
0
python
def apk(actual, predicted, k=10): "\n Computes the average precision at k.\n This function computes the average prescision at k between two lists of\n items.\n Parameters\n ----------\n actual : list\n A list of elements that are to be predicted (order doesn't matter)\n predicted : ...
def apk(actual, predicted, k=10): "\n Computes the average precision at k.\n This function computes the average prescision at k between two lists of\n items.\n Parameters\n ----------\n actual : list\n A list of elements that are to be predicted (order doesn't matter)\n predicted : ...
570529bb77278b46631009031e0298a779d9527571985a31b1dcd2cb289b8526
def mapk(actual, predicted, k=10): "\n Computes the mean average precision at k.\n This function computes the mean average prescision at k between two lists\n of lists of items.\n Parameters\n ----------\n actual : list\n A list of lists of elements that are to be predicted\n ...
Computes the mean average precision at k. This function computes the mean average prescision at k between two lists of lists of items. Parameters ---------- actual : list A list of lists of elements that are to be predicted (order doesn't matter in the lists) predicted : list A list of lis...
src/metrics.py
mapk
ivallesp/corporacionfavorita
0
python
def mapk(actual, predicted, k=10): "\n Computes the mean average precision at k.\n This function computes the mean average prescision at k between two lists\n of lists of items.\n Parameters\n ----------\n actual : list\n A list of lists of elements that are to be predicted\n ...
def mapk(actual, predicted, k=10): "\n Computes the mean average precision at k.\n This function computes the mean average prescision at k between two lists\n of lists of items.\n Parameters\n ----------\n actual : list\n A list of lists of elements that are to be predicted\n ...
7d7576580a3d0339491546bbacf5daeda569e58fb858c0d1b62fe38e78efc245
def in_top_k(y_true, y_pred, k=5): '\n Trims the y_pred to a length of k on the right and calculates the accuracies\n to the y_true.\n :y_true: list of actual values to be predicted (list)\n :y_pred: list of predicted values (ordered by propensity) (list)\n :k: number of predictions to consider (int)...
Trims the y_pred to a length of k on the right and calculates the accuracies to the y_true. :y_true: list of actual values to be predicted (list) :y_pred: list of predicted values (ordered by propensity) (list) :k: number of predictions to consider (int) :return: a list of top_k accuracies (list)
src/metrics.py
in_top_k
ivallesp/corporacionfavorita
0
python
def in_top_k(y_true, y_pred, k=5): '\n Trims the y_pred to a length of k on the right and calculates the accuracies\n to the y_true.\n :y_true: list of actual values to be predicted (list)\n :y_pred: list of predicted values (ordered by propensity) (list)\n :k: number of predictions to consider (int)...
def in_top_k(y_true, y_pred, k=5): '\n Trims the y_pred to a length of k on the right and calculates the accuracies\n to the y_true.\n :y_true: list of actual values to be predicted (list)\n :y_pred: list of predicted values (ordered by propensity) (list)\n :k: number of predictions to consider (int)...
5c0cffd2d43fac4a787e387d7d6da8b7c16b2c7865b7ac7186f881cf08f8d0a0
def top_k_categorical_accuracy(y_true, y_pred, k=5): '\n Trims the y_pred to a length of k by the right and calculates the topK categorical accuracy to the y_true.\n :y_true: list of actual values to be predicted (list)\n :y_pred: list of predicted values (ordered by propensity) (list)\n :k: number of p...
Trims the y_pred to a length of k by the right and calculates the topK categorical accuracy to the y_true. :y_true: list of actual values to be predicted (list) :y_pred: list of predicted values (ordered by propensity) (list) :k: number of predictions to consider (int) :return: the average of the accuracies (float)
src/metrics.py
top_k_categorical_accuracy
ivallesp/corporacionfavorita
0
python
def top_k_categorical_accuracy(y_true, y_pred, k=5): '\n Trims the y_pred to a length of k by the right and calculates the topK categorical accuracy to the y_true.\n :y_true: list of actual values to be predicted (list)\n :y_pred: list of predicted values (ordered by propensity) (list)\n :k: number of p...
def top_k_categorical_accuracy(y_true, y_pred, k=5): '\n Trims the y_pred to a length of k by the right and calculates the topK categorical accuracy to the y_true.\n :y_true: list of actual values to be predicted (list)\n :y_pred: list of predicted values (ordered by propensity) (list)\n :k: number of p...
810879830d60f3de3e19c64bda76f0f3bffeb16f716c8569e85761578a82be72
def top_k_hit_ratio(y_true, y_pred, k=5): '\n Trims the y_pred to a length of k on the right and calculates the hit ratio at k\n :y_true: list of actual values to be predicted (list)\n :y_pred: list of predicted values (ordered by propensity) (list)\n :k: number of predictions to consider (int)\n :re...
Trims the y_pred to a length of k on the right and calculates the hit ratio at k :y_true: list of actual values to be predicted (list) :y_pred: list of predicted values (ordered by propensity) (list) :k: number of predictions to consider (int) :return: the average of the git ratios(float)
src/metrics.py
top_k_hit_ratio
ivallesp/corporacionfavorita
0
python
def top_k_hit_ratio(y_true, y_pred, k=5): '\n Trims the y_pred to a length of k on the right and calculates the hit ratio at k\n :y_true: list of actual values to be predicted (list)\n :y_pred: list of predicted values (ordered by propensity) (list)\n :k: number of predictions to consider (int)\n :re...
def top_k_hit_ratio(y_true, y_pred, k=5): '\n Trims the y_pred to a length of k on the right and calculates the hit ratio at k\n :y_true: list of actual values to be predicted (list)\n :y_pred: list of predicted values (ordered by propensity) (list)\n :k: number of predictions to consider (int)\n :re...
661ec83513d92463e17a2fc985acc4fae755028fa9b68569414aed683ee54a43
def rank_precision_recall_fscore_support_at_k(y_true, y_pred, k=5): '\n Trims the y_pred to a length of k by the right and calculates the average\n accuracies to the y_true.\n :y_true: list of actual values to be predicted (list)\n :y_pred: list of predicted values (ordered by propensity) (list)\n :k...
Trims the y_pred to a length of k by the right and calculates the average accuracies to the y_true. :y_true: list of actual values to be predicted (list) :y_pred: list of predicted values (ordered by propensity) (list) :k: number of predictions to consider (int) :return: the average of the accuracies (float)
src/metrics.py
rank_precision_recall_fscore_support_at_k
ivallesp/corporacionfavorita
0
python
def rank_precision_recall_fscore_support_at_k(y_true, y_pred, k=5): '\n Trims the y_pred to a length of k by the right and calculates the average\n accuracies to the y_true.\n :y_true: list of actual values to be predicted (list)\n :y_pred: list of predicted values (ordered by propensity) (list)\n :k...
def rank_precision_recall_fscore_support_at_k(y_true, y_pred, k=5): '\n Trims the y_pred to a length of k by the right and calculates the average\n accuracies to the y_true.\n :y_true: list of actual values to be predicted (list)\n :y_pred: list of predicted values (ordered by propensity) (list)\n :k...
309c3f7e29ae09149bb15f4970e590d8e341fb05400f4ffc3a6334aa8ab60309
def generate_rank_reports(y_true, y_pred, k_range=None): '\n Given the true values and the predicted ones, it generates a dataframe containing \n the map@k, the topKcategoricalAccuracy and the hitsRatio@K, the precision and recall\n @k by product.\n :y_true: list of actual values to be predicted (list)\...
Given the true values and the predicted ones, it generates a dataframe containing the map@k, the topKcategoricalAccuracy and the hitsRatio@K, the precision and recall @k by product. :y_true: list of actual values to be predicted (list) :y_pred: list of predicted values (ordered by propensity) (list) :k_range: range nu...
src/metrics.py
generate_rank_reports
ivallesp/corporacionfavorita
0
python
def generate_rank_reports(y_true, y_pred, k_range=None): '\n Given the true values and the predicted ones, it generates a dataframe containing \n the map@k, the topKcategoricalAccuracy and the hitsRatio@K, the precision and recall\n @k by product.\n :y_true: list of actual values to be predicted (list)\...
def generate_rank_reports(y_true, y_pred, k_range=None): '\n Given the true values and the predicted ones, it generates a dataframe containing \n the map@k, the topKcategoricalAccuracy and the hitsRatio@K, the precision and recall\n @k by product.\n :y_true: list of actual values to be predicted (list)\...
e0a3045a356557f466cb9e0e0fc2c0f226e41a0b6f89e72b384b66989cc944b2
def mae(truth, preds): '\n Calculates the Mean average error\n :param truth: list of actual values to be predicted (list)\n :param preds: list of predicted values (ordered by propensity) (list)\n :return: the mean absolute error (float)\n ' return np.abs((truth - preds)).mean()
Calculates the Mean average error :param truth: list of actual values to be predicted (list) :param preds: list of predicted values (ordered by propensity) (list) :return: the mean absolute error (float)
src/metrics.py
mae
ivallesp/corporacionfavorita
0
python
def mae(truth, preds): '\n Calculates the Mean average error\n :param truth: list of actual values to be predicted (list)\n :param preds: list of predicted values (ordered by propensity) (list)\n :return: the mean absolute error (float)\n ' return np.abs((truth - preds)).mean()
def mae(truth, preds): '\n Calculates the Mean average error\n :param truth: list of actual values to be predicted (list)\n :param preds: list of predicted values (ordered by propensity) (list)\n :return: the mean absolute error (float)\n ' return np.abs((truth - preds)).mean()<|docstring|>Calcul...
13a639dcd11b5c669e3348cd5af919bf791ac97d73cb402ae12cb566e4802acd
def generate_binary_reports(y_true, y_pred, path, alias='', uplift_bins=100): '\n Given a target variable and a set of predictions, calculates a set of standard metrics to measure the performance\n :param y_true: list of actual values to be predicted (list)\n :param y_pred: list of predicted values (ordere...
Given a target variable and a set of predictions, calculates a set of standard metrics to measure the performance :param y_true: list of actual values to be predicted (list) :param y_pred: list of predicted values (ordered by propensity) (list) :param path: path to the folder where the reports must be saved (str|unicod...
src/metrics.py
generate_binary_reports
ivallesp/corporacionfavorita
0
python
def generate_binary_reports(y_true, y_pred, path, alias=, uplift_bins=100): '\n Given a target variable and a set of predictions, calculates a set of standard metrics to measure the performance\n :param y_true: list of actual values to be predicted (list)\n :param y_pred: list of predicted values (ordered ...
def generate_binary_reports(y_true, y_pred, path, alias=, uplift_bins=100): '\n Given a target variable and a set of predictions, calculates a set of standard metrics to measure the performance\n :param y_true: list of actual values to be predicted (list)\n :param y_pred: list of predicted values (ordered ...
eb82281faf0285b0d88ed935d67e9d5eeaa7d5a432e49d16f433613070b95090
def testSuccess(self): 'test successfully writing a layer' path = os.path.join(unitTestDataPath(), 'raster', 'with_color_table.tif') raster_layer = QgsRasterLayer(path, 'test') self.assertTrue(raster_layer.isValid()) pipe = QgsRasterPipe() self.assertTrue(pipe.set(raster_layer.dataProvider().clo...
test successfully writing a layer
tests/src/python/test_qgsrasterfilewritertask.py
testSuccess
dyna-mis/Hilabeling
0
python
def testSuccess(self): path = os.path.join(unitTestDataPath(), 'raster', 'with_color_table.tif') raster_layer = QgsRasterLayer(path, 'test') self.assertTrue(raster_layer.isValid()) pipe = QgsRasterPipe() self.assertTrue(pipe.set(raster_layer.dataProvider().clone())) tmp = create_temp_filena...
def testSuccess(self): path = os.path.join(unitTestDataPath(), 'raster', 'with_color_table.tif') raster_layer = QgsRasterLayer(path, 'test') self.assertTrue(raster_layer.isValid()) pipe = QgsRasterPipe() self.assertTrue(pipe.set(raster_layer.dataProvider().clone())) tmp = create_temp_filena...
c1e84d243bfe48942fa4bd7fd41dfab8c44ddc57ed7be96ff8a08abb8e853f30
def testLayerRemovalBeforeRun(self): 'test behavior when layer is removed before task begins' path = os.path.join(unitTestDataPath(), 'raster', 'with_color_table.tif') raster_layer = QgsRasterLayer(path, 'test') self.assertTrue(raster_layer.isValid()) pipe = QgsRasterPipe() self.assertTrue(pipe....
test behavior when layer is removed before task begins
tests/src/python/test_qgsrasterfilewritertask.py
testLayerRemovalBeforeRun
dyna-mis/Hilabeling
0
python
def testLayerRemovalBeforeRun(self): path = os.path.join(unitTestDataPath(), 'raster', 'with_color_table.tif') raster_layer = QgsRasterLayer(path, 'test') self.assertTrue(raster_layer.isValid()) pipe = QgsRasterPipe() self.assertTrue(pipe.set(raster_layer.dataProvider().clone())) tmp = crea...
def testLayerRemovalBeforeRun(self): path = os.path.join(unitTestDataPath(), 'raster', 'with_color_table.tif') raster_layer = QgsRasterLayer(path, 'test') self.assertTrue(raster_layer.isValid()) pipe = QgsRasterPipe() self.assertTrue(pipe.set(raster_layer.dataProvider().clone())) tmp = crea...
db691091155e33e8a9ded51fc987d571a4121d936cedc4e45cc3169f6d49b709
@plugin.rule('hello', 'hi', 'hey', 'hello|hi') @plugin.example('hello') def handler(wrapped, trigger): 'This is the doc you are looking for.' wrapped.reply('Hi!')
This is the doc you are looking for.
test/plugins/test_plugins_rules.py
handler
FahimFBA/sopel
555
python
@plugin.rule('hello', 'hi', 'hey', 'hello|hi') @plugin.example('hello') def handler(wrapped, trigger): wrapped.reply('Hi!')
@plugin.rule('hello', 'hi', 'hey', 'hello|hi') @plugin.example('hello') def handler(wrapped, trigger): wrapped.reply('Hi!')<|docstring|>This is the doc you are looking for.<|endoftext|>
c9a0e71b3263797a110a28056ee10fb9d58d891c1892ea07e94d031191255f82
@plugin.rule('hello', 'hi', 'hey', 'hello|hi') @plugin.example('hello') def handler(wrapped, trigger): 'This is the doc you are looking for.\n\n And now with extended text, for testing purpose only.\n ' wrapped.reply('Hi!')
This is the doc you are looking for. And now with extended text, for testing purpose only.
test/plugins/test_plugins_rules.py
handler
FahimFBA/sopel
555
python
@plugin.rule('hello', 'hi', 'hey', 'hello|hi') @plugin.example('hello') def handler(wrapped, trigger): 'This is the doc you are looking for.\n\n And now with extended text, for testing purpose only.\n ' wrapped.reply('Hi!')
@plugin.rule('hello', 'hi', 'hey', 'hello|hi') @plugin.example('hello') def handler(wrapped, trigger): 'This is the doc you are looking for.\n\n And now with extended text, for testing purpose only.\n ' wrapped.reply('Hi!')<|docstring|>This is the doc you are looking for. And now with extended te...
3f62eb4dae80d64ec4a969e29fed6b854cd8828c5f0288b6d2bbe6e1c218d8bc
@pytest.fixture def bobster_columnar_table_multi_batch_normal_mean_5000_stdev_1000_data_context(tmp_path_factory, monkeypatch) -> DataContext: "\n This fixture generates three years' worth (36 months; i.e., 36 batches) of taxi trip data with the number of rows\n of a batch sampled from a normal distribution w...
This fixture generates three years' worth (36 months; i.e., 36 batches) of taxi trip data with the number of rows of a batch sampled from a normal distribution with the mean of 5,000 rows and the standard deviation of 1,000 rows.
tests/rule_based_profiler/conftest.py
bobster_columnar_table_multi_batch_normal_mean_5000_stdev_1000_data_context
cn-karan-mudaliar/great_expectations
6,451
python
@pytest.fixture def bobster_columnar_table_multi_batch_normal_mean_5000_stdev_1000_data_context(tmp_path_factory, monkeypatch) -> DataContext: "\n This fixture generates three years' worth (36 months; i.e., 36 batches) of taxi trip data with the number of rows\n of a batch sampled from a normal distribution w...
@pytest.fixture def bobster_columnar_table_multi_batch_normal_mean_5000_stdev_1000_data_context(tmp_path_factory, monkeypatch) -> DataContext: "\n This fixture generates three years' worth (36 months; i.e., 36 batches) of taxi trip data with the number of rows\n of a batch sampled from a normal distribution w...
37f6217a4e35c09065bf44f6ec91b69333099747b01509b4b5007a51a81e4b51
@pytest.fixture def multi_part_name_parameter_container(): '\n $parameter.date_strings.yyyy_mm_dd_hh_mm_ss_tz_date_format\n $parameter.date_strings.yyyy_mm_dd_date_format\n $parameter.date_strings.mm_yyyy_dd_hh_mm_ss_tz_date_format\n $parameter.date_strings.mm_yyyy_dd_date_format\n $parameter.date_st...
$parameter.date_strings.yyyy_mm_dd_hh_mm_ss_tz_date_format $parameter.date_strings.yyyy_mm_dd_date_format $parameter.date_strings.mm_yyyy_dd_hh_mm_ss_tz_date_format $parameter.date_strings.mm_yyyy_dd_date_format $parameter.date_strings.tolerances.max_abs_error_time_milliseconds $parameter.date_strings.tolerances.max_nu...
tests/rule_based_profiler/conftest.py
multi_part_name_parameter_container
cn-karan-mudaliar/great_expectations
6,451
python
@pytest.fixture def multi_part_name_parameter_container(): '\n $parameter.date_strings.yyyy_mm_dd_hh_mm_ss_tz_date_format\n $parameter.date_strings.yyyy_mm_dd_date_format\n $parameter.date_strings.mm_yyyy_dd_hh_mm_ss_tz_date_format\n $parameter.date_strings.mm_yyyy_dd_date_format\n $parameter.date_st...
@pytest.fixture def multi_part_name_parameter_container(): '\n $parameter.date_strings.yyyy_mm_dd_hh_mm_ss_tz_date_format\n $parameter.date_strings.yyyy_mm_dd_date_format\n $parameter.date_strings.mm_yyyy_dd_hh_mm_ss_tz_date_format\n $parameter.date_strings.mm_yyyy_dd_date_format\n $parameter.date_st...
4b725b08187e07df6e4bb5235519b200d30e59a4bfcf6dab2397bdf66f5a60d4
def merge_config(config): '\n Merge config into global config.\n Args:\n config (dict): Config to be merged.\n Returns: global config\n ' for (key, value) in config.items(): if ('.' not in key): if (isinstance(value, dict) and (key in global_config)): globa...
Merge config into global config. Args: config (dict): Config to be merged. Returns: global config
sugar/tools/program.py
merge_config
mechanicalsea/sugar
4
python
def merge_config(config): '\n Merge config into global config.\n Args:\n config (dict): Config to be merged.\n Returns: global config\n ' for (key, value) in config.items(): if ('.' not in key): if (isinstance(value, dict) and (key in global_config)): globa...
def merge_config(config): '\n Merge config into global config.\n Args:\n config (dict): Config to be merged.\n Returns: global config\n ' for (key, value) in config.items(): if ('.' not in key): if (isinstance(value, dict) and (key in global_config)): globa...
354f0e0b43857b3d2abbad139bad2ec8cea69ac4eb32d6b746b7c470502fb7fa
def load_config(file_path): '\n Load config from yml/yaml file.\n Args:\n file_path (str): Path of the config file to be loaded.\n Returns: global config\n ' (_, ext) = os.path.splitext(file_path) assert (ext in ['.yml', '.yaml']), 'only support yaml files for now' merge_config(yaml.l...
Load config from yml/yaml file. Args: file_path (str): Path of the config file to be loaded. Returns: global config
sugar/tools/program.py
load_config
mechanicalsea/sugar
4
python
def load_config(file_path): '\n Load config from yml/yaml file.\n Args:\n file_path (str): Path of the config file to be loaded.\n Returns: global config\n ' (_, ext) = os.path.splitext(file_path) assert (ext in ['.yml', '.yaml']), 'only support yaml files for now' merge_config(yaml.l...
def load_config(file_path): '\n Load config from yml/yaml file.\n Args:\n file_path (str): Path of the config file to be loaded.\n Returns: global config\n ' (_, ext) = os.path.splitext(file_path) assert (ext in ['.yml', '.yaml']), 'only support yaml files for now' merge_config(yaml.l...
bfe08fb8cb522e482a8b02eda517e554c1bd5c67e60d0bd4467c8a444e49e91d
def check_gpu(use_gpu): '\n Log error and exit when set use_gpu=true in paddlepaddle\n cpu version.\n ' err = 'Config use_gpu cannot be set as true while you are using pytorch cpu version ! \nPlease try: \n\t1. Install pytorch-gpu to run model on GPU \n\t2. Set use_gpu as false in config file to run mo...
Log error and exit when set use_gpu=true in paddlepaddle cpu version.
sugar/tools/program.py
check_gpu
mechanicalsea/sugar
4
python
def check_gpu(use_gpu): '\n Log error and exit when set use_gpu=true in paddlepaddle\n cpu version.\n ' err = 'Config use_gpu cannot be set as true while you are using pytorch cpu version ! \nPlease try: \n\t1. Install pytorch-gpu to run model on GPU \n\t2. Set use_gpu as false in config file to run mo...
def check_gpu(use_gpu): '\n Log error and exit when set use_gpu=true in paddlepaddle\n cpu version.\n ' err = 'Config use_gpu cannot be set as true while you are using pytorch cpu version ! \nPlease try: \n\t1. Install pytorch-gpu to run model on GPU \n\t2. Set use_gpu as false in config file to run mo...
2eb6868a9e6f7132404ec2979ea953289fcbf7ef8d475a776d8453e3a465dbd6
def load_external_lengths(path): 'Loads a length distribution from a plain text file. The file\n must contain blank separated <length>:<score> pairs in each line.\n \n Args:\n path (string): Path to the length file.\n \n Returns:\n list of dicts mapping a length to its scores, one dict ...
Loads a length distribution from a plain text file. The file must contain blank separated <length>:<score> pairs in each line. Args: path (string): Path to the length file. Returns: list of dicts mapping a length to its scores, one dict for each sentence.
cam/sgnmt/predictors/structure.py
load_external_lengths
cimeister/sgnmt
59
python
def load_external_lengths(path): 'Loads a length distribution from a plain text file. The file\n must contain blank separated <length>:<score> pairs in each line.\n \n Args:\n path (string): Path to the length file.\n \n Returns:\n list of dicts mapping a length to its scores, one dict ...
def load_external_lengths(path): 'Loads a length distribution from a plain text file. The file\n must contain blank separated <length>:<score> pairs in each line.\n \n Args:\n path (string): Path to the length file.\n \n Returns:\n list of dicts mapping a length to its scores, one dict ...
4fe9a549807d2c86b181b5e4743fdb9f9611144ee34109bbc6856a82314a2c1a
def update_trg_osm_ids(wmap_path): 'Update the OSM_*_ID variables using a target word map.\n\n Args:\n wmap_path (string): Path to the wmap file.\n ' global OSM_SRC_POP_ID, OSM_SET_MARKER_ID, OSM_JUMP_FWD_ID, OSM_JUMP_BWD_ID, OSM_SRC_POP2_ID, OSM_COPY_ID, OSM_SRC_UNPOP_ID if (not wmap_path): ...
Update the OSM_*_ID variables using a target word map. Args: wmap_path (string): Path to the wmap file.
cam/sgnmt/predictors/structure.py
update_trg_osm_ids
cimeister/sgnmt
59
python
def update_trg_osm_ids(wmap_path): 'Update the OSM_*_ID variables using a target word map.\n\n Args:\n wmap_path (string): Path to the wmap file.\n ' global OSM_SRC_POP_ID, OSM_SET_MARKER_ID, OSM_JUMP_FWD_ID, OSM_JUMP_BWD_ID, OSM_SRC_POP2_ID, OSM_COPY_ID, OSM_SRC_UNPOP_ID if (not wmap_path): ...
def update_trg_osm_ids(wmap_path): 'Update the OSM_*_ID variables using a target word map.\n\n Args:\n wmap_path (string): Path to the wmap file.\n ' global OSM_SRC_POP_ID, OSM_SET_MARKER_ID, OSM_JUMP_FWD_ID, OSM_JUMP_BWD_ID, OSM_SRC_POP2_ID, OSM_COPY_ID, OSM_SRC_UNPOP_ID if (not wmap_path): ...
abc931b1ac28268b015370471e207de9b365e44eb36ceef1ca1a55a7f515254d
def update_src_osm_ids(wmap_path): 'Update the OSM_*_ID variables using a source word map.\n\n Args:\n wmap_path (string): Path to the wmap file.\n ' global OSM_EOP_ID if (not wmap_path): return with open(wmap_path) as f: for line in f: (word, word_id) = line.str...
Update the OSM_*_ID variables using a source word map. Args: wmap_path (string): Path to the wmap file.
cam/sgnmt/predictors/structure.py
update_src_osm_ids
cimeister/sgnmt
59
python
def update_src_osm_ids(wmap_path): 'Update the OSM_*_ID variables using a source word map.\n\n Args:\n wmap_path (string): Path to the wmap file.\n ' global OSM_EOP_ID if (not wmap_path): return with open(wmap_path) as f: for line in f: (word, word_id) = line.str...
def update_src_osm_ids(wmap_path): 'Update the OSM_*_ID variables using a source word map.\n\n Args:\n wmap_path (string): Path to the wmap file.\n ' global OSM_EOP_ID if (not wmap_path): return with open(wmap_path) as f: for line in f: (word, word_id) = line.str...
a26febbbf1989670650ee2841eebc9f91a16578bf8deab849bd65f70de528c24
def __init__(self, src_wmap, trg_wmap, use_jumps=True, use_auto_pop=False, use_unpop=False, use_pop2=False, use_src_eop=False, use_copy=False): 'Creates a new osm predictor.\n\n Args:\n src_wmap (string): Path to the source wmap. Used to grap\n EOP id.\n tr...
Creates a new osm predictor. Args: src_wmap (string): Path to the source wmap. Used to grap EOP id. trg_wmap (string): Path to the target wmap. Used to update IDs of operations. use_jumps (bool): If true, use SET_MARKER, JUMP_FWD and JUMP_...
cam/sgnmt/predictors/structure.py
__init__
cimeister/sgnmt
59
python
def __init__(self, src_wmap, trg_wmap, use_jumps=True, use_auto_pop=False, use_unpop=False, use_pop2=False, use_src_eop=False, use_copy=False): 'Creates a new osm predictor.\n\n Args:\n src_wmap (string): Path to the source wmap. Used to grap\n EOP id.\n tr...
def __init__(self, src_wmap, trg_wmap, use_jumps=True, use_auto_pop=False, use_unpop=False, use_pop2=False, use_src_eop=False, use_copy=False): 'Creates a new osm predictor.\n\n Args:\n src_wmap (string): Path to the source wmap. Used to grap\n EOP id.\n tr...
60dd6a18350e1b3608cb5cb85cbb7ef25e9eb47156051eba1d21510ba079c8c2
def initialize(self, src_sentence): 'Sets the number of source tokens.\n \n Args:\n src_sentence (list): Not used\n ' if self.use_src_eop: self.src_len = (src_sentence.count(OSM_EOP_ID) + 1) else: self.src_len = len(src_sentence) self.n_holes = 0 self....
Sets the number of source tokens. Args: src_sentence (list): Not used
cam/sgnmt/predictors/structure.py
initialize
cimeister/sgnmt
59
python
def initialize(self, src_sentence): 'Sets the number of source tokens.\n \n Args:\n src_sentence (list): Not used\n ' if self.use_src_eop: self.src_len = (src_sentence.count(OSM_EOP_ID) + 1) else: self.src_len = len(src_sentence) self.n_holes = 0 self....
def initialize(self, src_sentence): 'Sets the number of source tokens.\n \n Args:\n src_sentence (list): Not used\n ' if self.use_src_eop: self.src_len = (src_sentence.count(OSM_EOP_ID) + 1) else: self.src_len = len(src_sentence) self.n_holes = 0 self....
8809de341be38e51533cc301bd02c9b302accdc90e54fd7252047e03c9ac543d
def predict_next(self): 'Apply OSM constraints.\n \n Returns:\n dict.\n ' ret = {} if (self.n_pop >= self.src_len): return {utils.EOS_ID: 0.0} else: ret[utils.EOS_ID] = utils.NEG_INF if (self.use_unpop and (self.n_pop <= 0)): ret[OSM_SRC_UNPOP_...
Apply OSM constraints. Returns: dict.
cam/sgnmt/predictors/structure.py
predict_next
cimeister/sgnmt
59
python
def predict_next(self): 'Apply OSM constraints.\n \n Returns:\n dict.\n ' ret = {} if (self.n_pop >= self.src_len): return {utils.EOS_ID: 0.0} else: ret[utils.EOS_ID] = utils.NEG_INF if (self.use_unpop and (self.n_pop <= 0)): ret[OSM_SRC_UNPOP_...
def predict_next(self): 'Apply OSM constraints.\n \n Returns:\n dict.\n ' ret = {} if (self.n_pop >= self.src_len): return {utils.EOS_ID: 0.0} else: ret[utils.EOS_ID] = utils.NEG_INF if (self.use_unpop and (self.n_pop <= 0)): ret[OSM_SRC_UNPOP_...
efd3163e0028445a9fccb08dff5045227a97c7ca9816823f783e275cfd569eff
def consume(self, word): 'Updates the number of holes, EOPs, and the head position.' if (not self._is_pop(word)): if (self.use_unpop and (word == OSM_SRC_UNPOP_ID)): self.n_pop -= 1 else: self.history.append(word) else: self.n_pop += 1 if self.use_jumps: ...
Updates the number of holes, EOPs, and the head position.
cam/sgnmt/predictors/structure.py
consume
cimeister/sgnmt
59
python
def consume(self, word): if (not self._is_pop(word)): if (self.use_unpop and (word == OSM_SRC_UNPOP_ID)): self.n_pop -= 1 else: self.history.append(word) else: self.n_pop += 1 if self.use_jumps: if (word == OSM_SET_MARKER_ID): self.n_h...
def consume(self, word): if (not self._is_pop(word)): if (self.use_unpop and (word == OSM_SRC_UNPOP_ID)): self.n_pop -= 1 else: self.history.append(word) else: self.n_pop += 1 if self.use_jumps: if (word == OSM_SET_MARKER_ID): self.n_h...
5d70dc6e08cc7c1257b31a4fef397266af96ba0ea6560443c3c2c88a10ca046b
def is_equal(self, state1, state2): 'Trivial implementation' return (state1 == state2)
Trivial implementation
cam/sgnmt/predictors/structure.py
is_equal
cimeister/sgnmt
59
python
def is_equal(self, state1, state2): return (state1 == state2)
def is_equal(self, state1, state2): return (state1 == state2)<|docstring|>Trivial implementation<|endoftext|>
973dad8dfca650cb5a40479629ebc9f1cc089316656b2891e23c25bbfab9b52d
def __init__(self, trg_wmap, trg_test_file): 'Creates a new forcedosm predictor.\n\n Args:\n trg_wmap (string): Path to the target wmap file. Used to\n grap OSM operation IDs.\n trg_test_file (string): Path to the plain text file with \n ...
Creates a new forcedosm predictor. Args: trg_wmap (string): Path to the target wmap file. Used to grap OSM operation IDs. trg_test_file (string): Path to the plain text file with the target sentences. Must have the same number of l...
cam/sgnmt/predictors/structure.py
__init__
cimeister/sgnmt
59
python
def __init__(self, trg_wmap, trg_test_file): 'Creates a new forcedosm predictor.\n\n Args:\n trg_wmap (string): Path to the target wmap file. Used to\n grap OSM operation IDs.\n trg_test_file (string): Path to the plain text file with \n ...
def __init__(self, trg_wmap, trg_test_file): 'Creates a new forcedosm predictor.\n\n Args:\n trg_wmap (string): Path to the target wmap file. Used to\n grap OSM operation IDs.\n trg_test_file (string): Path to the plain text file with \n ...
904ac38d0ed34fadbc59d6217571b2e4f41a399f5c24f8c0f61ab99e57fd473e
def initialize(self, src_sentence): 'Resets compiled and head.\n \n Args:\n src_sentence (list): Not used\n ' self.compiled = ['X'] self.head = 0 self.cur_trg_sentence = self.trg_sentences[self.current_sen_id]
Resets compiled and head. Args: src_sentence (list): Not used
cam/sgnmt/predictors/structure.py
initialize
cimeister/sgnmt
59
python
def initialize(self, src_sentence): 'Resets compiled and head.\n \n Args:\n src_sentence (list): Not used\n ' self.compiled = ['X'] self.head = 0 self.cur_trg_sentence = self.trg_sentences[self.current_sen_id]
def initialize(self, src_sentence): 'Resets compiled and head.\n \n Args:\n src_sentence (list): Not used\n ' self.compiled = ['X'] self.head = 0 self.cur_trg_sentence = self.trg_sentences[self.current_sen_id]<|docstring|>Resets compiled and head. Args: src_sentence ...
4afc0b46c1f81c9572a02847768a6c9321f686ac1f8beec2363f3dec14c6daf0
def _is_complete(self): 'Returns true if the compiled sentence contains the right\n number of terminals.\n ' n_terminals = len([s for s in self.compiled if (s != 'X')]) return (n_terminals == len(self.cur_trg_sentence))
Returns true if the compiled sentence contains the right number of terminals.
cam/sgnmt/predictors/structure.py
_is_complete
cimeister/sgnmt
59
python
def _is_complete(self): 'Returns true if the compiled sentence contains the right\n number of terminals.\n ' n_terminals = len([s for s in self.compiled if (s != 'X')]) return (n_terminals == len(self.cur_trg_sentence))
def _is_complete(self): 'Returns true if the compiled sentence contains the right\n number of terminals.\n ' n_terminals = len([s for s in self.compiled if (s != 'X')]) return (n_terminals == len(self.cur_trg_sentence))<|docstring|>Returns true if the compiled sentence contains the right numbe...
cc1b6c7d0657d9d5bff8acf29b7f9f538aa472208583cd4476f81bc58dc121f3
def predict_next(self): 'Apply word reference constraints.\n \n Returns:\n dict.\n ' ret = {OSM_SRC_POP_ID: 0.0} possible_words = self._align() if possible_words[self.head]: ret[OSM_SET_MARKER_ID] = 0.0 if any(possible_words[:self.head]): ret[OSM_JUMP_...
Apply word reference constraints. Returns: dict.
cam/sgnmt/predictors/structure.py
predict_next
cimeister/sgnmt
59
python
def predict_next(self): 'Apply word reference constraints.\n \n Returns:\n dict.\n ' ret = {OSM_SRC_POP_ID: 0.0} possible_words = self._align() if possible_words[self.head]: ret[OSM_SET_MARKER_ID] = 0.0 if any(possible_words[:self.head]): ret[OSM_JUMP_...
def predict_next(self): 'Apply word reference constraints.\n \n Returns:\n dict.\n ' ret = {OSM_SRC_POP_ID: 0.0} possible_words = self._align() if possible_words[self.head]: ret[OSM_SET_MARKER_ID] = 0.0 if any(possible_words[:self.head]): ret[OSM_JUMP_...
aadaa9618b1e4991829622593aa1b51e7a130fa10821769c004117cfc8b41842
def get_unk_probability(self, posterior): 'Always returns -inf.' return utils.NEG_INF
Always returns -inf.
cam/sgnmt/predictors/structure.py
get_unk_probability
cimeister/sgnmt
59
python
def get_unk_probability(self, posterior): return utils.NEG_INF
def get_unk_probability(self, posterior): return utils.NEG_INF<|docstring|>Always returns -inf.<|endoftext|>
af89108dfc80f9da79093deb2b264f812eb76fe9620f7695833a884b6f579512
def consume(self, word): 'Updates the compiled string and the head position.' if (word == OSM_SET_MARKER_ID): self._insert_op('X') elif (word == OSM_JUMP_FWD_ID): self._jump_op(1) elif (word == OSM_JUMP_BWD_ID): self._jump_op((- 1)) elif (word != OSM_SRC_POP_ID): self...
Updates the compiled string and the head position.
cam/sgnmt/predictors/structure.py
consume
cimeister/sgnmt
59
python
def consume(self, word): if (word == OSM_SET_MARKER_ID): self._insert_op('X') elif (word == OSM_JUMP_FWD_ID): self._jump_op(1) elif (word == OSM_JUMP_BWD_ID): self._jump_op((- 1)) elif (word != OSM_SRC_POP_ID): self._insert_op(str(word))
def consume(self, word): if (word == OSM_SET_MARKER_ID): self._insert_op('X') elif (word == OSM_JUMP_FWD_ID): self._jump_op(1) elif (word == OSM_JUMP_BWD_ID): self._jump_op((- 1)) elif (word != OSM_SRC_POP_ID): self._insert_op(str(word))<|docstring|>Updates the compi...
5d70dc6e08cc7c1257b31a4fef397266af96ba0ea6560443c3c2c88a10ca046b
def is_equal(self, state1, state2): 'Trivial implementation' return (state1 == state2)
Trivial implementation
cam/sgnmt/predictors/structure.py
is_equal
cimeister/sgnmt
59
python
def is_equal(self, state1, state2): return (state1 == state2)
def is_equal(self, state1, state2): return (state1 == state2)<|docstring|>Trivial implementation<|endoftext|>
fbba0303c790a7a123ddd42e49a481a43d9ad7877d7e87bec5c8044896db06ba
def __init__(self, max_terminal_id, closing_bracket_id, max_depth=(- 1), extlength_path=''): 'Creates a new bracket predictor.\n \n Args:\n max_terminal_id (int): All IDs greater than this are \n brackets\n closing_bracket_id (string): All brackets except these one...
Creates a new bracket predictor. Args: max_terminal_id (int): All IDs greater than this are brackets closing_bracket_id (string): All brackets except these ones are opening. Comma-separated list of integers. max_depth (int): If positive, restrict the maximum depth extlength_path (stri...
cam/sgnmt/predictors/structure.py
__init__
cimeister/sgnmt
59
python
def __init__(self, max_terminal_id, closing_bracket_id, max_depth=(- 1), extlength_path=): 'Creates a new bracket predictor.\n \n Args:\n max_terminal_id (int): All IDs greater than this are \n brackets\n closing_bracket_id (string): All brackets except these ones ...
def __init__(self, max_terminal_id, closing_bracket_id, max_depth=(- 1), extlength_path=): 'Creates a new bracket predictor.\n \n Args:\n max_terminal_id (int): All IDs greater than this are \n brackets\n closing_bracket_id (string): All brackets except these ones ...
783b2e365f88e93ec8f74c208f306f27c478f833e7690208bf0a676ecbba93b4
def initialize(self, src_sentence): 'Sets the current depth to 0.\n \n Args:\n src_sentence (list): Not used\n ' self.cur_depth = 0 self.ends_with_opening = True self.n_terminals = 0 if self.length_scores: self.cur_length_scores = self.length_scores[self.curre...
Sets the current depth to 0. Args: src_sentence (list): Not used
cam/sgnmt/predictors/structure.py
initialize
cimeister/sgnmt
59
python
def initialize(self, src_sentence): 'Sets the current depth to 0.\n \n Args:\n src_sentence (list): Not used\n ' self.cur_depth = 0 self.ends_with_opening = True self.n_terminals = 0 if self.length_scores: self.cur_length_scores = self.length_scores[self.curre...
def initialize(self, src_sentence): 'Sets the current depth to 0.\n \n Args:\n src_sentence (list): Not used\n ' self.cur_depth = 0 self.ends_with_opening = True self.n_terminals = 0 if self.length_scores: self.cur_length_scores = self.length_scores[self.curre...
22cab50275fbe7fbe5dfb265212e6b724d0fef7362f2617632a927160564ecfb
def predict_next(self, words): 'If the maximum depth is reached, exclude all opening\n brackets. If history is not balanced, exclude EOS. If the\n current depth is zero, exclude closing brackets.\n \n Args:\n words (list): Set of words to score\n Returns:\n d...
If the maximum depth is reached, exclude all opening brackets. If history is not balanced, exclude EOS. If the current depth is zero, exclude closing brackets. Args: words (list): Set of words to score Returns: dict.
cam/sgnmt/predictors/structure.py
predict_next
cimeister/sgnmt
59
python
def predict_next(self, words): 'If the maximum depth is reached, exclude all opening\n brackets. If history is not balanced, exclude EOS. If the\n current depth is zero, exclude closing brackets.\n \n Args:\n words (list): Set of words to score\n Returns:\n d...
def predict_next(self, words): 'If the maximum depth is reached, exclude all opening\n brackets. If history is not balanced, exclude EOS. If the\n current depth is zero, exclude closing brackets.\n \n Args:\n words (list): Set of words to score\n Returns:\n d...
7c466c50ce008d360e164dde66488f12e33d530e370ecc6f8d964fa5b49e8406
def get_unk_probability(self, posterior): 'Always returns 0.0' if ((self.cur_depth == 0) and (not self.ends_with_opening)): return utils.NEG_INF return 0.0
Always returns 0.0
cam/sgnmt/predictors/structure.py
get_unk_probability
cimeister/sgnmt
59
python
def get_unk_probability(self, posterior): if ((self.cur_depth == 0) and (not self.ends_with_opening)): return utils.NEG_INF return 0.0
def get_unk_probability(self, posterior): if ((self.cur_depth == 0) and (not self.ends_with_opening)): return utils.NEG_INF return 0.0<|docstring|>Always returns 0.0<|endoftext|>
6bd30068f206213116cccb90ebaf3cfde2389d58a8be60855f1540e44cd44ab3
def consume(self, word): 'Updates current depth and the number of consumed terminals.' if (word in self.closing_bracket_ids): if self.ends_with_opening: self.n_terminals += 1 self.cur_depth -= 1 self.ends_with_opening = False elif (word > self.max_terminal_id): se...
Updates current depth and the number of consumed terminals.
cam/sgnmt/predictors/structure.py
consume
cimeister/sgnmt
59
python
def consume(self, word): if (word in self.closing_bracket_ids): if self.ends_with_opening: self.n_terminals += 1 self.cur_depth -= 1 self.ends_with_opening = False elif (word > self.max_terminal_id): self.cur_depth += 1 self.ends_with_opening = True
def consume(self, word): if (word in self.closing_bracket_ids): if self.ends_with_opening: self.n_terminals += 1 self.cur_depth -= 1 self.ends_with_opening = False elif (word > self.max_terminal_id): self.cur_depth += 1 self.ends_with_opening = True<|docs...
da8db1fa9da12e154f7db4a95454922709f9d6223988c31fb1c8bc5f7fd36d44
def get_state(self): 'Returns the current depth and number of consumed terminals' return (self.cur_depth, self.n_terminals, self.ends_with_opening)
Returns the current depth and number of consumed terminals
cam/sgnmt/predictors/structure.py
get_state
cimeister/sgnmt
59
python
def get_state(self): return (self.cur_depth, self.n_terminals, self.ends_with_opening)
def get_state(self): return (self.cur_depth, self.n_terminals, self.ends_with_opening)<|docstring|>Returns the current depth and number of consumed terminals<|endoftext|>
7d860c8df482ad80d6c31d5e81bcf25b2b6cccabe27da66f720c831048f9dcd9
def set_state(self, state): 'Sets the current depth and number of consumed terminals' (self.cur_depth, self.n_terminals, self.ends_with_opening) = state
Sets the current depth and number of consumed terminals
cam/sgnmt/predictors/structure.py
set_state
cimeister/sgnmt
59
python
def set_state(self, state): (self.cur_depth, self.n_terminals, self.ends_with_opening) = state
def set_state(self, state): (self.cur_depth, self.n_terminals, self.ends_with_opening) = state<|docstring|>Sets the current depth and number of consumed terminals<|endoftext|>