uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d3f3f7f5facbd7551d122165 | train | function | @assert_no_logs
def test_table_caption_margin_top():
page, = render_pages('''
<style>
table { margin: 20px; }
caption, h1, h2 { margin: 20px; height: 10px }
td { height: 10px }
</style>
<h1></h1>
<table>
<caption></caption>
<tr>
<td></td>
... | @assert_no_logs
def test_table_caption_margin_top():
| page, = render_pages('''
<style>
table { margin: 20px; }
caption, h1, h2 { margin: 20px; height: 10px }
td { height: 10px }
</style>
<h1></h1>
<table>
<caption></caption>
<tr>
<td></td>
</tr>
</table>
<h2></h2>
''')
... | .children
line, = div.children
text1, table_wrapper, text2 = line.children
table, = table_wrapper.children
assert text1.position_y == text2.position_y == 0
assert table.height == 10 * 2
assert table.position_y == table_position_y
@assert_no_logs
def test_table_caption_margin_top():
| 78 | 78 | 260 | 12 | 65 | rfiedorowicz/WeasyPrint | tests/test_layout/test_table.py | Python | test_table_caption_margin_top | test_table_caption_margin_top | 2,618 | 2,644 | 2,618 | 2,619 | 2acd5cf8f90cc6b5a9c72c8fc1d22bd9f62ba8f8 | bigcode/the-stack | train |
b0034123e0b372ceca440968 | train | function | @assert_no_logs
def test_layout_table_auto_50():
# Test regression:
# https://github.com/Kozea/WeasyPrint/issues/685
page, = render_pages('''
<style>@font-face { src: url(AHEM____.TTF); font-family: ahem }</style>
<table style="font-family: ahem; border-spacing: 5px">
<tr><td>a</td><td>a<... | @assert_no_logs
def test_layout_table_auto_50():
# Test regression:
# https://github.com/Kozea/WeasyPrint/issues/685
| page, = render_pages('''
<style>@font-face { src: url(AHEM____.TTF); font-family: ahem }</style>
<table style="font-family: ahem; border-spacing: 5px">
<tr><td>a</td><td>a</td><td>a</td><td>a</td><td>a</td></tr>
<tr>
<td colspan='5'>aaa aaa aaa aaa</td>
</tr>
</table>... | table_wrapper.children
row_group, = table.children
row, = row_group.children
td, = row.children
assert td.width == 48 # 3 * font-size
@assert_no_logs
def test_layout_table_auto_50():
# Test regression:
# https://github.com/Kozea/WeasyPrint/issues/685
| 77 | 77 | 259 | 35 | 41 | rfiedorowicz/WeasyPrint | tests/test_layout/test_table.py | Python | test_layout_table_auto_50 | test_layout_table_auto_50 | 1,514 | 1,536 | 1,514 | 1,517 | f5588cbf160e4b156a4096d54299deac58a6fe22 | bigcode/the-stack | train |
b8a508df966340619ca23aa4 | train | function | @assert_no_logs
def test_layout_table_auto_7():
page, = render_pages('''
<table style="border-spacing: 10px; margin: 5px">
<colgroup>
<col style="width: 20px" />
</colgroup>
<tr>
<td></td>
<td style="width: 40px">a</td>
</tr>
</table>
'''... | @assert_no_logs
def test_layout_table_auto_7():
| page, = render_pages('''
<table style="border-spacing: 10px; margin: 5px">
<colgroup>
<col style="width: 20px" />
</colgroup>
<tr>
<td></td>
<td style="width: 40px">a</td>
</tr>
</table>
''')
html, = page.children
body, = html.chi... | # spacing
assert td_11.width == td_21.width == 4 # minimum width
assert td_12.position_x == 6 # 1 + 5 + sp
assert td_12.width == 14 # available width
assert table.width == 21
@assert_no_logs
def test_layout_table_auto_7():
| 78 | 78 | 261 | 13 | 64 | rfiedorowicz/WeasyPrint | tests/test_layout/test_table.py | Python | test_layout_table_auto_7 | test_layout_table_auto_7 | 451 | 477 | 451 | 452 | 061028463104487a8d554bc24fbabf768bb3fd10 | bigcode/the-stack | train |
f80e67e12ddd535a0476fd1a | train | function | def antismash_load_types(json_file):
"""Load the gene types from the json
The structure of the json is:
{
"cluster-74": {
"end": 12552,
"idx": 74,
"orfs": [
{
"locus_tag": "ctg562_1",
"end": 282,
... | def antismash_load_types(json_file):
| """Load the gene types from the json
The structure of the json is:
{
"cluster-74": {
"end": 12552,
"idx": 74,
"orfs": [
{
"locus_tag": "ctg562_1",
"end": 282,
"description": "<span ...... | = line.split('\t')
_, contig, cluster, entries, *_ = split
contig_id = contig.replace(' ', '-')
if contig_id not in res:
res[contig_id] = []
res[contig_id].extend(list(map(lambda f_id: (f_id, cluster),
entries... | 89 | 89 | 299 | 9 | 79 | hariszaf/pipeline-v5 | docker/scripts_python3/antismash_to_gff.py | Python | antismash_load_types | antismash_load_types | 54 | 88 | 54 | 54 | b518217133fcc245bf4c27f047231da72d49e07d | bigcode/the-stack | train |
a331e00b558f66e774f44e7b | train | function | def build_gff(embl_file, gclusters, as_types, mag=False):
"""Build the GFF from the geneclusters and the EMBL file
"""
entries = SeqIO.parse(embl_file, 'embl')
for entry in entries:
query_name = entry.id
query_description = entry.description
if mag:
query_name = _mags... | def build_gff(embl_file, gclusters, as_types, mag=False):
| """Build the GFF from the geneclusters and the EMBL file
"""
entries = SeqIO.parse(embl_file, 'embl')
for entry in entries:
query_name = entry.id
query_description = entry.description
if mag:
query_name = _mags_name_clean(query_name)
query_name = query_name.re... | else:
attributes.append(['as_type', ['other']])
attributes.append(['as_gene_kind', _get_value(entry_quals, 'gene_kind')])
attributes.append(['product', _get_value(entry_quals, 'product')])
return ';'.join([name + '=' + ','.join(values) for name,values in attributes if len(values)])
def build_gff... | 93 | 93 | 312 | 17 | 76 | hariszaf/pipeline-v5 | docker/scripts_python3/antismash_to_gff.py | Python | build_gff | build_gff | 140 | 178 | 140 | 140 | cd1128b67e2627d0501e7efc7edbbf87c6fd2ebf | bigcode/the-stack | train |
35700c0804a5f438282b775a | train | function | def _clean_as_notes(value):
"""Remove comments that point to antiSMASH HTML images and URLEncode
"""
if '.png' in value:
return ''
else:
return parse.quote(value)
| def _clean_as_notes(value):
| """Remove comments that point to antiSMASH HTML images and URLEncode
"""
if '.png' in value:
return ''
else:
return parse.quote(value)
| 'other')
return feature_types
def _get_value(entry_quals, key, cb=lambda x: x):
"""Get the value from the entry and apply the callback
"""
return list(map(lambda v: cb(v), entry_quals.get(key, [])))
def _clean_as_notes(value):
| 64 | 64 | 47 | 7 | 57 | hariszaf/pipeline-v5 | docker/scripts_python3/antismash_to_gff.py | Python | _clean_as_notes | _clean_as_notes | 95 | 101 | 95 | 95 | 5cc3b4a06554255a93757991f5bfc502feeea5e3 | bigcode/the-stack | train |
0607c958256b4958ae408904 | train | function | def _get_value(entry_quals, key, cb=lambda x: x):
"""Get the value from the entry and apply the callback
"""
return list(map(lambda v: cb(v), entry_quals.get(key, [])))
| def _get_value(entry_quals, key, cb=lambda x: x):
| """Get the value from the entry and apply the callback
"""
return list(map(lambda v: cb(v), entry_quals.get(key, [])))
| in cluster_data.get('orfs', []):
if 'locus_tag' in orf:
feature_types[orf.get('locus_tag')] = orf.get('type', 'other')
return feature_types
def _get_value(entry_quals, key, cb=lambda x: x):
| 64 | 64 | 49 | 16 | 47 | hariszaf/pipeline-v5 | docker/scripts_python3/antismash_to_gff.py | Python | _get_value | _get_value | 90 | 93 | 90 | 90 | ccdb0d4b051472fb3c2fdfda4c1923cbf729b19e | bigcode/the-stack | train |
b0dfcabb2ab5b12d2d94ce65 | train | function | def build_attributes(entry_quals, gc_data, as_types):
"""Convert the CDS features to gff attributes field for an CDS entry
"""
locus_tag = entry_quals.get('locus_tag')[0]
attributes = []
attributes.append(['as_notes', _get_value(entry_quals, 'note', _clean_as_notes)])
attributes.append(['as_gene... | def build_attributes(entry_quals, gc_data, as_types):
| """Convert the CDS features to gff attributes field for an CDS entry
"""
locus_tag = entry_quals.get('locus_tag')[0]
attributes = []
attributes.append(['as_notes', _get_value(entry_quals, 'note', _clean_as_notes)])
attributes.append(['as_gene_functions', _get_value(entry_quals, 'gene_functions')... | _1-NZ_JH815228.1-Fusobacterium-ulcerans-ATCC-49185-genomic
That name is not proper for the .gff file so it is cleaned in order to return:
GUT_GENOME096033_1
"""
return re.sub(r'[-|\s].+', '', query_name)
def build_attributes(entry_quals, gc_data, as_types):
| 87 | 87 | 293 | 13 | 74 | hariszaf/pipeline-v5 | docker/scripts_python3/antismash_to_gff.py | Python | build_attributes | build_attributes | 114 | 138 | 114 | 114 | dee6def59bfb7895c4317e78411eb29a153059bc | bigcode/the-stack | train |
22663d0d5e91ad556e0b7f0a | train | function | def _mags_name_clean(query_name):
"""Clean the MAGs genome name.
MAGs .embl query_name is:
GUT_GENOME096033_1-NZ_JH815228.1-Fusobacterium-ulcerans-ATCC-49185-genomic
That name is not proper for the .gff file so it is cleaned in order to return:
GUT_GENOME096033_1
"""
return re.sub(r'[-... | def _mags_name_clean(query_name):
| """Clean the MAGs genome name.
MAGs .embl query_name is:
GUT_GENOME096033_1-NZ_JH815228.1-Fusobacterium-ulcerans-ATCC-49185-genomic
That name is not proper for the .gff file so it is cleaned in order to return:
GUT_GENOME096033_1
"""
return re.sub(r'[-|\s].+', '', query_name)
| entry_quals.get(key, [])))
def _clean_as_notes(value):
"""Remove comments that point to antiSMASH HTML images and URLEncode
"""
if '.png' in value:
return ''
else:
return parse.quote(value)
def _mags_name_clean(query_name):
| 64 | 64 | 110 | 9 | 55 | hariszaf/pipeline-v5 | docker/scripts_python3/antismash_to_gff.py | Python | _mags_name_clean | _mags_name_clean | 103 | 112 | 103 | 103 | c4e9c42287df00328e8f87129e90dea51a6fc78e | bigcode/the-stack | train |
a7a749293c1c18c990773c88 | train | function | def aggregate_clusters(geneclus_file):
"""Parse the genecluster.txt file and return a dict.
Each entry on the dict:
{
'contig_id': [
'cluster_id' ex. terpene,
[
'features names on embl' ex. ctg467_5
]
]
}
"""
res = {}
with o... | def aggregate_clusters(geneclus_file):
| """Parse the genecluster.txt file and return a dict.
Each entry on the dict:
{
'contig_id': [
'cluster_id' ex. terpene,
[
'features names on embl' ex. ctg467_5
]
]
}
"""
res = {}
with open(geneclus_file, 'r') as reader:
... | or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import argparse
import subprocess
from urllib import parse
import json
import re
from Bio import SeqIO
import logging
logger = logging.getLogger(__name__)
def aggregate_clusters(geneclus_file):
| 64 | 64 | 178 | 8 | 56 | hariszaf/pipeline-v5 | docker/scripts_python3/antismash_to_gff.py | Python | aggregate_clusters | aggregate_clusters | 30 | 52 | 30 | 30 | 5262a088a9181902b7d739f4a6df92d5ae97ea37 | bigcode/the-stack | train |
9353549251028506bd0dddd6 | train | function | def run_profile():
import profile
profile.run("for i in range(1): demo()", "/tmp/profile.out")
import pstats
p = pstats.Stats("/tmp/profile.out")
p.strip_dirs().sort_stats("time", "cum").print_stats(60)
p.strip_dirs().sort_stats("cum", "time").print_stats(60)
| def run_profile():
| import profile
profile.run("for i in range(1): demo()", "/tmp/profile.out")
import pstats
p = pstats.Stats("/tmp/profile.out")
p.strip_dirs().sort_stats("time", "cum").print_stats(60)
p.strip_dirs().sort_stats("cum", "time").print_stats(60)
| trees = list(chart.parses(grammar.start()))
if print_times:
print("Time: %s" % (perf_counter() - t))
if print_trees:
for tree in trees:
print(tree)
else:
print("Nr trees:", len(trees))
def run_profile():
| 64 | 64 | 79 | 4 | 60 | Pandinosaurus/nltk | nltk/parse/featurechart.py | Python | run_profile | run_profile | 652 | 660 | 652 | 652 | ddf3b9f7b26f003d00fb2427a2d207e0a9790f11 | bigcode/the-stack | train |
5bf158aeb0d03a22defb6d68 | train | class | class InstantiateVarsChart(FeatureChart):
"""
A specialized chart that 'instantiates' variables whose names
start with '@', by replacing them with unique new variables.
In particular, whenever a complete edge is added to the chart, any
variables in the edge's ``lhs`` whose names start with '@' will ... | class InstantiateVarsChart(FeatureChart):
| """
A specialized chart that 'instantiates' variables whose names
start with '@', by replacing them with unique new variables.
In particular, whenever a complete edge is added to the chart, any
variables in the edge's ``lhs`` whose names start with '@' will be
replaced by unique new ``Variable``... | ATEGY, **parser_args)
class FeatureBottomUpChartParser(FeatureChartParser):
def __init__(self, grammar, **parser_args):
FeatureChartParser.__init__(self, grammar, BU_FEATURE_STRATEGY, **parser_args)
class FeatureBottomUpLeftCornerChartParser(FeatureChartParser):
def __init__(self, grammar, **parser_... | 125 | 126 | 421 | 8 | 117 | Pandinosaurus/nltk | nltk/parse/featurechart.py | Python | InstantiateVarsChart | InstantiateVarsChart | 527 | 583 | 527 | 527 | 3a37a57e2d46e424f756173e93ed57bfbaea8ae3 | bigcode/the-stack | train |
487bd417d3fa8c25b1b4eddb | train | function | def demo_grammar():
from nltk.grammar import FeatureGrammar
return FeatureGrammar.fromstring(
"""
S -> NP VP
PP -> Prep NP
NP -> NP PP
VP -> VP PP
VP -> Verb NP
VP -> Verb
NP -> Det[pl=?x] Noun[pl=?x]
NP -> "John"
NP -> "I"
Det -> "the"
Det -> "my"
Det[-pl] -> "a"
Noun[-pl] -> "dog"
Noun[-pl] -> "cook... | def demo_grammar():
| from nltk.grammar import FeatureGrammar
return FeatureGrammar.fromstring(
"""
S -> NP VP
PP -> Prep NP
NP -> NP PP
VP -> VP PP
VP -> Verb NP
VP -> Verb
NP -> Det[pl=?x] Noun[pl=?x]
NP -> "John"
NP -> "I"
Det -> "the"
Det -> "my"
Det[-pl] -> "a"
Noun[-pl] -> "dog"
Noun[-pl] -> "cookie"
Verb -> "ate"
Ve... | .lhs().substitute_bindings(inst_vars)
def inst_vars(self, edge):
return {
var: logic.unique_variable()
for var in edge.lhs().variables()
if var.name.startswith("@")
}
# ////////////////////////////////////////////////////////////
# Demo
# //////////////////////... | 63 | 64 | 138 | 5 | 58 | Pandinosaurus/nltk | nltk/parse/featurechart.py | Python | demo_grammar | demo_grammar | 591 | 615 | 591 | 591 | 2c424ae8a45d1c0481d8bc2d8d9de9f7792859ec | bigcode/the-stack | train |
5222a9991497cd3c2dd2daf2 | train | class | class FeatureSingleEdgeFundamentalRule(SingleEdgeFundamentalRule):
"""
A specialized version of the completer / single edge fundamental rule
that operates on nonterminals whose symbols are ``FeatStructNonterminal``s.
Rather than simply comparing the nonterminals for equality, they are
unified.
"... | class FeatureSingleEdgeFundamentalRule(SingleEdgeFundamentalRule):
| """
A specialized version of the completer / single edge fundamental rule
that operates on nonterminals whose symbols are ``FeatStructNonterminal``s.
Rather than simply comparing the nonterminals for equality, they are
unified.
"""
_fundamental_rule = FeatureFundamentalRule()
def _appl... | .
new_edge = left_edge.move_dot_forward(right_edge.end(), bindings)
# Add it to the chart, with appropriate child pointers.
if chart.insert_with_backpointer(new_edge, left_edge, right_edge):
yield new_edge
class FeatureSingleEdgeFundamentalRule(SingleEdgeFundamentalRule):
| 64 | 64 | 213 | 14 | 49 | Pandinosaurus/nltk | nltk/parse/featurechart.py | Python | FeatureSingleEdgeFundamentalRule | FeatureSingleEdgeFundamentalRule | 309 | 331 | 309 | 309 | 5d57b2774528b49a44b06b2624e94c679a6f5f60 | bigcode/the-stack | train |
1bec368fdc8d574ac78f76d1 | train | function | def demo(
print_times=True,
print_grammar=True,
print_trees=True,
print_sentence=True,
trace=1,
parser=FeatureChartParser,
sent="I saw John with a dog with my cookie",
):
import sys
import time
print()
grammar = demo_grammar()
if print_grammar:
print(grammar)
... | def demo(
print_times=True,
print_grammar=True,
print_trees=True,
print_sentence=True,
trace=1,
parser=FeatureChartParser,
sent="I saw John with a dog with my cookie",
):
| import sys
import time
print()
grammar = demo_grammar()
if print_grammar:
print(grammar)
print()
print("*", parser.__name__)
if print_sentence:
print("Sentence:", sent)
tokens = sent.split()
t = perf_counter()
cp = parser(grammar, trace=trace)
chart =... | Prep -> "with"
Prep -> "under"
"""
)
def demo(
print_times=True,
print_grammar=True,
print_trees=True,
print_sentence=True,
trace=1,
parser=FeatureChartParser,
sent="I saw John with a dog with my cookie",
):
| 64 | 64 | 192 | 51 | 13 | Pandinosaurus/nltk | nltk/parse/featurechart.py | Python | demo | demo | 618 | 649 | 618 | 626 | 75164e0b9fd74c08e5f286881f6985f8000db081 | bigcode/the-stack | train |
f05fca58407ef333e29f087b | train | class | class FeatureBottomUpPredictCombineRule(BottomUpPredictCombineRule):
def apply(self, chart, grammar, edge):
if edge.is_incomplete():
return
found = edge.lhs()
for prod in grammar.productions(rhs=found):
bindings = {}
if isinstance(edge, FeatureTreeEdge):
... | class FeatureBottomUpPredictCombineRule(BottomUpPredictCombineRule):
| def apply(self, chart, grammar, edge):
if edge.is_incomplete():
return
found = edge.lhs()
for prod in grammar.productions(rhs=found):
bindings = {}
if isinstance(edge, FeatureTreeEdge):
_next = prod.rhs()[0]
if not is_nonter... | _next = prod.rhs()[0]
if not is_nonterminal(_next):
continue
new_edge = FeatureTreeEdge.from_production(prod, edge.start())
if chart.insert(new_edge, ()):
yield new_edge
class FeatureBottomUpPredictCombineRule(BottomUpPredictCo... | 65 | 65 | 219 | 14 | 50 | Pandinosaurus/nltk | nltk/parse/featurechart.py | Python | FeatureBottomUpPredictCombineRule | FeatureBottomUpPredictCombineRule | 423 | 450 | 423 | 423 | 57a33748a7bb895aa4c5c499182c26f6cf033982 | bigcode/the-stack | train |
406808d049bdf617c8f11eaa | train | class | class FeatureEmptyPredictRule(EmptyPredictRule):
def apply(self, chart, grammar):
for prod in grammar.productions(empty=True):
for index in range(chart.num_leaves() + 1):
new_edge = FeatureTreeEdge.from_production(prod, index)
if chart.insert(new_edge, ()):
... | class FeatureEmptyPredictRule(EmptyPredictRule):
| def apply(self, chart, grammar):
for prod in grammar.productions(empty=True):
for index in range(chart.num_leaves() + 1):
new_edge = FeatureTreeEdge.from_production(prod, index)
if chart.insert(new_edge, ()):
yield new_edge
| =False)
if result is None:
continue
new_edge = FeatureTreeEdge.from_production(
prod, edge.start()
).move_dot_forward(edge.end(), bindings)
if chart.insert(new_edge, (edge,)):
yield new_edge
class FeatureEmptyPredic... | 64 | 64 | 72 | 10 | 53 | Pandinosaurus/nltk | nltk/parse/featurechart.py | Python | FeatureEmptyPredictRule | FeatureEmptyPredictRule | 453 | 459 | 453 | 453 | c14eb12d45a2b467be0a526abe4fc9aeb09b3eef | bigcode/the-stack | train |
050d6b02b6b3ae3164325c2d | train | class | class FeatureBottomUpLeftCornerChartParser(FeatureChartParser):
def __init__(self, grammar, **parser_args):
FeatureChartParser.__init__(
self, grammar, BU_LC_FEATURE_STRATEGY, **parser_args
)
| class FeatureBottomUpLeftCornerChartParser(FeatureChartParser):
| def __init__(self, grammar, **parser_args):
FeatureChartParser.__init__(
self, grammar, BU_LC_FEATURE_STRATEGY, **parser_args
)
| Y, **parser_args)
class FeatureBottomUpChartParser(FeatureChartParser):
def __init__(self, grammar, **parser_args):
FeatureChartParser.__init__(self, grammar, BU_FEATURE_STRATEGY, **parser_args)
class FeatureBottomUpLeftCornerChartParser(FeatureChartParser):
| 64 | 64 | 52 | 13 | 51 | Pandinosaurus/nltk | nltk/parse/featurechart.py | Python | FeatureBottomUpLeftCornerChartParser | FeatureBottomUpLeftCornerChartParser | 515 | 519 | 515 | 515 | b408d1433d825e0cc00c99501eac9e3acf98e453 | bigcode/the-stack | train |
3ed92691a7a8e8ed494f16d9 | train | class | class FeatureTopDownPredictRule(CachedTopDownPredictRule):
r"""
A specialized version of the (cached) top down predict rule that operates
on nonterminals whose symbols are ``FeatStructNonterminal``s. Rather
than simply comparing the nonterminals for equality, they are
unified.
The top down exp... | class FeatureTopDownPredictRule(CachedTopDownPredictRule):
| r"""
A specialized version of the (cached) top down predict rule that operates
on nonterminals whose symbols are ``FeatStructNonterminal``s. Rather
than simply comparing the nonterminals for equality, they are
unified.
The top down expand rule states that:
- ``[A -> alpha \* B1 beta][i:j]... | fundamental_rule
for right_edge in chart.select(
start=left_edge.end(), is_complete=True, lhs=left_edge.nextsym()
):
yield from fr.apply(chart, grammar, left_edge, right_edge)
# ////////////////////////////////////////////////////////////
# Top-Down Prediction
# ///////////////... | 138 | 138 | 463 | 13 | 124 | Pandinosaurus/nltk | nltk/parse/featurechart.py | Python | FeatureTopDownPredictRule | FeatureTopDownPredictRule | 347 | 400 | 347 | 347 | 642ad5061a8234d01d922eb734ec195ecfb47626 | bigcode/the-stack | train |
68f4d75971da63623b7a778c | train | class | class FeatureFundamentalRule(FundamentalRule):
r"""
A specialized version of the fundamental rule that operates on
nonterminals whose symbols are ``FeatStructNonterminal``s. Rather
than simply comparing the nonterminals for equality, they are
unified. Variable bindings from these unifications are ... | class FeatureFundamentalRule(FundamentalRule):
| r"""
A specialized version of the fundamental rule that operates on
nonterminals whose symbols are ``FeatStructNonterminal``s. Rather
than simply comparing the nonterminals for equality, they are
unified. Variable bindings from these unifications are collected
and stored in the chart using a `... | if it exists, otherwise it returns the ``item`` itself
"""
if isinstance(item, dict) and TYPE in item:
return item[TYPE]
else:
return item
def parses(self, start, tree_class=Tree):
for edge in self.select(start=0, end=self._num_leaves):
if (
... | 152 | 153 | 513 | 10 | 142 | Pandinosaurus/nltk | nltk/parse/featurechart.py | Python | FeatureFundamentalRule | FeatureFundamentalRule | 247 | 306 | 247 | 247 | 084b29a65529d8f3ef911e643327e22d719e42ca | bigcode/the-stack | train |
6d798ab7452e68d95bfbf632 | train | class | class FeatureBottomUpPredictRule(BottomUpPredictRule):
def apply(self, chart, grammar, edge):
if edge.is_incomplete():
return
for prod in grammar.productions(rhs=edge.lhs()):
if isinstance(edge, FeatureTreeEdge):
_next = prod.rhs()[0]
if not is... | class FeatureBottomUpPredictRule(BottomUpPredictRule):
| def apply(self, chart, grammar, edge):
if edge.is_incomplete():
return
for prod in grammar.productions(rhs=edge.lhs()):
if isinstance(edge, FeatureTreeEdge):
_next = prod.rhs()[0]
if not is_nonterminal(_next):
continue
... | _edge, ()):
yield new_edge
# Record the fact that we've applied this rule.
self._done[nextsym_with_bindings, index] = (chart, grammar)
# ////////////////////////////////////////////////////////////
# Bottom-Up Prediction
# //////////////////////////////////////////////////////////... | 63 | 64 | 106 | 12 | 51 | Pandinosaurus/nltk | nltk/parse/featurechart.py | Python | FeatureBottomUpPredictRule | FeatureBottomUpPredictRule | 408 | 420 | 408 | 408 | 05091c8cc712201c19c3cd20659f7d84e626d215 | bigcode/the-stack | train |
4c274f53c80b007353a54099 | train | class | class FeatureChart(Chart):
"""
A Chart for feature grammars.
:see: ``Chart`` for more information.
"""
def select(self, **restrictions):
"""
Returns an iterator over the edges in this chart.
See ``Chart.select`` for more information about the
``restrictions`` on the ... | class FeatureChart(Chart):
| """
A Chart for feature grammars.
:see: ``Chart`` for more information.
"""
def select(self, **restrictions):
"""
Returns an iterator over the edges in this chart.
See ``Chart.select`` for more information about the
``restrictions`` on the edges.
"""
... | self._bindings.copy()
def variables(self):
"""
:return: The set of variables used by this edge.
:rtype: set(Variable)
"""
return find_variables(
[self._lhs]
+ list(self._rhs)
+ list(self._bindings.keys())
+ list(self._bindings... | 179 | 179 | 598 | 6 | 172 | Pandinosaurus/nltk | nltk/parse/featurechart.py | Python | FeatureChart | FeatureChart | 162 | 239 | 162 | 162 | eaa6293e61a1348d5d1dd6652285e8234436a36b | bigcode/the-stack | train |
efe0f8bb653b16e5efca5b37 | train | class | class FeatureTreeEdge(TreeEdge):
"""
A specialized tree edge that allows shared variable bindings
between nonterminals on the left-hand side and right-hand side.
Each ``FeatureTreeEdge`` contains a set of ``bindings``, i.e., a
dictionary mapping from variables to values. If the edge is not
com... | class FeatureTreeEdge(TreeEdge):
| """
A specialized tree edge that allows shared variable bindings
between nonterminals on the left-hand side and right-hand side.
Each ``FeatureTreeEdge`` contains a set of ``bindings``, i.e., a
dictionary mapping from variables to values. If the edge is not
complete, then these bindings are si... | Natural Language Toolkit: Chart Parser for Feature-Based Grammars
#
# Copyright (C) 2001-2021 NLTK Project
# Author: Rob Speer <rspeer@mit.edu>
# Peter Ljunglöf <peter.ljunglof@heatherleaf.se>
# URL: <http://nltk.org/>
# For license information, see LICENSE.TXT
"""
Extension of chart parsing implementation to... | 255 | 256 | 902 | 7 | 248 | Pandinosaurus/nltk | nltk/parse/featurechart.py | Python | FeatureTreeEdge | FeatureTreeEdge | 46 | 152 | 46 | 46 | 848d26f8eb074822527fa2e911e208c1bac2e21c | bigcode/the-stack | train |
c907dde8fe0a82aec91fc8a0 | train | class | class FeatureTopDownChartParser(FeatureChartParser):
def __init__(self, grammar, **parser_args):
FeatureChartParser.__init__(self, grammar, TD_FEATURE_STRATEGY, **parser_args)
| class FeatureTopDownChartParser(FeatureChartParser):
| def __init__(self, grammar, **parser_args):
FeatureChartParser.__init__(self, grammar, TD_FEATURE_STRATEGY, **parser_args)
| chart_class=FeatureChart,
**parser_args,
):
ChartParser.__init__(
self,
grammar,
strategy=strategy,
trace_chart_width=trace_chart_width,
chart_class=chart_class,
**parser_args,
)
class FeatureTopDownChartParser(FeatureC... | 64 | 64 | 45 | 11 | 53 | Pandinosaurus/nltk | nltk/parse/featurechart.py | Python | FeatureTopDownChartParser | FeatureTopDownChartParser | 505 | 507 | 505 | 505 | cd75bd6e3e3e16a9732a5d03024ed2470722ac8d | bigcode/the-stack | train |
867f4bf1a35293a6197cfc26 | train | class | class FeatureBottomUpChartParser(FeatureChartParser):
def __init__(self, grammar, **parser_args):
FeatureChartParser.__init__(self, grammar, BU_FEATURE_STRATEGY, **parser_args)
| class FeatureBottomUpChartParser(FeatureChartParser):
| def __init__(self, grammar, **parser_args):
FeatureChartParser.__init__(self, grammar, BU_FEATURE_STRATEGY, **parser_args)
| ,
**parser_args,
)
class FeatureTopDownChartParser(FeatureChartParser):
def __init__(self, grammar, **parser_args):
FeatureChartParser.__init__(self, grammar, TD_FEATURE_STRATEGY, **parser_args)
class FeatureBottomUpChartParser(FeatureChartParser):
| 64 | 64 | 45 | 11 | 53 | Pandinosaurus/nltk | nltk/parse/featurechart.py | Python | FeatureBottomUpChartParser | FeatureBottomUpChartParser | 510 | 512 | 510 | 510 | 3ddd15cea06ac284d0f40868d494a5c1412ab945 | bigcode/the-stack | train |
8d22f52675a9ff9035f72b71 | train | class | class FeatureChartParser(ChartParser):
def __init__(
self,
grammar,
strategy=BU_LC_FEATURE_STRATEGY,
trace_chart_width=20,
chart_class=FeatureChart,
**parser_args,
):
ChartParser.__init__(
self,
grammar,
strategy=strateg... | class FeatureChartParser(ChartParser):
| def __init__(
self,
grammar,
strategy=BU_LC_FEATURE_STRATEGY,
trace_chart_width=20,
chart_class=FeatureChart,
**parser_args,
):
ChartParser.__init__(
self,
grammar,
strategy=strategy,
trace_chart_width=trace_... | PredictRule(),
FeatureBottomUpPredictRule(),
FeatureSingleEdgeFundamentalRule(),
]
BU_LC_FEATURE_STRATEGY = [
LeafInitRule(),
FeatureEmptyPredictRule(),
FeatureBottomUpPredictCombineRule(),
FeatureSingleEdgeFundamentalRule(),
]
class FeatureChartParser(ChartParser):
| 64 | 64 | 91 | 8 | 56 | Pandinosaurus/nltk | nltk/parse/featurechart.py | Python | FeatureChartParser | FeatureChartParser | 486 | 502 | 486 | 486 | dfd7d440c745142112e73d269dc297a63709688a | bigcode/the-stack | train |
1a3cd368a7aad168138c87ea | train | class | class FeatureTopDownInitRule(TopDownInitRule):
def apply(self, chart, grammar):
for prod in grammar.productions(lhs=grammar.start()):
new_edge = FeatureTreeEdge.from_production(prod, 0)
if chart.insert(new_edge, ()):
yield new_edge
| class FeatureTopDownInitRule(TopDownInitRule):
| def apply(self, chart, grammar):
for prod in grammar.productions(lhs=grammar.start()):
new_edge = FeatureTreeEdge.from_production(prod, 0)
if chart.insert(new_edge, ()):
yield new_edge
| .select(
start=left_edge.end(), is_complete=True, lhs=left_edge.nextsym()
):
yield from fr.apply(chart, grammar, left_edge, right_edge)
# ////////////////////////////////////////////////////////////
# Top-Down Prediction
# ////////////////////////////////////////////////////////////
cl... | 63 | 64 | 63 | 12 | 51 | Pandinosaurus/nltk | nltk/parse/featurechart.py | Python | FeatureTopDownInitRule | FeatureTopDownInitRule | 339 | 344 | 339 | 339 | 0423526df2f98113d8b356db75359520350daa7f | bigcode/the-stack | train |
c56d8e70c2b522cda3c98847 | train | function | def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_table('tasks')
| def downgrade():
### commands auto generated by Alembic - please adjust! ###
| op.drop_table('tasks')
| sa.Column('created_at', sa.DateTime(), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
| 63 | 64 | 24 | 17 | 46 | neoinal/ToDoManager | alembic/versions/809bd8fbc9_create_task_model.py | Python | downgrade | downgrade | 31 | 33 | 31 | 32 | 62126203bdb9e042c4a8acb51d0e000e997d0059 | bigcode/the-stack | train |
047b35e7713700bf0e65e160 | train | function | def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.create_table('tasks',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('summary', sa.Text(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullabl... | def upgrade():
### commands auto generated by Alembic - please adjust! ###
| op.create_table('tasks',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('summary', sa.Text(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
| # revision identifiers, used by Alembic.
revision = '809bd8fbc9'
down_revision = None
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
| 64 | 64 | 86 | 17 | 46 | neoinal/ToDoManager | alembic/versions/809bd8fbc9_create_task_model.py | Python | upgrade | upgrade | 19 | 27 | 19 | 20 | fea9402eb90a4ef62f6343f9c76445ab2365a5ad | bigcode/the-stack | train |
d195f07598c210e867c21aeb | train | class | class PrologError(Exception):
pass
| class PrologError(Exception):
| pass
| BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import sys
from pyswip.core import *
class PrologError(Exception):
| 64 | 64 | 9 | 6 | 58 | DylanLukes/pyswip | pyswip/prolog.py | Python | PrologError | PrologError | 31 | 32 | 31 | 31 | c198c21ed8051ac8c6f2a0d37489ea4805d2da29 | bigcode/the-stack | train |
d350397bac6229b54dec1d17 | train | class | class Prolog:
"""Easily query SWI-Prolog.
This is a singleton class
"""
# We keep track of open queries to avoid nested queries.
_queryIsOpen = False
class _QueryWrapper(object):
def __init__(self):
if Prolog._queryIsOpen:
raise NestedQueryError("The last q... | class Prolog:
| """Easily query SWI-Prolog.
This is a singleton class
"""
# We keep track of open queries to avoid nested queries.
_queryIsOpen = False
class _QueryWrapper(object):
def __init__(self):
if Prolog._queryIsOpen:
raise NestedQueryError("The last query was not c... | args.append("./")
args.append("-q") # --quiet
args.append("-nosignals") # "Inhibit any signal handling by Prolog"
if SWI_HOME_DIR is not None:
args.append("--home=%s" % SWI_HOME_DIR)
result = PL_initialise(len(args),args)
# result is a boolean variable (i.e. 0 or 1) indicating w... | 256 | 256 | 857 | 4 | 251 | DylanLukes/pyswip | pyswip/prolog.py | Python | Prolog | Prolog | 76 | 174 | 76 | 76 | 75c519c9396cc37cfb00ac62780aa3606a3aef32 | bigcode/the-stack | train |
b594364a93b7a86cafcb1b41 | train | function | def _initialize():
args = []
args.append("./")
args.append("-q") # --quiet
args.append("-nosignals") # "Inhibit any signal handling by Prolog"
if SWI_HOME_DIR is not None:
args.append("--home=%s" % SWI_HOME_DIR)
result = PL_initialise(len(args),args)
# result is a boolean va... | def _initialize():
| args = []
args.append("./")
args.append("-q") # --quiet
args.append("-nosignals") # "Inhibit any signal handling by Prolog"
if SWI_HOME_DIR is not None:
args.append("--home=%s" % SWI_HOME_DIR)
result = PL_initialise(len(args),args)
# result is a boolean variable (i.e. 0 or 1... | NestedQueryError(PrologError):
"""
SWI-Prolog does not accept nested queries, that is, opening a query while
the previous one was not closed.
As this error may be somewhat difficult to debug in foreign code, it is
automatically treated inside pySWIP
"""
pass
def _initialize():
| 70 | 70 | 236 | 4 | 65 | DylanLukes/pyswip | pyswip/prolog.py | Python | _initialize | _initialize | 46 | 68 | 46 | 46 | 7792bd574b93bca9f9b44d0372c062a0188f9cbd | bigcode/the-stack | train |
57f9c1620c56ef68d6a118cc | train | class | class NestedQueryError(PrologError):
"""
SWI-Prolog does not accept nested queries, that is, opening a query while
the previous one was not closed.
As this error may be somewhat difficult to debug in foreign code, it is
automatically treated inside pySWIP
"""
pass
| class NestedQueryError(PrologError):
| """
SWI-Prolog does not accept nested queries, that is, opening a query while
the previous one was not closed.
As this error may be somewhat difficult to debug in foreign code, it is
automatically treated inside pySWIP
"""
pass
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import sys
from pyswip.core import *
class PrologError(Exception):
pass
class NestedQueryError(PrologError):
| 64 | 64 | 67 | 8 | 55 | DylanLukes/pyswip | pyswip/prolog.py | Python | NestedQueryError | NestedQueryError | 35 | 43 | 35 | 35 | 61fe3e620939a38562a6689a3a3486ab59f7b2c1 | bigcode/the-stack | train |
521f67f3cf0bb506dc0e73e3 | train | function | def get_classes(classes_path):
'''loads the classes'''
with open(classes_path) as f:
class_names = f.readlines()
class_names = [c.strip() for c in class_names]
return class_names
| def get_classes(classes_path):
| '''loads the classes'''
with open(classes_path) as f:
class_names = f.readlines()
class_names = [c.strip() for c in class_names]
return class_names
| ,
initial_epoch= 0,
callbacks=[logging, checkpoint, reduce_lr, early_stopping, TensorBoardColabCallback(tbc)])
model.save_weights(log_dir + 'trained_weights_final.h5')
model.save('trained.model')
# Further training if needed.
def get_classes(classes_path):
| 64 | 64 | 47 | 6 | 58 | dangxuanvuong98/pineapples_harvester | train.py | Python | get_classes | get_classes | 96 | 101 | 96 | 96 | 21565916b01daa246d0c459df2548c78aea62eb1 | bigcode/the-stack | train |
15e755a2a318754ff846e85c | train | function | def create_tiny_model(input_shape, anchors, num_classes, load_pretrained=True, freeze_body=2,
weights_path='model_data/tiny_yolo_weights.h5'):
'''create the training model, for Tiny YOLOv3'''
K.clear_session() # get a new session
image_input = Input(shape=(None, None, 3))
h, w = input_shape
... | def create_tiny_model(input_shape, anchors, num_classes, load_pretrained=True, freeze_body=2,
weights_path='model_data/tiny_yolo_weights.h5'):
| '''create the training model, for Tiny YOLOv3'''
K.clear_session() # get a new session
image_input = Input(shape=(None, None, 3))
h, w = input_shape
num_anchors = len(anchors)
y_true = [Input(shape=(h//{0:32, 1:16}[l], w//{0:32, 1:16}[l], \
num_anchors//2, num_classes+5)) for l in range... | _body.layers)))
model_loss = Lambda(yolo_loss, output_shape=(1,), name='yolo_loss',
arguments={'anchors': anchors, 'num_classes': num_classes, 'ignore_thresh': 0.5})(
[*model_body.output, *y_true])
model = Model([model_body.input, *y_true], model_loss)
return model
def create_tiny_model(in... | 115 | 115 | 385 | 37 | 77 | dangxuanvuong98/pineapples_harvester | train.py | Python | create_tiny_model | create_tiny_model | 141 | 169 | 141 | 142 | 58932dae1f1572ecd3951f29e5bee880be004e33 | bigcode/the-stack | train |
e12870eb974b947ffc608a31 | train | function | def get_anchors(anchors_path):
'''loads the anchors from a file'''
with open(anchors_path) as f:
anchors = f.readline()
anchors = [float(x) for x in anchors.split(',')]
return np.array(anchors).reshape(-1, 2)
| def get_anchors(anchors_path):
| '''loads the anchors from a file'''
with open(anchors_path) as f:
anchors = f.readline()
anchors = [float(x) for x in anchors.split(',')]
return np.array(anchors).reshape(-1, 2)
| .model')
# Further training if needed.
def get_classes(classes_path):
'''loads the classes'''
with open(classes_path) as f:
class_names = f.readlines()
class_names = [c.strip() for c in class_names]
return class_names
def get_anchors(anchors_path):
| 64 | 64 | 61 | 8 | 55 | dangxuanvuong98/pineapples_harvester | train.py | Python | get_anchors | get_anchors | 103 | 108 | 103 | 103 | 5da54a0f776bc7cd00fc7f8210221f72f52dc90d | bigcode/the-stack | train |
9e98d26476e08178ecbb8c5f | train | function | def data_generator(annotation_lines, batch_size, input_shape, anchors, num_classes):
'''data generator for fit_generator'''
n = len(annotation_lines)
i = 0
while True:
image_data = []
box_data = []
for b in range(batch_size):
if i==0:
np.random.shuffle... | def data_generator(annotation_lines, batch_size, input_shape, anchors, num_classes):
| '''data generator for fit_generator'''
n = len(annotation_lines)
i = 0
while True:
image_data = []
box_data = []
for b in range(batch_size):
if i==0:
np.random.shuffle(annotation_lines)
image, box = get_random_data(annotation_lines[i], inpu... | num_classes': num_classes, 'ignore_thresh': 0.7})(
[*model_body.output, *y_true])
model = Model([model_body.input, *y_true], model_loss)
return model
def data_generator(annotation_lines, batch_size, input_shape, anchors, num_classes):
| 64 | 64 | 165 | 17 | 46 | dangxuanvuong98/pineapples_harvester | train.py | Python | data_generator | data_generator | 171 | 188 | 171 | 171 | 882ced0ecfb5783b23691593d2135c0c13872b47 | bigcode/the-stack | train |
146a72cb60bd088a0357ee9b | train | function | def _main():
annotation_path = 'train.txt'
log_dir = 'logs/003/'
classes_path = 'model_data/pineapple_classes.txt'
anchors_path = 'model_data/yolo_anchors.txt'
class_names = get_classes(classes_path)
num_classes = len(class_names)
anchors = get_anchors(anchors_path)
input_shape = (4... | def _main():
| annotation_path = 'train.txt'
log_dir = 'logs/003/'
classes_path = 'model_data/pineapple_classes.txt'
anchors_path = 'model_data/yolo_anchors.txt'
class_names = get_classes(classes_path)
num_classes = len(class_names)
anchors = get_anchors(anchors_path)
input_shape = (416,416) # mul... |
"""
Retrain the YOLO model for your own dataset.
"""
import numpy as np
import keras.backend as K
from keras.layers import Input, Lambda
from keras.models import Model
from keras.optimizers import Adam
from keras.callbacks import TensorBoard, ModelCheckpoint, ReduceLROnPlateau, EarlyStopping
from PIL import ImageFile... | 116 | 256 | 898 | 4 | 112 | dangxuanvuong98/pineapples_harvester | train.py | Python | _main | _main | 18 | 92 | 18 | 18 | 5e63b97e2dc2923fcc5d952c70c7d631972c7548 | bigcode/the-stack | train |
fe091e74700deca7b86b550c | train | function | def create_model(input_shape, anchors, num_classes, load_pretrained=True, freeze_body=2,
weights_path='model_data/yolo_weights.h5'):
'''create the training model'''
K.clear_session() # get a new session
image_input = Input(shape=(None, None, 3))
h, w = input_shape
num_anchors = len(ancho... | def create_model(input_shape, anchors, num_classes, load_pretrained=True, freeze_body=2,
weights_path='model_data/yolo_weights.h5'):
| '''create the training model'''
K.clear_session() # get a new session
image_input = Input(shape=(None, None, 3))
h, w = input_shape
num_anchors = len(anchors)
y_true = [Input(shape=(h//{0:32, 1:16, 2:8}[l], w//{0:32, 1:16, 2:8}[l], \
num_anchors//3, num_classes+5)) for l in range(3)]
... | ()
class_names = [c.strip() for c in class_names]
return class_names
def get_anchors(anchors_path):
'''loads the anchors from a file'''
with open(anchors_path) as f:
anchors = f.readline()
anchors = [float(x) for x in anchors.split(',')]
return np.array(anchors).reshape(-1, 2)
def creat... | 114 | 114 | 382 | 33 | 81 | dangxuanvuong98/pineapples_harvester | train.py | Python | create_model | create_model | 111 | 139 | 111 | 112 | c35ecf181225c70fbe425d2f78ee276d74223a73 | bigcode/the-stack | train |
15bf2e0f248ac2f428b983b8 | train | function | def data_generator_wrapper(annotation_lines, batch_size, input_shape, anchors, num_classes):
n = len(annotation_lines)
if n==0 or batch_size<=0: return None
return data_generator(annotation_lines, batch_size, input_shape, anchors, num_classes)
| def data_generator_wrapper(annotation_lines, batch_size, input_shape, anchors, num_classes):
| n = len(annotation_lines)
if n==0 or batch_size<=0: return None
return data_generator(annotation_lines, batch_size, input_shape, anchors, num_classes)
| .array(image_data)
box_data = np.array(box_data)
y_true = preprocess_true_boxes(box_data, input_shape, anchors, num_classes)
yield [image_data, *y_true], np.zeros(batch_size)
def data_generator_wrapper(annotation_lines, batch_size, input_shape, anchors, num_classes):
| 64 | 64 | 57 | 18 | 46 | dangxuanvuong98/pineapples_harvester | train.py | Python | data_generator_wrapper | data_generator_wrapper | 190 | 193 | 190 | 190 | 311fefbb16949ac126a6b07a5eef43b91f75ce78 | bigcode/the-stack | train |
2a5b901b43a9da2052eb4b4e | train | class | class CmdRemoteAdd(CmdRemote):
def run(self):
if self.args.default:
logger.info(f"Setting '{self.args.name}' as a default remote.")
with self.config.edit(self.args.level) as conf:
if self.args.name in conf["remote"] and not self.args.force:
raise ConfigError(... | class CmdRemoteAdd(CmdRemote):
| def run(self):
if self.args.default:
logger.info(f"Setting '{self.args.name}' as a default remote.")
with self.config.edit(self.args.level) as conf:
if self.args.name in conf["remote"] and not self.args.force:
raise ConfigError(
"remote '{... | if getattr(self.args, "name", None):
self.args.name = self.args.name.lower()
def _check_exists(self, conf):
if self.args.name not in conf["remote"]:
raise ConfigError(f"remote '{self.args.name}' doesn't exist.")
class CmdRemoteAdd(CmdRemote):
| 63 | 64 | 137 | 8 | 55 | indhupriya/dvc | dvc/command/remote.py | Python | CmdRemoteAdd | CmdRemoteAdd | 24 | 40 | 24 | 24 | f2f0a347c0941062af46ae78ba91a49081186db0 | bigcode/the-stack | train |
168eb3d72efea3aa116bb5d5 | train | function | def add_parser(subparsers, parent_parser):
from dvc.command.config import parent_config_parser
REMOTE_HELP = "Set up and manage data remotes."
remote_parser = subparsers.add_parser(
"remote",
parents=[parent_parser],
description=append_doc_link(REMOTE_HELP, "remote"),
help=R... | def add_parser(subparsers, parent_parser):
| from dvc.command.config import parent_config_parser
REMOTE_HELP = "Set up and manage data remotes."
remote_parser = subparsers.add_parser(
"remote",
parents=[parent_parser],
description=append_doc_link(REMOTE_HELP, "remote"),
help=REMOTE_HELP,
formatter_class=argpars... | ):
conf = self.config.load_one(self.args.level)
for name, conf in conf["remote"].items():
logger.info("{}\t{}".format(name, conf["url"]))
return 0
class CmdRemoteRename(CmdRemote):
def _rename_default(self, conf):
if conf["core"].get("remote") == self.args.name:
... | 256 | 256 | 1,008 | 10 | 245 | indhupriya/dvc | dvc/command/remote.py | Python | add_parser | add_parser | 145 | 271 | 145 | 145 | 5902b5b17f4bdcb67a5afd8f60f871f44d5b60ef | bigcode/the-stack | train |
fa09d9835d80c48593328989 | train | class | class CmdRemoteDefault(CmdRemote):
def run(self):
if self.args.name is None and not self.args.unset:
conf = self.config.load_one(self.args.level)
try:
print(conf["core"]["remote"])
except KeyError:
logger.info("No default remote set")
... | class CmdRemoteDefault(CmdRemote):
| def run(self):
if self.args.name is None and not self.args.unset:
conf = self.config.load_one(self.args.level)
try:
print(conf["core"]["remote"])
except KeyError:
logger.info("No default remote set")
return 1
else:
... | conf["remote"][self.args.name] = {}
section = conf["remote"][self.args.name]
if self.args.unset:
section.pop(self.args.option, None)
else:
section[self.args.option] = self.args.value
return 0
class CmdRemoteDefault(CmdRemote):
| 64 | 64 | 185 | 8 | 55 | indhupriya/dvc | dvc/command/remote.py | Python | CmdRemoteDefault | CmdRemoteDefault | 78 | 105 | 78 | 78 | 6f6d3bb761c59783b6a9d60bddc386003f10ea4e | bigcode/the-stack | train |
612978c5a8c49ab78e5651a6 | train | class | class CmdRemoteRename(CmdRemote):
def _rename_default(self, conf):
if conf["core"].get("remote") == self.args.name:
conf["core"]["remote"] = self.args.new
def run(self):
all_config = self.config.load_config_to_level(None)
if self.args.new in all_config.get("remote", {}):
... | class CmdRemoteRename(CmdRemote):
| def _rename_default(self, conf):
if conf["core"].get("remote") == self.args.name:
conf["core"]["remote"] = self.args.new
def run(self):
all_config = self.config.load_config_to_level(None)
if self.args.new in all_config.get("remote", {}):
raise ConfigError(
... |
class CmdRemoteList(CmdRemote):
def run(self):
conf = self.config.load_one(self.args.level)
for name, conf in conf["remote"].items():
logger.info("{}\t{}".format(name, conf["url"]))
return 0
class CmdRemoteRename(CmdRemote):
| 64 | 64 | 203 | 8 | 55 | indhupriya/dvc | dvc/command/remote.py | Python | CmdRemoteRename | CmdRemoteRename | 116 | 142 | 116 | 116 | 82d8c5f8e3c28042354dfa6c97f386e512c56a20 | bigcode/the-stack | train |
4ccb9959f94c9402097ace41 | train | class | class CmdRemote(CmdConfig):
def __init__(self, args):
super().__init__(args)
if getattr(self.args, "name", None):
self.args.name = self.args.name.lower()
def _check_exists(self, conf):
if self.args.name not in conf["remote"]:
raise ConfigError(f"remote '{self.ar... | class CmdRemote(CmdConfig):
| def __init__(self, args):
super().__init__(args)
if getattr(self.args, "name", None):
self.args.name = self.args.name.lower()
def _check_exists(self, conf):
if self.args.name not in conf["remote"]:
raise ConfigError(f"remote '{self.args.name}' doesn't exist.")
| import argparse
import logging
from dvc.command.base import append_doc_link, fix_subparsers
from dvc.command.config import CmdConfig
from dvc.config import ConfigError, merge
from dvc.utils import format_link
logger = logging.getLogger(__name__)
class CmdRemote(CmdConfig):
| 63 | 64 | 79 | 7 | 56 | indhupriya/dvc | dvc/command/remote.py | Python | CmdRemote | CmdRemote | 12 | 21 | 12 | 12 | de6075106df46d6208b2470b47def1e536bc069b | bigcode/the-stack | train |
7ada156369be5905a2bef87f | train | class | class CmdRemoteRemove(CmdRemote):
def run(self):
with self.config.edit(self.args.level) as conf:
self._check_exists(conf)
del conf["remote"][self.args.name]
# Remove core.remote refs to this remote in any shadowing configs
for level in reversed(self.config.LEVELS):
... | class CmdRemoteRemove(CmdRemote):
| def run(self):
with self.config.edit(self.args.level) as conf:
self._check_exists(conf)
del conf["remote"][self.args.name]
# Remove core.remote refs to this remote in any shadowing configs
for level in reversed(self.config.LEVELS):
with self.config.edit(l... | force` to "
"overwrite it.".format(self.args.name)
)
conf["remote"][self.args.name] = {"url": self.args.url}
if self.args.default:
conf["core"]["remote"] = self.args.name
return 0
class CmdRemoteRemove(CmdRemote):
| 64 | 64 | 117 | 8 | 55 | indhupriya/dvc | dvc/command/remote.py | Python | CmdRemoteRemove | CmdRemoteRemove | 43 | 58 | 43 | 43 | 0be5cd1725138b2818e076dd599019f5e0e371e7 | bigcode/the-stack | train |
f34a329a1a2af8533ad81811 | train | class | class CmdRemoteModify(CmdRemote):
def run(self):
with self.config.edit(self.args.level) as conf:
merged = self.config.load_config_to_level(self.args.level)
merge(merged, conf)
self._check_exists(merged)
if self.args.name not in conf["remote"]:
... | class CmdRemoteModify(CmdRemote):
| def run(self):
with self.config.edit(self.args.level) as conf:
merged = self.config.load_config_to_level(self.args.level)
merge(merged, conf)
self._check_exists(merged)
if self.args.name not in conf["remote"]:
conf["remote"][self.args.name] = ... | reversed(self.config.LEVELS):
with self.config.edit(level) as conf:
if conf["core"].get("remote") == self.args.name:
del conf["core"]["remote"]
if level == self.args.level:
break
return 0
class CmdRemoteModify(CmdRemote):
| 64 | 64 | 121 | 8 | 55 | indhupriya/dvc | dvc/command/remote.py | Python | CmdRemoteModify | CmdRemoteModify | 61 | 75 | 61 | 61 | cee899f4d53d81e9e0b997eb4d5a8edec07a10bb | bigcode/the-stack | train |
be36e77348be198d58078e51 | train | class | class CmdRemoteList(CmdRemote):
def run(self):
conf = self.config.load_one(self.args.level)
for name, conf in conf["remote"].items():
logger.info("{}\t{}".format(name, conf["url"]))
return 0
| class CmdRemoteList(CmdRemote):
| def run(self):
conf = self.config.load_one(self.args.level)
for name, conf in conf["remote"].items():
logger.info("{}\t{}".format(name, conf["url"]))
return 0
| in conf["remote"]
or self.args.name in merged_conf["remote"]
):
conf["core"]["remote"] = self.args.name
else:
raise ConfigError(
"default remote must be present in remote list."
... | 64 | 64 | 55 | 8 | 55 | indhupriya/dvc | dvc/command/remote.py | Python | CmdRemoteList | CmdRemoteList | 108 | 113 | 108 | 108 | 3b253eed99ef173f7c1cfd214f199b7d74dddddc | bigcode/the-stack | train |
aed960fbb87a39e098ce563e | train | class | class TokensV3TestJSON(base.BaseIdentityV3AdminTest):
@decorators.idempotent_id('0f9f5a5f-d5cd-4a86-8a5b-c5ded151f212')
def test_tokens(self):
# Valid user's token is authenticated
# Create a User
u_name = data_utils.rand_name('user')
u_desc = '%s-description' % u_name
u... | class TokensV3TestJSON(base.BaseIdentityV3AdminTest):
@decorators.idempotent_id('0f9f5a5f-d5cd-4a86-8a5b-c5ded151f212')
| def test_tokens(self):
# Valid user's token is authenticated
# Create a User
u_name = data_utils.rand_name('user')
u_desc = '%s-description' % u_name
u_password = data_utils.rand_password()
user = self.create_test_user(
name=u_name, description=u_desc, pas... | # Copyright 2012 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | 241 | 256 | 1,424 | 50 | 190 | azorge/tempest | tempest/api/identity/admin/v3/test_tokens.py | Python | TokensV3TestJSON | TokensV3TestJSON | 27 | 178 | 27 | 29 | 5c2b7e4e3d6e183a2ea56f7e80dd7059f5157076 | bigcode/the-stack | train |
f9ff00920fb94fc68e21d303 | train | function | def _b_to_a(ind, grp, N, aindices, bindices, aoverlap, boverlap, agroup, bgroup):
'''
Iterative function, equivalent to ``_a_to_b``, to assign all sources
overlapping this catalogue "b" object in catalogue "a" with its group number.
Parameters
----------
ind : integer
The index into ``b... | def _b_to_a(ind, grp, N, aindices, bindices, aoverlap, boverlap, agroup, bgroup):
| '''
Iterative function, equivalent to ``_a_to_b``, to assign all sources
overlapping this catalogue "b" object in catalogue "a" with its group number.
Parameters
----------
ind : integer
The index into ``bgroup``, the specific source in question to be assigned
this group number.... | .ndarray
Array detailing the group number of each catalogue "b" source.
'''
agroup[ind] = grp
for q in aindices[:N, ind]:
if bgroup[q] != grp:
_b_to_a(q, grp, boverlap[q], aindices, bindices, aoverlap, boverlap, agroup, bgroup)
return
def _b_to_a(ind, grp, N, aindices, bindic... | 114 | 114 | 382 | 31 | 82 | lsst-uk/macauff | macauff/make_set_list.py | Python | _b_to_a | _b_to_a | 305 | 339 | 305 | 305 | d17e53aa0005b24c606a43bd683c07d7d056bca1 | bigcode/the-stack | train |
e897d1eba319ef23f24a0b6a | train | function | def _a_to_b(ind, grp, N, aindices, bindices, aoverlap, boverlap, agroup, bgroup):
'''
Iterative function, along with ``_b_to_a``, to assign all sources overlapping
this catalogue "a" object in catalogue "b" as being in the same group as it.
This subsequently calls ``_b_to_a`` for each of those "b" sour... | def _a_to_b(ind, grp, N, aindices, bindices, aoverlap, boverlap, agroup, bgroup):
| '''
Iterative function, along with ``_b_to_a``, to assign all sources overlapping
this catalogue "a" object in catalogue "b" as being in the same group as it.
This subsequently calls ``_b_to_a`` for each of those "b" sources, to
assign any "a" sources that overlap those objects to the same group, u... | verlap[i] == 0:
group_num += 1
bgroup[i] = group_num
for i in range(0, len(agroup)):
if agroup[i] == 0:
group_num += 1
_a_to_b(i, group_num, aoverlap[i], aindices, bindices,
aoverlap, boverlap, agroup, bgroup)
return agroup, bgroup
de... | 129 | 129 | 432 | 31 | 97 | lsst-uk/macauff | macauff/make_set_list.py | Python | _a_to_b | _a_to_b | 264 | 302 | 264 | 264 | 2756302776720d76814ba623ce34a73074d2e878 | bigcode/the-stack | train |
5835b78ca717c8927a6cec91 | train | function | def set_list(aindices, bindices, aoverlap, boverlap, joint_folder_path, n_pool):
'''
Creates the inter-catalogue groupings between catalogues "a" and "b", based
on previously determined individual source "overlaps" in astrometry.
Parameters
----------
aindices : numpy.ndarray
The indice... | def set_list(aindices, bindices, aoverlap, boverlap, joint_folder_path, n_pool):
| '''
Creates the inter-catalogue groupings between catalogues "a" and "b", based
on previously determined individual source "overlaps" in astrometry.
Parameters
----------
aindices : numpy.ndarray
The indices into catalogue "b", for each catalogue "a" source, that have
been deter... | # Licensed under a 3-clause BSD style license - see LICENSE
'''
This module hosts the functions to create overlapping groups of "islands" of
objects, astrometrically in common based on relative sky separation compared to
their respective uncertainties across two catalogues.
'''
import sys
import os
import warnings
imp... | 113 | 256 | 2,573 | 24 | 89 | lsst-uk/macauff | macauff/make_set_list.py | Python | set_list | set_list | 19 | 192 | 19 | 19 | 06e071e68367d27093bb7c12cd733a5976143cc9 | bigcode/the-stack | train |
abc4312c3895300cf3d9ebf4 | train | function | def _calc_group_length_exceeded(iterable):
i, n_a, n_b, maxiters = iterable
counter = 0
for k in np.arange(0, min(n_a, n_b)+1e-10, 1):
kcomb = (np.prod([qq for qq in np.arange(n_a-k+1, n_a+1e-10, 1)]) /
scipy.special.factorial(k))
kperm = np.prod([qq for qq in np.arange(n_b-... | def _calc_group_length_exceeded(iterable):
| i, n_a, n_b, maxiters = iterable
counter = 0
for k in np.arange(0, min(n_a, n_b)+1e-10, 1):
kcomb = (np.prod([qq for qq in np.arange(n_a-k+1, n_a+1e-10, 1)]) /
scipy.special.factorial(k))
kperm = np.prod([qq for qq in np.arange(n_b-k+1, n_b+1e-10, 1)])
counter += kco... | in bindices[:N, ind]:
if agroup[f] != grp:
_a_to_b(f, grp, aoverlap[f], aindices, bindices, aoverlap, boverlap, agroup, bgroup)
return
def _calc_group_length_exceeded(iterable):
| 64 | 64 | 166 | 10 | 53 | lsst-uk/macauff | macauff/make_set_list.py | Python | _calc_group_length_exceeded | _calc_group_length_exceeded | 342 | 354 | 342 | 342 | a66707d0cb7e7bcca195dab6d88ba34a25e00486 | bigcode/the-stack | train |
42c0df4493a12e41f6e05eda | train | function | def _initial_group_numbering(aindices, bindices, aoverlap, boverlap, joint_folder_path):
'''
Iterates over the indices mapping overlaps between the two catalogues,
assigning initial group numbers to sources to be placed in "islands".
Loops through all "lonely", single-source islands in each catalogue, ... | def _initial_group_numbering(aindices, bindices, aoverlap, boverlap, joint_folder_path):
| '''
Iterates over the indices mapping overlaps between the two catalogues,
assigning initial group numbers to sources to be placed in "islands".
Loops through all "lonely", single-source islands in each catalogue, and
those with a one-to-one mapping of a single "a" object and one "b" source,
be... | idy up temporary memmap arrays.
for name in ['agroup', 'bgroup', 'grplenexceed', 'goodlen', 'acount', 'bcount']:
os.remove('{}/group/{}.npy'.format(joint_folder_path, name))
alist = np.load('{}/group/alist.npy'.format(joint_folder_path), mmap_mode='r+')
blist = np.load('{}/group/blist.npy'.format(j... | 208 | 208 | 695 | 24 | 183 | lsst-uk/macauff | macauff/make_set_list.py | Python | _initial_group_numbering | _initial_group_numbering | 195 | 261 | 195 | 195 | a50ec3422a5dac31e88472d8d883a7fd657b695d | bigcode/the-stack | train |
d511f16dd668898590141153 | train | class | class ReconcileEngine(object):
"""
Main class of the reconciliation system
"""
def __init__(self, redis_client):
self.item_store = ItemStore(redis_client)
self.type_matcher = TypeMatcher(redis_client)
self.pf = PropertyFactory(self.item_store)
self.sitelink_fetcher = self... | class ReconcileEngine(object):
| """
Main class of the reconciliation system
"""
def __init__(self, redis_client):
self.item_store = ItemStore(redis_client)
self.type_matcher = TypeMatcher(redis_client)
self.pf = PropertyFactory(self.item_store)
self.sitelink_fetcher = self.item_store.sitelink_fetcher
... | from config import *
import requests
import itertools
import re
import json
from collections import defaultdict
from .itemstore import ItemStore
from .typematcher import TypeMatcher
from .utils import to_q
from .language import language_fallback
from .propertypath import PropertyFactory
from .wikidatavalue import Item... | 88 | 256 | 3,486 | 6 | 81 | framawiki/openrefine-wikidata | wdreconcile/engine.py | Python | ReconcileEngine | ReconcileEngine | 16 | 454 | 16 | 16 | 2acbcc1282d2dacb16049cb862967426d6e9ed4a | bigcode/the-stack | train |
a70ff3951e0f132ff36ce5aa | train | function | def main():
with open("config/config.json") as f:
config = json.load(f)
model = "msaenet"
param_space = {f"{model}__module__lambda_1": [0.01, 0.001, 0.0001]}
for cancer in config["cancers"]:
print(f"Starting: {cancer}")
data = pd.read_csv(
f"./data/processed/{cancer}/... | def main():
| with open("config/config.json") as f:
config = json.load(f)
model = "msaenet"
param_space = {f"{model}__module__lambda_1": [0.01, 0.001, 0.0001]}
for cancer in config["cancers"]:
print(f"Starting: {cancer}")
data = pd.read_csv(
f"./data/processed/{cancer}/merged/{conf... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import os
import sys
module_path = os.path.abspath(os.path.join("./src/"))
if module_path not in sys.path:
sys.path.append(module_path)
from timeit import default_timer as timer
import numpy as np
import pandas as pd
import torch
from model.autoencoder... | 136 | 256 | 926 | 3 | 132 | dnwissel/msc_thesis | src/jobs/run_msae_residual.py | Python | main | main | 26 | 137 | 26 | 26 | 2e5bcc6e5b53653aab656317c0c699272733a46b | bigcode/the-stack | train |
ae5cc6b8514ddf2946b46958 | train | function | def test_is_simple_permutation():
"""Test if matrix is a simple permutation matrix."""
mat = np.array([[1, 0, 0], [0, 0, 1], [0, 1, 0]])
np.testing.assert_equal(is_permutation(mat), True)
| def test_is_simple_permutation():
| """Test if matrix is a simple permutation matrix."""
mat = np.array([[1, 0, 0], [0, 0, 1], [0, 1, 0]])
np.testing.assert_equal(is_permutation(mat), True)
| """Test is_permutation."""
import numpy as np
from toqito.matrix_props import is_permutation
def test_is_simple_permutation():
| 30 | 64 | 64 | 7 | 22 | vanzilar/toqito | tests/test_matrix_props/test_is_permutation.py | Python | test_is_simple_permutation | test_is_simple_permutation | 7 | 10 | 7 | 7 | 7cead11ead0e63609043f2be70b89b15ab6df8d2 | bigcode/the-stack | train |
2f9f4c91c37a3bc89d626d9b | train | function | def test_is_not_square_matrix():
"""Test non-square matrix and thus will fail."""
mat = np.array([[1, 0, 0 ], [1, 0, 0], [0, 1, 0], [0, 0, 1]])
np.testing.assert_equal(is_permutation(mat), False)
| def test_is_not_square_matrix():
| """Test non-square matrix and thus will fail."""
mat = np.array([[1, 0, 0 ], [1, 0, 0], [0, 1, 0], [0, 0, 1]])
np.testing.assert_equal(is_permutation(mat), False)
| """Test if matrix is a simple permutation matrix."""
mat = np.array([[1, 0, 0], [0, 0, 1], [0, 1, 0]])
np.testing.assert_equal(is_permutation(mat), True)
def test_is_not_square_matrix():
| 64 | 64 | 73 | 7 | 57 | vanzilar/toqito | tests/test_matrix_props/test_is_permutation.py | Python | test_is_not_square_matrix | test_is_not_square_matrix | 13 | 16 | 13 | 13 | b1b23627301ef2e7f927d58a5c10b280d2068504 | bigcode/the-stack | train |
348ed1c0ea35ff0346b065e3 | train | function | def test_is_matrix_with_nonunitary_column_sum():
"""Test a non-permutation matrix where the unitary column sum check will fail."""
mat = np.array([[0, 0, 1,0], [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0]])
np.testing.assert_equal(is_permutation(mat), False)
| def test_is_matrix_with_nonunitary_column_sum():
| """Test a non-permutation matrix where the unitary column sum check will fail."""
mat = np.array([[0, 0, 1,0], [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0]])
np.testing.assert_equal(is_permutation(mat), False)
| 1,0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]])
np.testing.assert_equal(is_permutation(mat), False)
def test_is_matrix_with_nonunitary_column_sum():
| 64 | 64 | 95 | 11 | 53 | vanzilar/toqito | tests/test_matrix_props/test_is_permutation.py | Python | test_is_matrix_with_nonunitary_column_sum | test_is_matrix_with_nonunitary_column_sum | 31 | 34 | 31 | 31 | 8f02157e556da28280f15780fef2207d79be67c1 | bigcode/the-stack | train |
8ffc03480baa12891ca15c21 | train | function | def test_is_not_binary_value_matrix():
"""Test a non-permutation matrix with one element being 9 which is not in set (0,1)."""
mat = np.array([[0, 0, 0, 9], [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0]])
np.testing.assert_equal(is_permutation(mat), False)
| def test_is_not_binary_value_matrix():
| """Test a non-permutation matrix with one element being 9 which is not in set (0,1)."""
mat = np.array([[0, 0, 0, 9], [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0]])
np.testing.assert_equal(is_permutation(mat), False)
| ."""
mat = np.array([[1, 0, 0 ], [1, 0, 0], [0, 1, 0], [0, 0, 1]])
np.testing.assert_equal(is_permutation(mat), False)
def test_is_not_binary_value_matrix():
| 64 | 64 | 99 | 8 | 56 | vanzilar/toqito | tests/test_matrix_props/test_is_permutation.py | Python | test_is_not_binary_value_matrix | test_is_not_binary_value_matrix | 19 | 22 | 19 | 19 | 22fdb324c1db9b32139dd0879dcfede4f33c2fdb | bigcode/the-stack | train |
049b1e0845ef9ee3e80a9701 | train | function | def test_is_matrix_with_negative_values_and_unitary_sums():
"""Test a non-permutation matrix with some negative values that passes the unitary sum check."""
mat = np.array([[2, -1], [-1, 2]])
np.testing.assert_equal(is_permutation(mat), False)
| def test_is_matrix_with_negative_values_and_unitary_sums():
| """Test a non-permutation matrix with some negative values that passes the unitary sum check."""
mat = np.array([[2, -1], [-1, 2]])
np.testing.assert_equal(is_permutation(mat), False)
| matrix with fractional values that passes the unitary sum check."""
mat = np.array([[0.5, 0.5], [0.5, 0.5]])
np.testing.assert_equal(is_permutation(mat), False)
def test_is_matrix_with_negative_values_and_unitary_sums():
| 64 | 64 | 64 | 13 | 51 | vanzilar/toqito | tests/test_matrix_props/test_is_permutation.py | Python | test_is_matrix_with_negative_values_and_unitary_sums | test_is_matrix_with_negative_values_and_unitary_sums | 43 | 46 | 43 | 43 | 8ee11c10e0e64ad9992f6f3bd68b47985fa093fb | bigcode/the-stack | train |
6c63a2a8d884427656911c46 | train | function | def test_is_matrix_with_fractional_values_and_unitary_sums():
"""Test a non-permutation matrix with fractional values that passes the unitary sum check."""
mat = np.array([[0.5, 0.5], [0.5, 0.5]])
np.testing.assert_equal(is_permutation(mat), False)
| def test_is_matrix_with_fractional_values_and_unitary_sums():
| """Test a non-permutation matrix with fractional values that passes the unitary sum check."""
mat = np.array([[0.5, 0.5], [0.5, 0.5]])
np.testing.assert_equal(is_permutation(mat), False)
| ], [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0]])
np.testing.assert_equal(is_permutation(mat), False)
def test_is_matrix_with_fractional_values_and_unitary_sums():
| 64 | 64 | 72 | 14 | 50 | vanzilar/toqito | tests/test_matrix_props/test_is_permutation.py | Python | test_is_matrix_with_fractional_values_and_unitary_sums | test_is_matrix_with_fractional_values_and_unitary_sums | 37 | 40 | 37 | 37 | 8da5c8be8373bc9a9c7c12e9d87073c33d7f285c | bigcode/the-stack | train |
ecb4c1a1dbc3ff90484b371b | train | function | def test_is_matrix_with_nonunitary_row_sum():
"""Test a non-permutation matrix where the unitary row sum check will fail."""
mat = np.array([[0, 1, 1,0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]])
np.testing.assert_equal(is_permutation(mat), False)
| def test_is_matrix_with_nonunitary_row_sum():
| """Test a non-permutation matrix where the unitary row sum check will fail."""
mat = np.array([[0, 1, 1,0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]])
np.testing.assert_equal(is_permutation(mat), False)
| , 9], [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0]])
np.testing.assert_equal(is_permutation(mat), False)
def test_is_matrix_with_nonunitary_row_sum():
| 64 | 64 | 95 | 11 | 53 | vanzilar/toqito | tests/test_matrix_props/test_is_permutation.py | Python | test_is_matrix_with_nonunitary_row_sum | test_is_matrix_with_nonunitary_row_sum | 25 | 28 | 25 | 25 | eff46755bab6d6ac379b6d4df0b80b4704742d54 | bigcode/the-stack | train |
a8b80bc7ce1f03fce5c7bcde | train | class | class LanguageTester:
def __init__(self,
test_data: List,
encoder: LanguageEncoder,
optimizer: torch.optim.Optimizer,
num_epochs: int,
device: torch.device,
checkpoint_dir: str,
num_models_to_keep:... | class LanguageTester:
| def __init__(self,
test_data: List,
encoder: LanguageEncoder,
optimizer: torch.optim.Optimizer,
num_epochs: int,
device: torch.device,
checkpoint_dir: str,
num_models_to_keep: int,
... | import json
import argparse
from typing import List, Dict
import glob
import os
import torch
from spacy.tokenizer import Tokenizer
from spacy.lang.en import English
import logging
from tqdm import tqdm
from matplotlib import pyplot as plt
import numpy as np
from image_encoder import ImageEncoder, DeconvolutionalN... | 126 | 173 | 577 | 4 | 122 | esteng/guiding-multi-step | test_language_encoder.py | Python | LanguageTester | LanguageTester | 26 | 94 | 26 | 26 | e0e1afd694d8954ce91dee1d2c260890f6b27fdb | bigcode/the-stack | train |
f0a576da1aaffecc494c769b | train | class | class Migration(migrations.Migration):
dependencies = [
('flights', '0002_remove_passenger_bitrhday'),
]
operations = [
migrations.AlterField(
model_name='flight',
name='arrival',
field=models.CharField(default='2022-03-12 13:30', max_length=30),
... | class Migration(migrations.Migration):
| dependencies = [
('flights', '0002_remove_passenger_bitrhday'),
]
operations = [
migrations.AlterField(
model_name='flight',
name='arrival',
field=models.CharField(default='2022-03-12 13:30', max_length=30),
),
migrations.AlterField(
... | # Generated by Django 3.2.9 on 2022-03-09 09:41
from django.db import migrations, models
class Migration(migrations.Migration):
| 38 | 64 | 117 | 7 | 30 | Dreamshh/ITMO_ICT_WebDevelopment_2021-2022 | students/K33401/laboratory_works/Shtreikh_Anna/Lr_3/Lr3/flights/migrations/0003_auto_20220309_1241.py | Python | Migration | Migration | 6 | 23 | 6 | 7 | 53c4a5d984ab790bd96e3e9761e9dfcd10235e08 | bigcode/the-stack | train |
c6406db744f139735e7a8f1e | train | function | @app.route("/")
def homepage():
"""View function for Home Page."""
return render_template("home.html")
| @app.route("/")
def homepage():
| """View function for Home Page."""
return render_template("home.html")
| """Flask Application for Paws Rescue Center."""
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def homepage():
| 30 | 64 | 22 | 6 | 24 | cloudacademy-rnd/bill-digitization | src/flaskr/server.py | Python | homepage | homepage | 6 | 9 | 6 | 7 | 97a50e288afc66d601d4623813f4a131327622f1 | bigcode/the-stack | train |
d26a222410f89bb0caa9b03e | train | function | @app.route("/about")
def about():
"""View function for About Page."""
return render_template("about.html")
| @app.route("/about")
def about():
| """View function for About Page."""
return render_template("about.html")
| """Flask Application for Paws Rescue Center."""
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def homepage():
"""View function for Home Page."""
return render_template("home.html")
@app.route("/about")
def about():
| 54 | 64 | 24 | 8 | 46 | cloudacademy-rnd/bill-digitization | src/flaskr/server.py | Python | about | about | 12 | 15 | 12 | 13 | f788dfa65a89cf70b76796775b7b1856006dafb4 | bigcode/the-stack | train |
930f711a37ad0692430619ce | train | function | def snakecase(string: Text) -> Text:
"""Convert string into snake case.
Join punctuation with underscore
Inspired by: https://github.com/okunishinishi/python-stringcase
License: MIT
:param string: String to convert.
:returns: snake_case_string.
Examples
--------
>>> snakecase('... | def snakecase(string: Text) -> Text:
| """Convert string into snake case.
Join punctuation with underscore
Inspired by: https://github.com/okunishinishi/python-stringcase
License: MIT
:param string: String to convert.
:returns: snake_case_string.
Examples
--------
>>> snakecase('foo_bar_baz')
foo_bar_baz
>>>... | convert.
:returns: lower case string.
Examples
--------
>>> lowercase('foo_bar_baz')
Foo_bar_baz
>>> lowercase('FooBarBaz')
foobarbaz
"""
return str(string).lower()
def snakecase(string: Text) -> Text:
| 64 | 64 | 164 | 10 | 54 | KaczuH/pykechain | pykechain/utils.py | Python | snakecase | snakecase | 370 | 396 | 370 | 370 | f235f5857f5eb4c7af1d68f97ef21731a711a7a0 | bigcode/the-stack | train |
fa6c821c8d4889ff88bdc295 | train | function | def is_url(value: Text) -> bool:
"""
Return whether or not given value is a valid URL.
If the value is valid URL this function returns ``True``.
This validator implementation is taken and augmented from https://github.com/kvesteri/validators/
Copyright (c) 2013-2014 Konsta Vesterinen, It is Licenc... | def is_url(value: Text) -> bool:
| """
Return whether or not given value is a valid URL.
If the value is valid URL this function returns ``True``.
This validator implementation is taken and augmented from https://github.com/kvesteri/validators/
Copyright (c) 2013-2014 Konsta Vesterinen, It is Licenced with the MIT license.
Thi... | "
r"@(?:[a-zA-Z0-9\[\]](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z0-9\[\]]{2,6}\.?$"
)
def find(iterable: Iterable[T], predicate: Callable[[T], bool]) -> Optional[T]:
"""Return the first item in the iterable that matches the predicate function."""
for i in iterable:
if predicate(i):
... | 255 | 256 | 1,908 | 10 | 245 | KaczuH/pykechain | pykechain/utils.py | Python | is_url | is_url | 46 | 156 | 46 | 46 | 7025786594ddfb8a272de71b8e520a2f545e94bd | bigcode/the-stack | train |
2ad713e1216c0498f3e96135 | train | function | def lowercase(string: Text) -> Text:
"""Convert string into lower case.
Inspired by: https://github.com/okunishinishi/python-stringcase
License: MIT
:param string: String to convert.
:returns: lower case string.
Examples
--------
>>> lowercase('foo_bar_baz')
Foo_bar_baz
>>> lo... | def lowercase(string: Text) -> Text:
| """Convert string into lower case.
Inspired by: https://github.com/okunishinishi/python-stringcase
License: MIT
:param string: String to convert.
:returns: lower case string.
Examples
--------
>>> lowercase('foo_bar_baz')
Foo_bar_baz
>>> lowercase('FooBarBaz')
foobarbaz
... | foo_bar_baz')
Foo_bar_baz
>>> capitalcase('FooBarBaz')
FooBarBaz
"""
string = str(string)
if not string:
return string
return uppercase(string[0]) + string[1:]
def lowercase(string: Text) -> Text:
| 63 | 64 | 101 | 9 | 54 | KaczuH/pykechain | pykechain/utils.py | Python | lowercase | lowercase | 350 | 367 | 350 | 350 | bc2c51f8bf7696312e1404e4103c1847db470e0e | bigcode/the-stack | train |
814db075884bbcefffa8fd8b | train | function | def __dict_public__(cls: type(object)) -> Dict:
"""
Get the __dict__ of the class `cls`, excluding 'dunder' attributes and methods.
:param cls: class object
:return: dictionary with public attributes
Example
-------
>>> from pykechain.enums import Category
>>> sorted(__dict_public__(cl... | def __dict_public__(cls: type(object)) -> Dict:
| """
Get the __dict__ of the class `cls`, excluding 'dunder' attributes and methods.
:param cls: class object
:return: dictionary with public attributes
Example
-------
>>> from pykechain.enums import Category
>>> sorted(__dict_public__(cls=Category).values())
['INSTANCE', 'MODEL']
... | FKD", value).encode("ascii", "ignore").decode("ascii")
)
value = re.sub(r"[^\w\s-]", "", value).strip().lower()
return re.sub(r"[-\s]+", "-", value)
def __dict_public__(cls: type(object)) -> Dict:
| 64 | 64 | 115 | 13 | 51 | KaczuH/pykechain | pykechain/utils.py | Python | __dict_public__ | __dict_public__ | 441 | 455 | 441 | 441 | 71485661cb37a85a85d53d02f5dc82b7b281f9db | bigcode/the-stack | train |
cb134703e898dec1c52fd1b9 | train | function | def get_in_chunks(lst: Union[List, Iterable], chunk_size: int) -> Iterable:
"""
Yield successive chunks from a list based on the chunk_size.
:param lst: list or Iterable
:type lst: List or Iterable
:param chunk_size: size of the chunks
:type chunk_size: int
:returns: Iterator that returns l... | def get_in_chunks(lst: Union[List, Iterable], chunk_size: int) -> Iterable:
| """
Yield successive chunks from a list based on the chunk_size.
:param lst: list or Iterable
:type lst: List or Iterable
:param chunk_size: size of the chunks
:type chunk_size: int
:returns: Iterator that returns list of length chunk_size until original lst is depleted.
:rtype: Iterabl... |
if public:
super_class_dict = __dict_public__(cls=super_class)
else:
super_class_dict = super_class.__dict__
_dict.update(super_class_dict)
return _dict
def get_in_chunks(lst: Union[List, Iterable], chunk_size: int) -> Iterable:
| 64 | 64 | 121 | 19 | 44 | KaczuH/pykechain | pykechain/utils.py | Python | get_in_chunks | get_in_chunks | 495 | 507 | 495 | 495 | 37c7d6b25cef1c9279f984430f45ca34590c1974 | bigcode/the-stack | train |
04e2a36e75716819273cf825 | train | function | def is_valid_email(value: Text) -> bool:
"""
Return whether or not given value is a valid email address.
If the value is valid email this function returns ``True``.
The email will only be checked if it contains the right form, not if the email
address exist. There are many and better ways to check ... | def is_valid_email(value: Text) -> bool:
| """
Return whether or not given value is a valid email address.
If the value is valid email this function returns ``True``.
The email will only be checked if it contains the right form, not if the email
address exist. There are many and better ways to check if the email is valid, but
in this ca... | :@/]*)?"
# query string
r"(?:\?\S*)?"
# fragment
r"(?:#\S*)?" r"$",
re.UNICODE | re.IGNORECASE,
)
return bool(regex.match(value))
def is_valid_email(value: Text) -> bool:
| 64 | 64 | 193 | 11 | 53 | KaczuH/pykechain | pykechain/utils.py | Python | is_valid_email | is_valid_email | 159 | 184 | 159 | 159 | 20dadeb1495e5f0281e9bb7b01bfb696fefac44d | bigcode/the-stack | train |
eef2b7fef6c09bcd69c837c6 | train | function | def uppercase(string: Text) -> Text:
"""Convert string into upper case.
Inspired by: https://github.com/okunishinishi/python-stringcase
License: MIT
:param string: String to convert.
:returns: Upper case string.
Examples
--------
>>> uppercase('foo_bar_baz')
FOO_BAR_BAZ
>>> up... | def uppercase(string: Text) -> Text:
| """Convert string into upper case.
Inspired by: https://github.com/okunishinishi/python-stringcase
License: MIT
:param string: String to convert.
:returns: Upper case string.
Examples
--------
>>> uppercase('foo_bar_baz')
FOO_BAR_BAZ
>>> uppercase('FooBarBaz')
FOOBARBAZ
... | "[\-\.\s]", "_", str(string))
if not string:
return string
return lowercase(string[0]) + re.sub(
r"[A-Z]", lambda matched: "_" + lowercase(matched.group(0)), string[1:]
)
def uppercase(string: Text) -> Text:
| 64 | 64 | 103 | 9 | 55 | KaczuH/pykechain | pykechain/utils.py | Python | uppercase | uppercase | 399 | 416 | 399 | 399 | 628649df9e9e783158f275a754892fbadaca927c | bigcode/the-stack | train |
ad29b096728d5642c83849bf | train | function | def capitalcase(string: Text) -> Text:
"""Convert string into capital case.
First letters will be uppercase.
Inspired by: https://github.com/okunishinishi/python-stringcase
License: MIT
:param string: String to convert.
:returns: Capital case string.
Examples
--------
>>> capital... | def capitalcase(string: Text) -> Text:
| """Convert string into capital case.
First letters will be uppercase.
Inspired by: https://github.com/okunishinishi/python-stringcase
License: MIT
:param string: String to convert.
:returns: Capital case string.
Examples
--------
>>> capitalcase('foo_bar_baz')
Foo_bar_baz
... | "", str(string))
if not string:
return string
return lowercase(string[0]) + re.sub(
r"[\-_\.\s]([a-z])", lambda matched: uppercase(matched.group(1)), string[1:]
)
def capitalcase(string: Text) -> Text:
| 64 | 64 | 130 | 10 | 54 | KaczuH/pykechain | pykechain/utils.py | Python | capitalcase | capitalcase | 325 | 347 | 325 | 325 | ed19d81bf823cc6265de60b5bb8a67a042237437 | bigcode/the-stack | train |
1cfc24099ac7310366cc13c3 | train | function | def clean_empty_values(update_dict: Dict) -> Dict:
"""
Clean a dictionary by removing all the keys that have an empty value.
:param update_dict: dictionary with keys=request parameters
:type update_dict: dict
:return: same dictionary but cleaned up if there are values None
:rtype: dict
"""... | def clean_empty_values(update_dict: Dict) -> Dict:
| """
Clean a dictionary by removing all the keys that have an empty value.
:param update_dict: dictionary with keys=request parameters
:type update_dict: dict
:return: same dictionary but cleaned up if there are values None
:rtype: dict
"""
cleaned_up_dict = {k: v for k, v in update_dic... | args, **kwargs):
"""Only create a single instance of this class, i.e. simple singleton pattern."""
if cls.__instance is None:
cls.__instance = super().__new__(cls)
return cls.__instance
empty = Empty()
def clean_empty_values(update_dict: Dict) -> Dict:
| 64 | 64 | 103 | 12 | 52 | KaczuH/pykechain | pykechain/utils.py | Python | clean_empty_values | clean_empty_values | 571 | 582 | 571 | 571 | 85719bc23edad2054a7f2cc93efdf0588ec24de0 | bigcode/the-stack | train |
1dd538f93a821f192eeb39b0 | train | function | def find(iterable: Iterable[T], predicate: Callable[[T], bool]) -> Optional[T]:
"""Return the first item in the iterable that matches the predicate function."""
for i in iterable:
if predicate(i):
return i
return None
| def find(iterable: Iterable[T], predicate: Callable[[T], bool]) -> Optional[T]:
| """Return the first item in the iterable that matches the predicate function."""
for i in iterable:
if predicate(i):
return i
return None
| [a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z0-9\[\]]{2,6}\.?$"
)
def find(iterable: Iterable[T], predicate: Callable[[T], bool]) -> Optional[T]:
| 63 | 64 | 54 | 20 | 43 | KaczuH/pykechain | pykechain/utils.py | Python | find | find | 24 | 30 | 24 | 24 | 9e084db23057ac696edac506a1097a015a91f59f | bigcode/the-stack | train |
2b939970128b7d1d6edbba16 | train | function | def slugify_ref(value: Text, allow_unicode: bool = False) -> Text:
"""
Convert to ASCII if 'allow_unicode' is False. Convert spaces to hyphens.
Remove characters that aren't alphanumerics, underscores, or hyphens. Convert to lowercase.
Also strip leading and trailing whitespace.
:param value: text... | def slugify_ref(value: Text, allow_unicode: bool = False) -> Text:
| """
Convert to ASCII if 'allow_unicode' is False. Convert spaces to hyphens.
Remove characters that aren't alphanumerics, underscores, or hyphens. Convert to lowercase.
Also strip leading and trailing whitespace.
:param value: text to slugify
:param allow_unicode: (optional) boolean to allow u... | Upper case string.
Examples
--------
>>> uppercase('foo_bar_baz')
FOO_BAR_BAZ
>>> uppercase('FooBarBaz')
FOOBARBAZ
"""
return str(string).upper()
def slugify_ref(value: Text, allow_unicode: bool = False) -> Text:
| 68 | 68 | 229 | 18 | 50 | KaczuH/pykechain | pykechain/utils.py | Python | slugify_ref | slugify_ref | 419 | 438 | 419 | 419 | ff36fc72966f576fc4e5ee4dbc6b449a11616c4a | bigcode/the-stack | train |
c890a221aef8c32910405d04 | train | function | def camelcase(string: Text) -> Text:
"""Convert string into camel case.
Inspired by: https://github.com/okunishinishi/python-stringcase
License: MIT
:param string: String to convert.
:returns: Camel case string.
Examples
--------
>>> camelcase('foo_bar_baz')
fooBarBaz
>>> came... | def camelcase(string: Text) -> Text:
| """Convert string into camel case.
Inspired by: https://github.com/okunishinishi/python-stringcase
License: MIT
:param string: String to convert.
:returns: Camel case string.
Examples
--------
>>> camelcase('foo_bar_baz')
fooBarBaz
>>> camelcase('FooBarBaz')
fooBarBaz
... | kw) if v is not None}
kw["tzinfo"] = tzinfo
return datetime(**kw)
#
# The following functions are inspired by: https://github.com/okunishinishi/python-stringcase
# License: MIT
#
def camelcase(string: Text) -> Text:
| 63 | 64 | 161 | 10 | 53 | KaczuH/pykechain | pykechain/utils.py | Python | camelcase | camelcase | 300 | 322 | 300 | 300 | 2051c03f097f43b61f8fe92fd456e6de635f870d | bigcode/the-stack | train |
d90b8d0b6d5e820982f509bc | train | function | def is_uuid(value: Text) -> bool:
"""
Check if the string value is a proper UUID string.
UUID check is performed based on a regex pattern:
`r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"`
:return: True if there is a match, otherwise False
:rtype: bool
... | def is_uuid(value: Text) -> bool:
| """
Check if the string value is a proper UUID string.
UUID check is performed based on a regex pattern:
`r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"`
:return: True if there is a match, otherwise False
:rtype: bool
"""
return bool(re.match(UUID_... | def find(iterable: Iterable[T], predicate: Callable[[T], bool]) -> Optional[T]:
"""Return the first item in the iterable that matches the predicate function."""
for i in iterable:
if predicate(i):
return i
return None
def is_uuid(value: Text) -> bool:
| 64 | 64 | 129 | 10 | 53 | KaczuH/pykechain | pykechain/utils.py | Python | is_uuid | is_uuid | 33 | 43 | 33 | 33 | 5c97cf5895a591bc317db958a15f804f40f13eb1 | bigcode/the-stack | train |
7f88d3e0d9a4c71151eae077 | train | function | def parse_datetime(value: Optional[Text]) -> Optional[datetime]:
"""
Convert datetime string to datetime object.
Helper function to convert a datetime string found in json responses to a datetime object with timezone information.
The server is storing all datetime strings as UTC (ZULU time). This funct... | def parse_datetime(value: Optional[Text]) -> Optional[datetime]:
| """
Convert datetime string to datetime object.
Helper function to convert a datetime string found in json responses to a datetime object with timezone information.
The server is storing all datetime strings as UTC (ZULU time). This function supports time zone offsets. When
the input contains one, ... | in context a temporary directory
Example
-------
>>> with temp_chdir() as temp_dir:
>>> # do things here
>>> print(temp_dir) # etc etc
...
>>> # when moving out of the context the temp_dir is destroyed
>>> pass
"""
if six.PY3:
from tempfile import TemporaryDir... | 197 | 197 | 659 | 14 | 183 | KaczuH/pykechain | pykechain/utils.py | Python | parse_datetime | parse_datetime | 233 | 291 | 233 | 233 | 4e71cf16a999f16be28dc29e1d578abc4f05356e | bigcode/the-stack | train |
7b8fc0feb0fcb6abd14108f9 | train | class | class Empty(object):
"""
Represents an empty value.
In edit functions we want to be able to edit values of model properties, e.g. the due_date of a process.
Consider the following example:
def edit(self, start_date, due_date)
self.start_date = start_date
self.due_date =... | class Empty(object):
| """
Represents an empty value.
In edit functions we want to be able to edit values of model properties, e.g. the due_date of a process.
Consider the following example:
def edit(self, start_date, due_date)
self.start_date = start_date
self.due_date = due_date
... | super_class_dict = super_class.__dict__
_dict.update(super_class_dict)
return _dict
def get_in_chunks(lst: Union[List, Iterable], chunk_size: int) -> Iterable:
"""
Yield successive chunks from a list based on the chunk_size.
:param lst: list or Iterable
:type lst: List or Iterable
:... | 147 | 147 | 490 | 4 | 143 | KaczuH/pykechain | pykechain/utils.py | Python | Empty | Empty | 510 | 565 | 510 | 510 | c8cdfda2a0bd989d929da618e9ce1de873cb4e8f | bigcode/the-stack | train |
54060e0d374bf16dd8b1be9e | train | function | def __dict__inherited__(cls: type(object), stop: type(object) = type, public: Optional[bool] = True) -> Dict:
"""
Get all __dict__ items of the class and its superclasses up to `type`, or the `stop` class given as input.
:param cls: class from which to retrieve the dict.
:type cls: type(object)
:pa... | def __dict__inherited__(cls: type(object), stop: type(object) = type, public: Optional[bool] = True) -> Dict:
| """
Get all __dict__ items of the class and its superclasses up to `type`, or the `stop` class given as input.
:param cls: class from which to retrieve the dict.
:type cls: type(object)
:param stop: optional class to indicate up to which superclass the inheritance should accumulate the dict.
:t... | from pykechain.enums import Category
>>> sorted(__dict_public__(cls=Category).values())
['INSTANCE', 'MODEL']
"""
return {k: v for (k, v) in cls.__dict__.items() if not k.startswith("__")}
def __dict__inherited__(cls: type(object), stop: type(object) = type, public: Optional[bool] = True) -> Dict:
| 87 | 88 | 294 | 32 | 55 | KaczuH/pykechain | pykechain/utils.py | Python | __dict__inherited__ | __dict__inherited__ | 458 | 492 | 458 | 458 | 5c8f9508c0570340423d1be81b41645b5d580c8f | bigcode/the-stack | train |
356d19b22099328dea26bee6 | train | function | @contextmanager
def temp_chdir(cwd: Optional[Text] = None):
"""
Create and return a temporary directory which you can use as a context manager.
When you are out of the context the temprorary disk gets erased.
.. versionadded:: 2.3
:param cwd: path to change working directory back to path when out... | @contextmanager
def temp_chdir(cwd: Optional[Text] = None):
| """
Create and return a temporary directory which you can use as a context manager.
When you are out of the context the temprorary disk gets erased.
.. versionadded:: 2.3
:param cwd: path to change working directory back to path when out of context
:type cwd: basestring or None
:return: i... |
:rtype: bool
Examples
--------
>>> is_valid_email("valid_email-address@example.com")
True
>>> is_valid_email("invalid@email")
False
"""
if re.match(EMAIL_REGEX_PATTERN, str(value)):
return True
else:
return False
@contextmanager
def temp_chdir(cwd: Optional[Tex... | 83 | 83 | 277 | 18 | 64 | KaczuH/pykechain | pykechain/utils.py | Python | temp_chdir | temp_chdir | 187 | 230 | 187 | 188 | a99b17255e6c71076630249e932a6d1026529157 | bigcode/the-stack | train |
7e0e982f05d04e7627976dd3 | train | class | class UdacityPlugin(AirflowPlugin):
name = "udacity_plugin"
operators = [
operators.StageToRedshiftOperator,
operators.LoadOperator,
operators.LoadDimensionOperator,
operators.DataQualityOperator,
operators.SetupDatabaseOperator
]
helpers = [
helpers.SqlQu... | class UdacityPlugin(AirflowPlugin):
| name = "udacity_plugin"
operators = [
operators.StageToRedshiftOperator,
operators.LoadOperator,
operators.LoadDimensionOperator,
operators.DataQualityOperator,
operators.SetupDatabaseOperator
]
helpers = [
helpers.SqlQueries
]
| from __future__ import division, absolute_import, print_function
from airflow.plugins_manager import AirflowPlugin
import operators
import helpers
# Defining the plugin class
class UdacityPlugin(AirflowPlugin):
| 44 | 64 | 65 | 9 | 34 | alexanderluiscampino/yelpify | airflow/plugins/__init__.py | Python | UdacityPlugin | UdacityPlugin | 11 | 22 | 11 | 11 | efc378d8284d376fe27988ff95f1813ed901b962 | bigcode/the-stack | train |
7fc1c36c544f1a861f26e4b5 | train | class | class BuiltInResourceNoId(object):
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_typ... | class BuiltInResourceNoId(object):
| """
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'name': 'str'
}
... | # coding: utf-8
"""
FlashArray REST API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: 2.10
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re
import six
import typing
from ... | 110 | 170 | 567 | 8 | 101 | Flav-STOR-WL/py-pure-client | pypureclient/flasharray/FA_2_10/models/built_in_resource_no_id.py | Python | BuiltInResourceNoId | BuiltInResourceNoId | 24 | 111 | 24 | 24 | c2e596be2ced3729caae5f49d9f85ed4c30b7a7d | bigcode/the-stack | train |
f59696a586d29f22c7b762cf | train | class | class Trainer(object):
def __init__(self, dataset, model, model_state_file, save_dir, device, shuffle,
num_epochs, batch_size, learning_rate, early_stopping_criteria):
self.dataset = dataset
self.class_weights = dataset.class_weights.to(device)
self.model = model.to(device)
... | class Trainer(object):
| def __init__(self, dataset, model, model_state_file, save_dir, device, shuffle,
num_epochs, batch_size, learning_rate, early_stopping_criteria):
self.dataset = dataset
self.class_weights = dataset.class_weights.to(device)
self.model = model.to(device)
self.save_dir = ... | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 12 15:32:05 2019
ref: github/GokuMohandas/practicalAI: notebooks/12_Embeddings.ipynb
@author: qwang
"""
import os
os.chdir('/home/qwang/rob')
import copy
import json
import time
from argparse import Namespace
import numpy as np
import matplotlib.pyplot as plt
from gens... | 156 | 256 | 4,046 | 4 | 151 | qianyingw/rob | bin/pomegranate_20190226/train.py | Python | Trainer | Trainer | 33 | 434 | 33 | 33 | 8de6839e3204fc49963e4881c4e429654c0bfa44 | bigcode/the-stack | train |
64b1fdd2f0a0eb459b20c8f0 | train | function | def make_embeddings_matrix(words):
embedding_dim = args.embedding_dim
embeddings = np.zeros((len(words), embedding_dim))
for i, word in enumerate(words):
if word in med_w2v:
embedding_vector = med_w2v[word]
embeddings[i, :] = embedding_vector[:embedding_dim]
... | def make_embeddings_matrix(words):
| embedding_dim = args.embedding_dim
embeddings = np.zeros((len(words), embedding_dim))
for i, word in enumerate(words):
if word in med_w2v:
embedding_vector = med_w2v[word]
embeddings[i, :] = embedding_vector[:embedding_dim]
else:
embedding_i = ... | , "train_state.json"), "w") as fp:
json.dump(self.train_state, fp)
#%% Using embeddings
med_w2v = KeyedVectors.load_word2vec_format('wordvec/wikipedia-pubmed-and-PMC-w2v.bin', binary=True)
def make_embeddings_matrix(words):
| 64 | 64 | 105 | 6 | 58 | qianyingw/rob | bin/pomegranate_20190226/train.py | Python | make_embeddings_matrix | make_embeddings_matrix | 440 | 451 | 440 | 440 | be9a8ad23ade731616df7b801b6b695af7c93df5 | bigcode/the-stack | train |
d6bd9960e69fd695bccbbbbe | train | class | class Git(object):
@classmethod
def get_branch(cls, path):
return (
subprocess
.check_output("git rev-parse --abbrev-ref HEAD",
shell=True, cwd=path)
.strip()
.decode("utf-8")
)
@classmethod
def get_version(cls, ... | class Git(object):
@classmethod
| def get_branch(cls, path):
return (
subprocess
.check_output("git rev-parse --abbrev-ref HEAD",
shell=True, cwd=path)
.strip()
.decode("utf-8")
)
@classmethod
def get_version(cls, path, memo={}):
"""
R... | ` or
``setup.py develop``
"""
from __future__ import print_function, unicode_literals
import os
import re
import subprocess
import sys
from inspect import getmodule
from itertools import groupby
try:
from pkg_resources import DistributionNotFound, get_distribution, parse_version
except ImportError:
have_set... | 99 | 99 | 331 | 8 | 91 | sensiblecodeio/__autoversion__ | __autoversion__.py | Python | Git | Git | 28 | 74 | 28 | 30 | d32818299ed9167ab5b75613903cc58d6b692a92 | bigcode/the-stack | train |
87bee7fdfd734130420617df | train | function | def get_repo_type(path):
"""
Return the class representing the repository type at ``path`` if there is
one, otherwise return None.
"""
for repo_type in repo_types:
if repo_type.is_repo_instance(path):
return repo_type
| def get_repo_type(path):
| """
Return the class representing the repository type at ``path`` if there is
one, otherwise return None.
"""
for repo_type in repo_types:
if repo_type.is_repo_instance(path):
return repo_type
| controlled repository.
"""
try:
cls.get_version(path)
return True
except subprocess.CalledProcessError:
# Git returns non-zero status
return False
except OSError:
# Git unavailable?
return False
repo_types = [Git]
... | 64 | 64 | 55 | 6 | 58 | sensiblecodeio/__autoversion__ | __autoversion__.py | Python | get_repo_type | get_repo_type | 79 | 86 | 79 | 79 | 3566b2ca5860e08947becdb08c28dd06543cfbc5 | bigcode/the-stack | train |
fd2a6b8fc5657c146c2f2a26 | train | function | def try_fix_num(n):
"""
Return ``n`` as an integer if it is numeric, otherwise return the input
"""
if not n.isdigit():
return n
if n.startswith("0"):
n = n.lstrip("0")
if not n:
n = "0"
return int(n)
| def try_fix_num(n):
| """
Return ``n`` as an integer if it is numeric, otherwise return the input
"""
if not n.isdigit():
return n
if n.startswith("0"):
n = n.lstrip("0")
if not n:
n = "0"
return int(n)
| # Look at what's to the left of "."
module_name, dot, _ = module_name.partition(".")
if dot == "":
# There is no dot, nothing more we can do.
break
else:
return getversion(module_name)
return None
def try_fix_num(n):
| 64 | 64 | 71 | 6 | 57 | sensiblecodeio/__autoversion__ | __autoversion__.py | Python | try_fix_num | try_fix_num | 136 | 146 | 136 | 136 | 93063b41837118e6e9bd27ca9d672adf7ee6e27f | bigcode/the-stack | train |
619238a987e1ff58642ec6c8 | train | function | def getversion(package):
"""
Obtain the ``__version__`` for ``package``, looking at the egg information
or the source repository's version control if necessary.
"""
distribution = get_distribution(package)
if distribution is None:
raise RuntimeError("Can't find distribution {0}".format(p... | def getversion(package):
| """
Obtain the ``__version__`` for ``package``, looking at the egg information
or the source repository's version control if necessary.
"""
distribution = get_distribution(package)
if distribution is None:
raise RuntimeError("Can't find distribution {0}".format(package))
repo_type = ... | = [Git]
def get_repo_type(path):
"""
Return the class representing the repository type at ``path`` if there is
one, otherwise return None.
"""
for repo_type in repo_types:
if repo_type.is_repo_instance(path):
return repo_type
def getversion(package):
| 64 | 64 | 99 | 5 | 58 | sensiblecodeio/__autoversion__ | __autoversion__.py | Python | getversion | getversion | 89 | 101 | 89 | 89 | 7c819c025db11b053dc71ea6181649f45a3d6721 | bigcode/the-stack | train |
4d227d2f4d66c5a33043505d | train | class | class Module(type(orig)):
@property
def __version__(self):
"""
Obtain the __version__ of the module of the requestor
"""
if not have_setuptools:
return "unknown-no-setuptools"
prev_frame = sys._getframe(1)
return version_from_frame(prev_frame)
@... | class Module(type(orig)):
@property
| def __version__(self):
"""
Obtain the __version__ of the module of the requestor
"""
if not have_setuptools:
return "unknown-no-setuptools"
prev_frame = sys._getframe(1)
return version_from_frame(prev_frame)
@property
def __version_tuple__(self):... | ) for x in split if x)
# Put the tuples in groups by "-"
def is_dash(s):
return s == "-"
grouped = groupby(parsed, is_dash)
return tuple(tuple(group) for dash, group in grouped if not dash)
class Module(type(orig)):
@property
| 64 | 64 | 159 | 10 | 54 | sensiblecodeio/__autoversion__ | __autoversion__.py | Python | Module | Module | 175 | 201 | 175 | 177 | 47c4e001269e781cb44653e1a01426b5a8023c26 | bigcode/the-stack | train |
87440b9c5aea42c8fd8a740f | train | function | def version_from_frame(frame):
"""
Given a ``frame``, obtain the version number of the module running there.
"""
module = getmodule(frame)
if module is None:
s = "<unknown from {0}:{1}>"
return s.format(frame.f_code.co_filename, frame.f_lineno)
module_name = module.__name__
... | def version_from_frame(frame):
| """
Given a ``frame``, obtain the version number of the module running there.
"""
module = getmodule(frame)
if module is None:
s = "<unknown from {0}:{1}>"
return s.format(frame.f_code.co_filename, frame.f_lineno)
module_name = module.__name__
variable = "AUTOVERSION_{}".f... | = get_distribution(package)
if distribution is None:
raise RuntimeError("Can't find distribution {0}".format(package))
repo_type = get_repo_type(distribution.location)
if repo_type is None:
return distribution.version
return repo_type.get_version(distribution.location)
def version_from... | 64 | 64 | 187 | 6 | 58 | sensiblecodeio/__autoversion__ | __autoversion__.py | Python | version_from_frame | version_from_frame | 104 | 133 | 104 | 104 | f663c1e09b20d03c71b60ba6b0e090f26e95e418 | bigcode/the-stack | train |
297d4545556803883b382fce | train | function | def tupleize_version(version):
"""
Split ``version`` into a lexicographically comparable tuple.
"1.0.3" -> ((1, 0, 3),)
"1.0.3-dev" -> ((1, 0, 3), ("dev",))
"1.0.3-rc-5" -> ((1, 0, 3), ("rc",), (5,))
"""
if version is None:
return (("unknown",),)
if version.startswith("<unknow... | def tupleize_version(version):
| """
Split ``version`` into a lexicographically comparable tuple.
"1.0.3" -> ((1, 0, 3),)
"1.0.3-dev" -> ((1, 0, 3), ("dev",))
"1.0.3-rc-5" -> ((1, 0, 3), ("rc",), (5,))
"""
if version is None:
return (("unknown",),)
if version.startswith("<unknown"):
return (("unknown"... | as an integer if it is numeric, otherwise return the input
"""
if not n.isdigit():
return n
if n.startswith("0"):
n = n.lstrip("0")
if not n:
n = "0"
return int(n)
def tupleize_version(version):
| 64 | 64 | 200 | 6 | 58 | sensiblecodeio/__autoversion__ | __autoversion__.py | Python | tupleize_version | tupleize_version | 149 | 172 | 149 | 149 | 91f5c1a6575e678d5111e19088904491baa05015 | bigcode/the-stack | train |
cf2b810bd2a63cc5865f4b0f | train | class | class TimestampMixin(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
abstract = True | class TimestampMixin(models.Model):
| created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
abstract = True | #encoding: utf-8
from django.db import models
class TimestampMixin(models.Model):
| 19 | 64 | 39 | 6 | 12 | srikanta6262/old.slcpy.com | apps/slcpy/models/mixins.py | Python | TimestampMixin | TimestampMixin | 5 | 10 | 5 | 5 | 6249fe226f1c76a737d1636100ed367822e1ecf4 | bigcode/the-stack | train |
be45f0841298df2cea332c3d | train | function | def _inverted_res_block(inputs, expansion, stride, alpha, filters, block_id):
in_channels = inputs._keras_shape[-1]
pointwise_conv_filters = int(filters * alpha)
pointwise_filters = _make_divisible(pointwise_conv_filters, 8)
x = inputs
prefix = 'block_{}_'.format(block_id)
if block_id:
... | def _inverted_res_block(inputs, expansion, stride, alpha, filters, block_id):
| in_channels = inputs._keras_shape[-1]
pointwise_conv_filters = int(filters * alpha)
pointwise_filters = _make_divisible(pointwise_conv_filters, 8)
x = inputs
prefix = 'block_{}_'.format(block_id)
if block_id:
# Expand
x = layers.Conv2D(expansion * in_channels,
... | _tf_dim_ordering_tf_kernels_' +
str(alpha) + '_' + str(rows) + '_no_top' + '.h5')
weigh_path = BASE_WEIGHT_PATH + model_name
weights_path = keras_utils.get_file(
model_name, weigh_path, cache_subdir='models')
model.load_weights(we... | 121 | 121 | 406 | 19 | 101 | RamsteinWR/PneumoniaRSNA1 | src/GrayscaleModels/mobilenet_v2_gray.py | Python | _inverted_res_block | _inverted_res_block | 436 | 483 | 436 | 436 | 0c6f5891aa1228c0c0cb40a3d0e5d4cc08c937de | bigcode/the-stack | train |
f234459ce3dbd6a79cb0b293 | train | function | def relu6(x):
return backend.relu(x, max_value=6)
| def relu6(x):
| return backend.relu(x, max_value=6)
| ('models')
keras_utils = get_keras_submodule('utils')
# TODO Change path to v1.1
BASE_WEIGHT_PATH = ('https://github.com/JonathanCMitchell/mobilenet_v2_keras/'
'releases/download/v1.1/')
def relu6(x):
| 63 | 64 | 17 | 6 | 57 | RamsteinWR/PneumoniaRSNA1 | src/GrayscaleModels/mobilenet_v2_gray.py | Python | relu6 | relu6 | 96 | 97 | 96 | 96 | 43923ab9f9fbcabd035795baf419553799775ae2 | bigcode/the-stack | train |
761cd70f60c78678c45bd438 | train | function | def _make_divisible(v, divisor, min_value=None):
if min_value is None:
min_value = divisor
new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)
# Make sure that round down does not go down by more than 10%.
if new_v < 0.9 * v:
new_v += divisor
return new_v
| def _make_divisible(v, divisor, min_value=None):
| if min_value is None:
min_value = divisor
new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)
# Make sure that round down does not go down by more than 10%.
if new_v < 0.9 * v:
new_v += divisor
return new_v
| repo.
# It ensures that all layers have a channel number that is divisible by 8
# It can be seen here:
# https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py
def _make_divisible(v, divisor, min_value=None):
| 64 | 64 | 87 | 13 | 50 | RamsteinWR/PneumoniaRSNA1 | src/GrayscaleModels/mobilenet_v2_gray.py | Python | _make_divisible | _make_divisible | 124 | 131 | 124 | 124 | a3b3890476b6ef3fe3a1a7d6f4e8633a4606661d | bigcode/the-stack | train |
1ba8c8d25cb351a00c5b4a80 | train | function | def preprocess_input(x):
"""Preprocesses a numpy array encoding a batch of images.
This function applies the "Inception" preprocessing which converts
the RGB values from [0, 255] to [-1, 1]. Note that this preprocessing
function is different from `imagenet_utils.preprocess_input()`.
# Arguments
... | def preprocess_input(x):
| """Preprocesses a numpy array encoding a batch of images.
This function applies the "Inception" preprocessing which converts
the RGB values from [0, 255] to [-1, 1]. Note that this preprocessing
function is different from `imagenet_utils.preprocess_input()`.
# Arguments
x: a 4D numpy array... | Change path to v1.1
BASE_WEIGHT_PATH = ('https://github.com/JonathanCMitchell/mobilenet_v2_keras/'
'releases/download/v1.1/')
def relu6(x):
return backend.relu(x, max_value=6)
def preprocess_input(x):
| 64 | 64 | 124 | 5 | 59 | RamsteinWR/PneumoniaRSNA1 | src/GrayscaleModels/mobilenet_v2_gray.py | Python | preprocess_input | preprocess_input | 100 | 115 | 100 | 100 | b03dd453432fc0466c2b5f71744cc2338bbd81b5 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.