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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8213ef17652446a388ab6091 | train | class | class EventDisplay(urwid.WidgetWrap):
"""A widget showing one Event()'s details """
def __init__(self, conf, event, collection=None):
self._conf = conf
self.collection = collection
self.event = event
divider = urwid.Divider(' ')
lines = []
lines.append(urwid.Tex... | class EventDisplay(urwid.WidgetWrap):
| """A widget showing one Event()'s details """
def __init__(self, conf, event, collection=None):
self._conf = conf
self.collection = collection
self.event = event
divider = urwid.Divider(' ')
lines = []
lines.append(urwid.Text('Title: ' + event.summary))
... | 'This event is marked as deleted'))
self.edit(self.focus_event.event)
elif key in self._conf['keybindings']['external_edit']:
self.edit(self.focus_event.event, external_edit=True)
elif key in self._conf['keybindings']['view'] or \
self._conf['... | 134 | 134 | 447 | 9 | 125 | PsychicNoodles/khal | khal/ui/__init__.py | Python | EventDisplay | EventDisplay | 944 | 998 | 944 | 944 | f4dd04f8529ea486895e3bb10dcdcc7f7f445876 | bigcode/the-stack | train |
a88422c8be3d9a063bad6c4a | train | class | class SelectableText(urwid.Text):
def selectable(self):
return True
def keypress(self, size, key):
return key
def get_cursor_coords(self, size):
return 0, 0
def render(self, size, focus=False):
canv = super().render(size, focus)
if focus:
canv = urw... | class SelectableText(urwid.Text):
| def selectable(self):
return True
def keypress(self, size, key):
return key
def get_cursor_coords(self, size):
return 0, 0
def render(self, size, focus=False):
canv = super().render(size, focus)
if focus:
canv = urwid.CompositeCanvas(canv)
... | + | | |
# | | | | +------------------------------+ | |
# | +-----------------+ +----------------------------------+ |
# +----------------------------------------------------------+
ALL = 1
INSTANCES = 2
class DateConversionError(Exception):
pass
class SelectableText(urwid.Text):
| 64 | 64 | 97 | 9 | 54 | PsychicNoodles/khal | khal/ui/__init__.py | Python | SelectableText | SelectableText | 83 | 98 | 83 | 83 | 263219fb06ba24c8e959cec2c55e6cbc9c49dceb | bigcode/the-stack | train |
4ea74187670c9abc606fc167 | train | class | class StaticDayWalker(DayWalker):
"""Only show events for a fixed number of days."""
def ensure_date(self, day):
"""make sure a DateListBox for `day` exists, update it and bring it into focus"""
# TODO cache events for each day and update as needed
num_days = max(1, self._conf['default'... | class StaticDayWalker(DayWalker):
| """Only show events for a fixed number of days."""
def ensure_date(self, day):
"""make sure a DateListBox for `day` exists, update it and bring it into focus"""
# TODO cache events for each day and update as needed
num_days = max(1, self._conf['default']['timedelta'].days)
for ... | veal focus')
for event in self.events])
return urwid.BoxAdapter(
DateListBox(urwid.SimpleFocusListWalker(event_list), date=day),
(len(event_list) + 1) if self.events else 1
)
def selectable(self):
"""mark this widget as selectable"""
return True
... | 120 | 120 | 402 | 8 | 111 | PsychicNoodles/khal | khal/ui/__init__.py | Python | StaticDayWalker | StaticDayWalker | 507 | 558 | 507 | 507 | 481ce4984ba865d1063a5b6f1f82600d5e090d26 | bigcode/the-stack | train |
0e79407e2a7d85dd7d1878c2 | train | class | class DListBox(EventListBox):
"""Container for a DayWalker"""
# XXX unfortunate naming, there is also DateListBox
def __init__(self, *args, **kwargs):
dynamic_days = kwargs.pop('dynamic_days', True)
super().__init__(*args, **kwargs)
self._init = dynamic_days
def render(self, si... | class DListBox(EventListBox):
| """Container for a DayWalker"""
# XXX unfortunate naming, there is also DateListBox
def __init__(self, *args, **kwargs):
dynamic_days = kwargs.pop('dynamic_days', True)
super().__init__(*args, **kwargs)
self._init = dynamic_days
def render(self, size, focus=False):
if s... | = None
self.set_focus_date_callback = set_focus_date_callback
super().__init__(*args, **kwargs)
def keypress(self, size, key):
return super().keypress(size, key)
@property
def focus_event(self):
if self.focus is None:
return None
else:
retur... | 161 | 161 | 537 | 8 | 153 | PsychicNoodles/khal | khal/ui/__init__.py | Python | DListBox | DListBox | 277 | 347 | 277 | 277 | f2f6dc6f86b0acbd74833f86dbf0cb84e058aeed | bigcode/the-stack | train |
3f26d5dc928ef210b965665f | train | class | class U_Event(urwid.Text):
def __init__(self, event, conf, delete_status, this_date=None, relative=True):
"""representation of an event in EventList
:param event: the encapsulated event
:type event: khal.event.Event
"""
if relative:
if isinstance(this_date, dt.da... | class U_Event(urwid.Text):
| def __init__(self, event, conf, delete_status, this_date=None, relative=True):
"""representation of an event in EventList
:param event: the encapsulated event
:type event: khal.event.Event
"""
if relative:
if isinstance(this_date, dt.datetime) or not isinstance(t... | omorrow ({weekday}, {daystr})'
elif day == dt.date.today() - dt.timedelta(days=1):
return f'Yesterday ({weekday}, {daystr})'
approx_delta = utils.relative_timedelta_str(day)
return '{weekday}, {day} ({approx_delta})'.format(
weekday=weekday,
approx_delta=app... | 171 | 171 | 570 | 8 | 162 | PsychicNoodles/khal | khal/ui/__init__.py | Python | U_Event | U_Event | 161 | 234 | 161 | 161 | 9adacf7bf9e2f8097f02f0905289afb61fbaedb6 | bigcode/the-stack | train |
504b82d38f08d6610fcc8122 | train | function | def _urwid_palette_entry(name, color, hmethod):
"""Create an urwid compatible palette entry.
:param name: name of the new attribute in the palette
:type name: string
:param color: color for the new attribute
:type color: string
:returns: an urwid palette entry
:rtype: tuple
"""
from... | def _urwid_palette_entry(name, color, hmethod):
| """Create an urwid compatible palette entry.
:param name: name of the new attribute in the palette
:type name: string
:param color: color for the new attribute
:type color: string
:returns: an urwid palette entry
:rtype: tuple
"""
from ..terminal import COLORS
if color == '' or ... | events = EventColumn(pane=self, elistbox=events)
ContainerWidget = linebox[self._conf['view']['frame']]
columns = NColumns(
[(self.lwidth, self.calendar), ContainerWidget(events)],
dividechars=0,
box_columns=[0, 0],
outermost=True,
)
... | 227 | 227 | 759 | 13 | 214 | PsychicNoodles/khal | khal/ui/__init__.py | Python | _urwid_palette_entry | _urwid_palette_entry | 1,179 | 1,244 | 1,179 | 1,179 | ef3801aac63e5538b302d442b495308c28f76382 | bigcode/the-stack | train |
37067acf86b77e8112e1f9de | train | class | class DateConversionError(Exception):
pass
| class DateConversionError(Exception):
| pass
| |
# | | | | | +--------------------------+ | | |
# | | | | +------------------------------+ | |
# | +-----------------+ +----------------------------------+ |
# +----------------------------------------------------------+
ALL = 1
INSTANCES = 2
class DateConversionError(Exceptio... | 64 | 64 | 9 | 6 | 57 | PsychicNoodles/khal | khal/ui/__init__.py | Python | DateConversionError | DateConversionError | 79 | 80 | 79 | 79 | fc70a7ddaff3f67ccfec3b607fbf3e2c0bda76eb | bigcode/the-stack | train |
0f570bd0b8b7385325541a0a | train | class | class TestSMSES(ElasticTestMixin, SimpleTestCase):
def test_processed_or_incoming(self):
json_output = {
"query": {
"filtered": {
"filter": {
"and": [
{"term": {"domain.exact": "demo"}},
... | class TestSMSES(ElasticTestMixin, SimpleTestCase):
| def test_processed_or_incoming(self):
json_output = {
"query": {
"filtered": {
"filter": {
"and": [
{"term": {"domain.exact": "demo"}},
{
"not": {
... | from django.test.testcases import SimpleTestCase
from corehq.apps.es.sms import SMSES
from corehq.apps.es.tests.utils import ElasticTestMixin
from corehq.elastic import SIZE_LIMIT
class TestSMSES(ElasticTestMixin, SimpleTestCase):
| 53 | 64 | 155 | 13 | 39 | rochakchauhan/commcare-hq | corehq/apps/es/tests/test_sms.py | Python | TestSMSES | TestSMSES | 8 | 35 | 8 | 8 | 74807b020ece260a19ffe58fcecb49e80b1b7e21 | bigcode/the-stack | train |
cebb466a51aed2467fd641bf | train | function | def comment_to_base(comment: YoutrackIssueComment):
return Comment(author=User(id=-1,
name=comment.author.fullName,
username=comment.author.login
),
text=comment.text if comment.text else "",
... | def comment_to_base(comment: YoutrackIssueComment):
| return Comment(author=User(id=-1,
name=comment.author.fullName,
username=comment.author.login
),
text=comment.text if comment.text else "",
created_at=float(comment.created) if comment.... | estimation=estimation,
time_spent=time_spent,
sprint=sprint,
attachments=[attachment_to_base(attachment) for attachment in issue.attachments]
)
deduplicate_attachments(converted_issue)
return converted_issue
def comment_to_base(comment: YoutrackIssueComment):
... | 64 | 64 | 83 | 12 | 51 | tafilz/yittrab | issuelab/tracker/youtrack/converter.py | Python | comment_to_base | comment_to_base | 108 | 118 | 108 | 110 | 2c1ee9ccc082afe32cff2d5d55abdad199e6fb92 | bigcode/the-stack | train |
4e5edf8b8d49f80f8155caa3 | train | function | def label_to_base(label: YouTrackIssueTags):
return Label(name=label.name,
description="",
color_hex=label.color.background if label.color.background else None
)
| def label_to_base(label: YouTrackIssueTags):
| return Label(name=label.name,
description="",
color_hex=label.color.background if label.color.background else None
)
| username=comment.author.login
),
text=comment.text if comment.text else "",
created_at=float(comment.created) if comment.created else 0.0,
attachments=[attachment_to_base(attachment) for attachment in ... | 64 | 64 | 39 | 11 | 53 | tafilz/yittrab | issuelab/tracker/youtrack/converter.py | Python | label_to_base | label_to_base | 119 | 123 | 119 | 119 | 15020e9e4f6d7f422d2d463aa8430fac1e7440fd | bigcode/the-stack | train |
e1dc84bb7ab7d860c0f490e1 | train | function | def attachment_to_base(attachment: YouTrackIssueAttachment):
return Attachment(filename=attachment.name,
url=attachment.url)
| def attachment_to_base(attachment: YouTrackIssueAttachment):
| return Attachment(filename=attachment.name,
url=attachment.url)
| (attachment) for attachment in comment.attachments]
)
def label_to_base(label: YouTrackIssueTags):
return Label(name=label.name,
description="",
color_hex=label.color.background if label.color.background else None
)
def attachment_to_base(attachm... | 63 | 64 | 26 | 12 | 51 | tafilz/yittrab | issuelab/tracker/youtrack/converter.py | Python | attachment_to_base | attachment_to_base | 125 | 127 | 125 | 125 | 057bc17d1eee90ee1813ae152e925e124ddc7e3e | bigcode/the-stack | train |
95dbb89ebb7c906854b6af05 | train | function | def sprint_to_base(sprint: YouTrackSprint) -> Milestone:
return Milestone(
id = int(sprint.id[sprint.id.find('-') + 1:]),
title = sprint.name,
description = "" if not sprint.goal else sprint.goal,
state = MilestoneState.CLOSED if sprint.archived else MilestoneState.ACTIVE,
... | def sprint_to_base(sprint: YouTrackSprint) -> Milestone:
| return Milestone(
id = int(sprint.id[sprint.id.find('-') + 1:]),
title = sprint.name,
description = "" if not sprint.goal else sprint.goal,
state = MilestoneState.CLOSED if sprint.archived else MilestoneState.ACTIVE,
start_date = None if not sprint.start else float(sprint.sta... | .base.user import User
from issuelab.base.label import Label
from issuelab.base.attachment import Attachment
from issuelab.tracker.youtrack.entities import *
closed_text = ['Done', 'Duplicate', 'Geschlossen']
def sprint_to_base(sprint: YouTrackSprint) -> Milestone:
| 64 | 64 | 109 | 16 | 48 | tafilz/yittrab | issuelab/tracker/youtrack/converter.py | Python | sprint_to_base | sprint_to_base | 15 | 23 | 15 | 15 | 7f1208788d13b17c2f1871af6ccf104d8e4fc32d | bigcode/the-stack | train |
fd15780ad2eb074cf098b343 | train | function | def issue_to_base(issue: YouTrackIssue) -> Issue:
comments: List[Comment] = []
labels: List[Label] = []
# comments
for comment in issue.comments:
comments.append(comment_to_base(comment))
# labels
for label in issue.tags:
labels.append(label_to_base(label))
... | def issue_to_base(issue: YouTrackIssue) -> Issue:
| comments: List[Comment] = []
labels: List[Label] = []
# comments
for comment in issue.comments:
comments.append(comment_to_base(comment))
# labels
for label in issue.tags:
labels.append(label_to_base(label))
state = IssueState.OPEN
estimati... | Label
from issuelab.base.attachment import Attachment
from issuelab.tracker.youtrack.entities import *
closed_text = ['Done', 'Duplicate', 'Geschlossen']
def sprint_to_base(sprint: YouTrackSprint) -> Milestone:
return Milestone(
id = int(sprint.id[sprint.id.find('-') + 1:]),
title = sprint.n... | 158 | 159 | 530 | 13 | 145 | tafilz/yittrab | issuelab/tracker/youtrack/converter.py | Python | issue_to_base | issue_to_base | 25 | 106 | 25 | 25 | 78cbac2864f8346d4529cb274de5530be1d01671 | bigcode/the-stack | train |
673da62e75b9e15beed05d4b | train | function | def deduplicate_attachments(issue: Issue):
for comment in issue.comments:
for attachment in comment.attachments:
# compare with issue attachments
for issue_attachment in issue.attachments:
if attachment.filename == issue_attachment.filename:
issue.... | def deduplicate_attachments(issue: Issue):
| for comment in issue.comments:
for attachment in comment.attachments:
# compare with issue attachments
for issue_attachment in issue.attachments:
if attachment.filename == issue_attachment.filename:
issue.attachments.remove(issue_attachment) | return Label(name=label.name,
description="",
color_hex=label.color.background if label.color.background else None
)
def attachment_to_base(attachment: YouTrackIssueAttachment):
return Attachment(filename=attachment.name,
url=attachment.... | 63 | 64 | 57 | 9 | 54 | tafilz/yittrab | issuelab/tracker/youtrack/converter.py | Python | deduplicate_attachments | deduplicate_attachments | 129 | 135 | 129 | 129 | 39f82623312e1cbbb56e218296193b8d6429dcc5 | bigcode/the-stack | train |
03106161252cc10a306431b7 | train | function | def test_protocols_conflict(builder):
builder.declare("x", protocol=bn.protocol.type(int))
incoming_builder = bn.FlowBuilder("new_name")
incoming_builder.declare("x", protocol=bn.protocol.type(str))
with pytest.raises(AlreadyDefinedEntityError):
builder.merge(incoming_builder.build())
bui... | def test_protocols_conflict(builder):
| builder.declare("x", protocol=bn.protocol.type(int))
incoming_builder = bn.FlowBuilder("new_name")
incoming_builder.declare("x", protocol=bn.protocol.type(str))
with pytest.raises(AlreadyDefinedEntityError):
builder.merge(incoming_builder.build())
builder.merge(incoming_builder.build(), k... | erging(new_flow, keep="error")
assert old_flow.merging(new_flow, keep="old").get(CACHE_DIR_ENT) == "old_dir"
assert old_flow.merging(new_flow, keep="new").get(CACHE_DIR_ENT) == "new_dir"
def test_protocols_conflict(builder):
| 64 | 64 | 142 | 8 | 56 | IDl0T/bionic | tests/test_flow/test_merge.py | Python | test_protocols_conflict | test_protocols_conflict | 291 | 308 | 291 | 291 | 29dad02ea18cb83e764c02e396b605e033135f49 | bigcode/the-stack | train |
0a86e65504c39523dec07b06 | train | function | def test_keep_old(merge_tester):
merge_tester.test_grid(
keep="old",
grid="""
OLD:NEW M D FS FM DS DJ FJ
Missing . - ^ ^ ^ ^ ^
Declared - - ^ ^ ^ ^ ^
FixedSingle < < < < < X X
FixedMulti < < < < < X X
... | def test_keep_old(merge_tester):
| merge_tester.test_grid(
keep="old",
grid="""
OLD:NEW M D FS FM DS DJ FJ
Missing . - ^ ^ ^ ^ ^
Declared - - ^ ^ ^ ^ ^
FixedSingle < < < < < X X
FixedMulti < < < < < X X
DerivedSingle < < < < < X ... | DerivedSingle < < ! ! ! ! !
DerivedJoint < < ! ! ! ! !
FixedJoint < < ! ! ! ! !
""",
)
def test_keep_old(merge_tester):
| 64 | 64 | 166 | 9 | 55 | IDl0T/bionic | tests/test_flow/test_merge.py | Python | test_keep_old | test_keep_old | 206 | 219 | 206 | 206 | 13df0ae1c8a33d73c7d45c1fb31bd81cca6237d3 | bigcode/the-stack | train |
ab41fb7e087c5a9a453ec3e1 | train | function | def test_keep_new(merge_tester):
merge_tester.test_grid(
keep="new",
grid="""
OLD:NEW M D FS FM DS DJ FJ
Missing . - ^ ^ ^ ^ ^
Declared - - ^ ^ ^ ^ ^
FixedSingle < < ^ ^ ^ ^ ^
FixedMulti < < ^ ^ ^ ^ ^
... | def test_keep_new(merge_tester):
| merge_tester.test_grid(
keep="new",
grid="""
OLD:NEW M D FS FM DS DJ FJ
Missing . - ^ ^ ^ ^ ^
Declared - - ^ ^ ^ ^ ^
FixedSingle < < ^ ^ ^ ^ ^
FixedMulti < < ^ ^ ^ ^ ^
DerivedSingle < < ^ ^ ^ ^ ... | Single < < < < < X X
DerivedJoint < < < < < < <
FixedJoint < < < < < < <
""",
)
def test_keep_new(merge_tester):
| 64 | 64 | 163 | 9 | 55 | IDl0T/bionic | tests/test_flow/test_merge.py | Python | test_keep_new | test_keep_new | 222 | 235 | 222 | 222 | 2fc9da3bef91c979b3d94a9121515e9acdc5790f | bigcode/the-stack | train |
cf3dbc546460d1c4afdb65a9 | train | function | @pytest.fixture(scope="function")
def merge_tester(builder):
f = builder.build()
tester = MergeTester()
tester.add("Missing", f)
tester.add("Declared", f.declaring("x"))
tester.add("FixedSingle", f.assigning("x", 2))
tester.add("FixedMulti", f.assigning("x", values=[3, 4]))
fb = f.to_buil... | @pytest.fixture(scope="function")
def merge_tester(builder):
| f = builder.build()
tester = MergeTester()
tester.add("Missing", f)
tester.add("Declared", f.declaring("x"))
tester.add("FixedSingle", f.assigning("x", 2))
tester.add("FixedMulti", f.assigning("x", values=[3, 4]))
fb = f.to_builder()
fb.assign("root_x", 3)
@fb
def x(root_x):
... | == "^":
# Entity should have the new values.
merged_flow = old_flow.merging(new_flow, keep)
assert merged_flow.get("x", set) == new_flow.get("x", set)
elif outcome_key == "!":
# Merge should fail.
with pytest.raises(AlreadyDefinedEntityError):
... | 187 | 187 | 626 | 12 | 175 | IDl0T/bionic | tests/test_flow/test_merge.py | Python | merge_tester | merge_tester | 115 | 187 | 115 | 116 | ad6a471104d104e7618b00b69ca6b2339beb7b21 | bigcode/the-stack | train |
feba914aa10b0ef2cf5a3744 | train | function | def test_old_name_is_kept():
old_flow = bn.FlowBuilder("old").build()
new_flow = bn.FlowBuilder("new").build()
for keep in ALL_KEEP_VALUES:
assert old_flow.merging(new_flow, keep=keep).name == "old"
| def test_old_name_is_kept():
| old_flow = bn.FlowBuilder("old").build()
new_flow = bn.FlowBuilder("new").build()
for keep in ALL_KEEP_VALUES:
assert old_flow.merging(new_flow, keep=keep).name == "old"
| DerivedSingle < < ^ ^ ^ ^ ^
DerivedJoint < < X X X ^ ^
FixedJoint < < X X X ^ ^
""",
)
def test_old_name_is_kept():
| 64 | 64 | 58 | 8 | 56 | IDl0T/bionic | tests/test_flow/test_merge.py | Python | test_old_name_is_kept | test_old_name_is_kept | 238 | 243 | 238 | 238 | dd7b87a83fc5ea2e12fc9819fb92c4f88d1a43de | bigcode/the-stack | train |
77670f2a2b6e09695a44ad10 | train | function | def test_keep_error(merge_tester):
merge_tester.test_grid(
keep="error",
grid="""
OLD:NEW M D FS FM DS DJ FJ
Missing . - ^ ^ ^ ^ ^
Declared - - ^ ^ ^ ^ ^
FixedSingle < < ! ! ! ! !
FixedMulti < < ! ! ! ! !
... | def test_keep_error(merge_tester):
| merge_tester.test_grid(
keep="error",
grid="""
OLD:NEW M D FS FM DS DJ FJ
Missing . - ^ ^ ^ ^ ^
Declared - - ^ ^ ^ ^ ^
FixedSingle < < ! ! ! ! !
FixedMulti < < ! ! ! ! !
DerivedSingle < < ! ! ! ... | : F811
return x_y
tester.add("DJ", fb.build())
tester.add("FJ", f.declaring("x").declaring("y").adding_case("x", 17, "y", 18))
return tester
def test_keep_error(merge_tester):
| 64 | 64 | 163 | 9 | 54 | IDl0T/bionic | tests/test_flow/test_merge.py | Python | test_keep_error | test_keep_error | 190 | 203 | 190 | 190 | 24ba9240b4de96cf197f6c7c1c175302fa63e47f | bigcode/the-stack | train |
7961d59a7fb5e221a222cc54 | train | function | def test_cache_dir_conflicts():
old_flow = bn.FlowBuilder("old").build().setting(CACHE_DIR_ENT, "old_dir")
new_flow = bn.FlowBuilder("new").build().setting(CACHE_DIR_ENT, "new_dir")
with pytest.raises(AlreadyDefinedEntityError):
old_flow.merging(new_flow, keep="error")
assert old_flow.merging(n... | def test_cache_dir_conflicts():
| old_flow = bn.FlowBuilder("old").build().setting(CACHE_DIR_ENT, "old_dir")
new_flow = bn.FlowBuilder("new").build().setting(CACHE_DIR_ENT, "new_dir")
with pytest.raises(AlreadyDefinedEntityError):
old_flow.merging(new_flow, keep="error")
assert old_flow.merging(new_flow, keep="old").get(CACHE_D... | ").build()
new_flow = bn.FlowBuilder("new").build().setting(CACHE_DIR_ENT, "new_dir")
for keep in ALL_KEEP_VALUES:
assert old_flow.merging(new_flow, keep=keep).get(CACHE_DIR_ENT) == "new_dir"
def test_cache_dir_conflicts():
| 64 | 64 | 121 | 7 | 57 | IDl0T/bionic | tests/test_flow/test_merge.py | Python | test_cache_dir_conflicts | test_cache_dir_conflicts | 281 | 288 | 281 | 281 | d1e6c9c80defb99c6b15d121df02d6c07a81ac2f | bigcode/the-stack | train |
263f772948d153099745f44f | train | function | def test_protocol_is_overwritten(builder):
builder.declare("x", protocol=bn.protocol.type(int))
incoming_builder = bn.FlowBuilder("new_name")
incoming_builder.assign("x", "blue", protocol=bn.protocol.type(str))
builder.merge(incoming_builder.build(), keep="new")
with pytest.raises(EntityValueErro... | def test_protocol_is_overwritten(builder):
| builder.declare("x", protocol=bn.protocol.type(int))
incoming_builder = bn.FlowBuilder("new_name")
incoming_builder.assign("x", "blue", protocol=bn.protocol.type(str))
builder.merge(incoming_builder.build(), keep="new")
with pytest.raises(EntityValueError):
builder.set("x", 3)
assert... | )
with pytest.raises(EntityValueError):
builder.set("x", "blue")
builder.merge(incoming_builder.build(), keep="new")
builder.set("x", "blue")
with pytest.raises(EntityValueError):
builder.set("x", 1)
def test_protocol_is_overwritten(builder):
| 64 | 64 | 92 | 8 | 56 | IDl0T/bionic | tests/test_flow/test_merge.py | Python | test_protocol_is_overwritten | test_protocol_is_overwritten | 311 | 322 | 311 | 311 | a0ea923be3ffcd4583c4acfebd8bc4c13e1c7b2e | bigcode/the-stack | train |
b29a569b5b364182b8a5ab65 | train | class | class MergeTester:
"""
A utility class for testing many variations of flow merging. This class
is configured by creating several flows, associated them with names using
the ``add`` method, and then calling ``test_grid`` with a string that
visually represents flow combinations and the expected outco... | class MergeTester:
| """
A utility class for testing many variations of flow merging. This class
is configured by creating several flows, associated them with names using
the ``add`` method, and then calling ``test_grid`` with a string that
visually represents flow combinations and the expected outcome from
merging... | import pytest
import bionic as bn
from bionic.exception import (
AlreadyDefinedEntityError,
EntityValueError,
IncompatibleEntityError,
UndefinedEntityError,
)
ALL_KEEP_VALUES = ["error", "old", "new", "combine"]
class MergeTester:
| 58 | 247 | 824 | 4 | 54 | IDl0T/bionic | tests/test_flow/test_merge.py | Python | MergeTester | MergeTester | 14 | 110 | 14 | 14 | e4eeafd8b79e4fdb906ba2e49247b89232b7e090 | bigcode/the-stack | train |
c22239ecc816678fd2f2d7eb | train | function | def test_cache_dir_already_set():
old_flow = bn.FlowBuilder("old").build().setting(CACHE_DIR_ENT, "old_dir")
new_flow = bn.FlowBuilder("new").build()
for keep in ALL_KEEP_VALUES:
assert old_flow.merging(new_flow, keep=keep).get(CACHE_DIR_ENT) == "old_dir"
| def test_cache_dir_already_set():
| old_flow = bn.FlowBuilder("old").build().setting(CACHE_DIR_ENT, "old_dir")
new_flow = bn.FlowBuilder("new").build()
for keep in ALL_KEEP_VALUES:
assert old_flow.merging(new_flow, keep=keep).get(CACHE_DIR_ENT) == "old_dir"
| old_flow = bn.FlowBuilder("old").build()
new_flow = bn.FlowBuilder("new").build()
for keep in ALL_KEEP_VALUES:
assert old_flow.merging(new_flow, keep=keep).get(CACHE_DIR_ENT) == "bndata"
def test_cache_dir_already_set():
| 64 | 64 | 74 | 8 | 56 | IDl0T/bionic | tests/test_flow/test_merge.py | Python | test_cache_dir_already_set | test_cache_dir_already_set | 265 | 270 | 265 | 265 | 4b63be3e56d2d6bb72cce2ac7ea46f7982d90fd6 | bigcode/the-stack | train |
379ff3c289dd90c2e4897c32 | train | function | def test_cache_dir_set_on_incoming():
old_flow = bn.FlowBuilder("old").build()
new_flow = bn.FlowBuilder("new").build().setting(CACHE_DIR_ENT, "new_dir")
for keep in ALL_KEEP_VALUES:
assert old_flow.merging(new_flow, keep=keep).get(CACHE_DIR_ENT) == "new_dir"
| def test_cache_dir_set_on_incoming():
| old_flow = bn.FlowBuilder("old").build()
new_flow = bn.FlowBuilder("new").build().setting(CACHE_DIR_ENT, "new_dir")
for keep in ALL_KEEP_VALUES:
assert old_flow.merging(new_flow, keep=keep).get(CACHE_DIR_ENT) == "new_dir"
| ().setting(CACHE_DIR_ENT, "old_dir")
new_flow = bn.FlowBuilder("new").build()
for keep in ALL_KEEP_VALUES:
assert old_flow.merging(new_flow, keep=keep).get(CACHE_DIR_ENT) == "old_dir"
def test_cache_dir_set_on_incoming():
| 64 | 64 | 75 | 9 | 55 | IDl0T/bionic | tests/test_flow/test_merge.py | Python | test_cache_dir_set_on_incoming | test_cache_dir_set_on_incoming | 273 | 278 | 273 | 273 | d0ff0b7b57ce037bdb5b5bb397acc4274a4749ed | bigcode/the-stack | train |
ea2da0dccf4d015b647121b2 | train | function | def test_old_name_is_kept_even_on_explicit_rename():
old_flow = bn.FlowBuilder("old").build()
new_flow = bn.FlowBuilder("new").build().setting("core__flow_name", "NEW")
for keep in ALL_KEEP_VALUES:
assert old_flow.merging(new_flow, keep=keep).name == "old"
| def test_old_name_is_kept_even_on_explicit_rename():
| old_flow = bn.FlowBuilder("old").build()
new_flow = bn.FlowBuilder("new").build().setting("core__flow_name", "NEW")
for keep in ALL_KEEP_VALUES:
assert old_flow.merging(new_flow, keep=keep).name == "old"
| old_flow = bn.FlowBuilder("old").build()
new_flow = bn.FlowBuilder("new").build()
for keep in ALL_KEEP_VALUES:
assert old_flow.merging(new_flow, keep=keep).name == "old"
def test_old_name_is_kept_even_on_explicit_rename():
| 64 | 64 | 74 | 14 | 50 | IDl0T/bionic | tests/test_flow/test_merge.py | Python | test_old_name_is_kept_even_on_explicit_rename | test_old_name_is_kept_even_on_explicit_rename | 246 | 251 | 246 | 246 | 11ded722d563c8708b1dd13d28abb249f7910cd3 | bigcode/the-stack | train |
a22f6971a3743f176cb21a81 | train | function | def test_cache_dir_not_set():
old_flow = bn.FlowBuilder("old").build()
new_flow = bn.FlowBuilder("new").build()
for keep in ALL_KEEP_VALUES:
assert old_flow.merging(new_flow, keep=keep).get(CACHE_DIR_ENT) == "bndata"
| def test_cache_dir_not_set():
| old_flow = bn.FlowBuilder("old").build()
new_flow = bn.FlowBuilder("new").build()
for keep in ALL_KEEP_VALUES:
assert old_flow.merging(new_flow, keep=keep).get(CACHE_DIR_ENT) == "bndata"
| bn.FlowBuilder("new").build().setting("core__flow_name", "NEW")
for keep in ALL_KEEP_VALUES:
assert old_flow.merging(new_flow, keep=keep).name == "old"
CACHE_DIR_ENT = "core__persistent_cache__global_dir"
def test_cache_dir_not_set():
| 64 | 64 | 63 | 7 | 57 | IDl0T/bionic | tests/test_flow/test_merge.py | Python | test_cache_dir_not_set | test_cache_dir_not_set | 257 | 262 | 257 | 257 | f4ba31b8339f9d10df04417ac5d4f62170662d4a | bigcode/the-stack | train |
4e9ba25fbb289b3083906681 | train | class | class verify_base(plain.plain):
def __init__(self, method):
super(verify_base, self).__init__(method)
self.method = method
def init_data(self):
return obfs_verify_data()
def set_server_info(self, server_info):
self.server_info = server_info
def client_encode(self, buf)... | class verify_base(plain.plain):
| def __init__(self, method):
super(verify_base, self).__init__(method)
self.method = method
def init_data(self):
return obfs_verify_data()
def set_server_info(self, server_info):
self.server_info = server_info
def client_encode(self, buf):
return buf
def cl... | _begin(str1, str2):
if len(str1) >= len(str2):
if str1[:len(str2)] == str2:
return True
return False
class obfs_verify_data(object):
def __init__(self):
pass
class verify_base(plain.plain):
| 64 | 64 | 122 | 8 | 55 | 0mco/shadowsocksR | shadowsocks/obfsplugin/verify.py | Python | verify_base | verify_base | 61 | 82 | 61 | 61 | 8831137828e5f8c3458f636b724142fea1043a27 | bigcode/the-stack | train |
648b60647d386b60f8a036b0 | train | class | class verify_deflate(verify_base):
def __init__(self, method):
super(verify_deflate, self).__init__(method)
self.recv_buf = b''
self.unit_len = 32700
self.decrypt_packet_num = 0
self.raw_trans = False
def pack_data(self, buf):
if len(buf) == 0:
return... | class verify_deflate(verify_base):
| def __init__(self, method):
super(verify_deflate, self).__init__(method)
self.recv_buf = b''
self.unit_len = 32700
self.decrypt_packet_num = 0
self.raw_trans = False
def pack_data(self, buf):
if len(buf) == 0:
return b''
data = zlib.compress(b... | ) >= len(str2):
if str1[:len(str2)] == str2:
return True
return False
class obfs_verify_data(object):
def __init__(self):
pass
class verify_base(plain.plain):
def __init__(self, method):
super(verify_base, self).__init__(method)
self.method = method
def i... | 174 | 174 | 583 | 8 | 166 | 0mco/shadowsocksR | shadowsocks/obfsplugin/verify.py | Python | verify_deflate | verify_deflate | 85 | 159 | 85 | 85 | de3870dabc085ec57f5bed7637efa40b95dfe8c5 | bigcode/the-stack | train |
ada31da6c2b45e0ab112d685 | train | function | def match_begin(str1, str2):
if len(str1) >= len(str2):
if str1[:len(str2)] == str2:
return True
return False
| def match_begin(str1, str2):
| if len(str1) >= len(str2):
if str1[:len(str2)] == str2:
return True
return False
| .obfsplugin import plain
from shadowsocks.core.common import to_bytes, to_str, ord, chr
def create_verify_deflate(method):
return verify_deflate(method)
obfs_map = {
'verify_deflate': (create_verify_deflate, ),
}
def match_begin(str1, str2):
| 64 | 64 | 41 | 9 | 55 | 0mco/shadowsocksR | shadowsocks/obfsplugin/verify.py | Python | match_begin | match_begin | 49 | 53 | 49 | 49 | 39a58305ba256f4d5c6ecc2707ab267a0d10cab0 | bigcode/the-stack | train |
0e141c1cb53c19c2dd5bb843 | train | class | class obfs_verify_data(object):
def __init__(self):
pass
| class obfs_verify_data(object):
| def __init__(self):
pass
| = {
'verify_deflate': (create_verify_deflate, ),
}
def match_begin(str1, str2):
if len(str1) >= len(str2):
if str1[:len(str2)] == str2:
return True
return False
class obfs_verify_data(object):
| 64 | 64 | 17 | 7 | 56 | 0mco/shadowsocksR | shadowsocks/obfsplugin/verify.py | Python | obfs_verify_data | obfs_verify_data | 56 | 58 | 56 | 56 | 7edefea4268581fbf9bc9802294dc3b751186747 | bigcode/the-stack | train |
0c8eba0deb3d3e4c144d8002 | train | function | def create_verify_deflate(method):
return verify_deflate(method)
| def create_verify_deflate(method):
| return verify_deflate(method)
|
import datetime
import random
import struct
import zlib
import hmac
import hashlib
import shadowsocks
from shadowsocks.core import common
from shadowsocks.obfsplugin import plain
from shadowsocks.core.common import to_bytes, to_str, ord, chr
def create_verify_deflate(method):
| 64 | 64 | 14 | 7 | 56 | 0mco/shadowsocksR | shadowsocks/obfsplugin/verify.py | Python | create_verify_deflate | create_verify_deflate | 40 | 41 | 40 | 40 | bd8966bbc60c054494cdbbd794c11e6db350ddb6 | bigcode/the-stack | train |
df1c2868af769e40ee52f55d | train | class | class AssignedGroup:
group: UnitGroup
retreaters: UnitGroup
enemies: UnitGroup | class AssignedGroup:
| group: UnitGroup
retreaters: UnitGroup
enemies: UnitGroup | from bot.services.unit_group_service import UnitGroup
class AssignedGroup:
| 14 | 64 | 22 | 4 | 9 | Scottdecat/HiveMind | bot/logic/unit_manager/assigned_group.py | Python | AssignedGroup | AssignedGroup | 3 | 6 | 3 | 3 | 50035b9111ca48bc5c85cea6925257f531f9c37b | bigcode/the-stack | train |
af00ca81deba120ddec95897 | train | function | def from_row_splits(values, row_splits, name=None):
"""Creates a `RaggedTensor` with rows partitioned by `row_splits`.
The returned `RaggedTensor` corresponds with the python list defined by:
```python
result = [values[row_splits[i]:row_splits[i + 1]]
for i in range(len(row_splits) - 1)]
```
... | def from_row_splits(values, row_splits, name=None):
| """Creates a `RaggedTensor` with rows partitioned by `row_splits`.
The returned `RaggedTensor` corresponds with the python list defined by:
```python
result = [values[row_splits[i]:row_splits[i + 1]]
for i in range(len(row_splits) - 1)]
```
Args:
values: A potentially ragged tensor with s... | .bincount(
value_rowids_int32,
minlength=nrows_int32,
maxlength=nrows_int32,
dtype=dtypes.int64)
row_splits = array_ops.concat([[0], math_ops.cumsum(row_lengths)], axis=0)
if const_nrows is not None:
row_lengths.set_shape([const_nrows])
row_splits.set_shape([const_nro... | 146 | 146 | 487 | 14 | 132 | wenming2014/tensorflow | tensorflow/python/ops/ragged/ragged_factory_ops.py | Python | from_row_splits | from_row_splits | 447 | 487 | 447 | 447 | 29c23d8c0835fa1cd0542aaa198bf3ce36bebaf4 | bigcode/the-stack | train |
b2f1c5d40320e5840dd4c80c | train | function | def convert_to_tensor_or_ragged_tensor(value,
dtype=None,
preferred_dtype=None,
name=None):
"""Converts value to a `RaggedTensor` or `Tensor`.
* If `value` is a `RaggedTensor`, then return it as-is.... | def convert_to_tensor_or_ragged_tensor(value,
dtype=None,
preferred_dtype=None,
name=None):
| """Converts value to a `RaggedTensor` or `Tensor`.
* If `value` is a `RaggedTensor`, then return it as-is.
* If `value` is a `RaggedTensorValue`, return a corresponding constant
`RaggedTensor`.
* Otherwise, use `convert_to_tensor` to convert `value` to a `Tensor`.
Args:
value: A `RaggedTensor`, a `R... | (dim + 1, ragged_rank, ragged_rank))
inner_values = sum((list(v) for v in inner_values), [])
# Compute the inner shape looking only at the leftmost elements; and then
# use check_inner_shape to verify that other elements have the same shape.
inner_shape = get_inner_shape(inner_values)
... | 128 | 128 | 429 | 24 | 104 | wenming2014/tensorflow | tensorflow/python/ops/ragged/ragged_factory_ops.py | Python | convert_to_tensor_or_ragged_tensor | convert_to_tensor_or_ragged_tensor | 302 | 342 | 302 | 305 | 895afa08c84308c48ea685366c8fd5e43e0f59f4 | bigcode/the-stack | train |
012d2b684781aec0838891c5 | train | function | def constant(pylist, dtype=None, ragged_rank=None, inner_shape=None, name=None):
"""Constructs a constant RaggedTensor from a nested Python list.
Example:
```python
>>> ragged.constant([[1, 2], [3], [4, 5, 6]]).eval()
RaggedTensorValue(values=[1, 2, 3, 4, 5, 6], splits=[0, 2, 3, 6])
```
All scalar valu... | def constant(pylist, dtype=None, ragged_rank=None, inner_shape=None, name=None):
| """Constructs a constant RaggedTensor from a nested Python list.
Example:
```python
>>> ragged.constant([[1, 2], [3], [4, 5, 6]]).eval()
RaggedTensorValue(values=[1, 2, 3, 4, 5, 6], splits=[0, 2, 3, 6])
```
All scalar values in `pylist` must have the same nesting depth `K`, and the
returned `RaggedTe... | specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Operations for constructing RaggedTensors."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
i... | 165 | 165 | 552 | 20 | 145 | wenming2014/tensorflow | tensorflow/python/ops/ragged/ragged_factory_ops.py | Python | constant | constant | 36 | 77 | 36 | 36 | 40976d7db1e74b563a7bcfcf537155d7170b9b0e | bigcode/the-stack | train |
37fb7ca3e65361f5fc155012 | train | function | def _constant_value(ragged_factory, inner_factory, pylist, dtype, ragged_rank,
inner_shape):
"""Constructs a constant RaggedTensor or RaggedTensorValue.
Args:
ragged_factory: A factory function with the signature:
`ragged_factory(values, row_splits)`
inner_factory: A factory funct... | def _constant_value(ragged_factory, inner_factory, pylist, dtype, ragged_rank,
inner_shape):
| """Constructs a constant RaggedTensor or RaggedTensorValue.
Args:
ragged_factory: A factory function with the signature:
`ragged_factory(values, row_splits)`
inner_factory: A factory function with the signature: `inner_factory(pylist,
dtype, shape, name)`
pylist: A nested `list` or `tuple`.... | ()` if
`ragged_rank` is not specified. If `ragged_rank` is specified, then a
default is chosen based on the contents of `pylist`.
Returns:
A `RaggedTensorValue` or `numpy.array` with rank `K` and the specified
`ragged_rank`, containing the values from `pylist`.
Raises:
ValueError: If the ... | 256 | 256 | 926 | 25 | 231 | wenming2014/tensorflow | tensorflow/python/ops/ragged/ragged_factory_ops.py | Python | _constant_value | _constant_value | 134 | 227 | 134 | 135 | c4ee98903332d0a5405a6681ec93c2602e556b0f | bigcode/the-stack | train |
ad0a5e369a8c1ed529bbaafb | train | function | def from_value_rowids(values, value_rowids, nrows=None, name=None):
"""Creates a `RaggedTensor` with rows partitioned by `value_rowids`.
The returned `RaggedTensor` corresponds with the python list defined by:
```python
result = [[values[i] for i in range(len(values)) if value_rowids[i] == row]
fo... | def from_value_rowids(values, value_rowids, nrows=None, name=None):
| """Creates a `RaggedTensor` with rows partitioned by `value_rowids`.
The returned `RaggedTensor` corresponds with the python list defined by:
```python
result = [[values[i] for i in range(len(values)) if value_rowids[i] == row]
for row in range(nrows)]
```
Warning: currently, this needs to ca... | is not possible.
name: Optional name to use if a new `Tensor` is created.
Returns:
A `Tensor` or `RaggedTensor`.
"""
if isinstance(value, ragged_tensor.RaggedTensor):
if dtype and not dtype.is_compatible_with(value.dtype):
raise ValueError('Tensor conversion requested dtype %s for '
... | 255 | 256 | 1,135 | 18 | 237 | wenming2014/tensorflow | tensorflow/python/ops/ragged/ragged_factory_ops.py | Python | from_value_rowids | from_value_rowids | 350 | 444 | 350 | 350 | 703c7f7bb4da8215e1a0297ff9c1150305df25af | bigcode/the-stack | train |
f212eb51d64108909d02df1c | train | function | def constant_value(pylist, dtype=None, ragged_rank=None, inner_shape=None):
"""Constructs a RaggedTensorValue from a nested Python list.
> Warning: This function returns a `RaggedTensorValue`, not a `RaggedTensor`.
> If you wish to construct a constant `RaggedTensor`, use
> [`ragged.constant(...)`](constant.md... | def constant_value(pylist, dtype=None, ragged_rank=None, inner_shape=None):
| """Constructs a RaggedTensorValue from a nested Python list.
> Warning: This function returns a `RaggedTensorValue`, not a `RaggedTensor`.
> If you wish to construct a constant `RaggedTensor`, use
> [`ragged.constant(...)`](constant.md) instead.
Example:
```python
>>> ragged.constant_value([[1, 2], [3]... | specifying the shape for individual inner
values in the returned `RaggedTensor`. Defaults to `()` if `ragged_rank`
is not specified. If `ragged_rank` is specified, then a default is chosen
based on the contents of `pylist`.
name: A name prefix for the returned tensor (optional).
Returns:
... | 202 | 202 | 676 | 18 | 184 | wenming2014/tensorflow | tensorflow/python/ops/ragged/ragged_factory_ops.py | Python | constant_value | constant_value | 80 | 131 | 80 | 80 | f1ad178a345743edb89e957d88dfd01b2b795d15 | bigcode/the-stack | train |
b4d137a589f23325f1ddbe5c | train | function | def from_nested_row_splits(inner_values, nested_row_splits, name=None):
"""Creates a `RaggedTensor` from a nested list of `row_splits` tensors.
Equivalent to:
```python
result = inner_values
for row_splits in reversed(nested_row_splits):
result = from_row_splits(result, row_splits)
```
Args:
in... | def from_nested_row_splits(inner_values, nested_row_splits, name=None):
| """Creates a `RaggedTensor` from a nested list of `row_splits` tensors.
Equivalent to:
```python
result = inner_values
for row_splits in reversed(nested_row_splits):
result = from_row_splits(result, row_splits)
```
Args:
inner_values: A potentially ragged tensor.
nested_row_splits: A list o... | (nested_value_rowids) + list(nested_nrows)):
result = inner_values
for value_rowids, nrows in reversed(
list(zip(nested_value_rowids, nested_nrows))):
result = from_value_rowids(result, value_rowids, nrows)
return result
def from_nested_row_splits(inner_values, nested_row_splits, name=None):
| 81 | 81 | 273 | 17 | 63 | wenming2014/tensorflow | tensorflow/python/ops/ragged/ragged_factory_ops.py | Python | from_nested_row_splits | from_nested_row_splits | 651 | 678 | 651 | 651 | 84de46ef7205f95ef17720d1c43492a2213446f0 | bigcode/the-stack | train |
141ccdc5848f2a705356be46 | train | function | def _default_inner_shape_for_pylist(pylist, ragged_rank):
"""Computes a default inner shape for the given python list."""
def get_inner_shape(item):
"""Returns the inner shape for a python list `item`."""
if not isinstance(item, (list, tuple)):
return ()
elif item:
return (len(item),) + get... | def _default_inner_shape_for_pylist(pylist, ragged_rank):
| """Computes a default inner shape for the given python list."""
def get_inner_shape(item):
"""Returns the inner shape for a python list `item`."""
if not isinstance(item, (list, tuple)):
return ()
elif item:
return (len(item),) + get_inner_shape(item[0])
else:
return (0,)
def c... | _scalar_and_max_depth(child)
if child_scalar_depth is not None:
if scalar_depth is not None and scalar_depth != child_scalar_depth + 1:
raise ValueError('all scalar values must have the same nesting depth')
scalar_depth = child_scalar_depth + 1
max_depth = max(max_depth, child_max_... | 109 | 109 | 366 | 15 | 94 | wenming2014/tensorflow | tensorflow/python/ops/ragged/ragged_factory_ops.py | Python | _default_inner_shape_for_pylist | _default_inner_shape_for_pylist | 260 | 296 | 260 | 260 | 5f30d44a76722d1093445bcad5416c11583aa9eb | bigcode/the-stack | train |
2136d5437663f6ac57928407 | train | function | def from_row_starts(values, row_starts, name=None):
"""Creates a `RaggedTensor` with rows partitioned by `row_starts`.
Equivalent to: `from_row_splits(values, concat([row_starts, nvals]))`.
Args:
values: A potentially ragged tensor with shape `[nvals, ...]`.
row_starts: A 1-D int64 tensor with shape `[n... | def from_row_starts(values, row_starts, name=None):
| """Creates a `RaggedTensor` with rows partitioned by `row_starts`.
Equivalent to: `from_row_splits(values, concat([row_starts, nvals]))`.
Args:
values: A potentially ragged tensor with shape `[nvals, ...]`.
row_starts: A 1-D int64 tensor with shape `[nrows]`. Must be nonnegative
and sorted in asc... | row_lengths]):
values = convert_to_tensor_or_ragged_tensor(values, name='values')
row_lengths = ops.convert_to_tensor(row_lengths, dtypes.int64,
'row_lengths')
row_lengths.shape.assert_has_rank(1)
row_limits = math_ops.cumsum(row_lengths)
row_splits = array_o... | 128 | 128 | 427 | 14 | 114 | wenming2014/tensorflow | tensorflow/python/ops/ragged/ragged_factory_ops.py | Python | from_row_starts | from_row_starts | 533 | 565 | 533 | 533 | 62f7d17d01d45f55c7a1e748c880079d56e58c82 | bigcode/the-stack | train |
322492cc6dd5f8a51735a4a3 | train | function | def _find_scalar_and_max_depth(pylist):
"""Finds nesting depth of scalar values in pylist.
Args:
pylist: A nested python `list` or `tuple`.
Returns:
A tuple `(scalar_depth, max_depth)`. `scalar_depth` is the nesting
depth of scalar values in `pylist`, or `None` if `pylist` contains no
scalars. ... | def _find_scalar_and_max_depth(pylist):
| """Finds nesting depth of scalar values in pylist.
Args:
pylist: A nested python `list` or `tuple`.
Returns:
A tuple `(scalar_depth, max_depth)`. `scalar_depth` is the nesting
depth of scalar values in `pylist`, or `None` if `pylist` contains no
scalars. `max_depth` is the maximum depth of `py... | concatenated_values.extend(row)
values = concatenated_values
values = inner_factory(
values, dtype=dtype, shape=(len(values),) + inner_shape, name='values')
for row_splits in reversed(nested_splits):
values = ragged_factory(values, row_splits)
return values
def _find_scalar_and_max_depth(pyli... | 79 | 79 | 266 | 10 | 68 | wenming2014/tensorflow | tensorflow/python/ops/ragged/ragged_factory_ops.py | Python | _find_scalar_and_max_depth | _find_scalar_and_max_depth | 230 | 257 | 230 | 230 | 96a18e0562fae58039f309a01e1ef91dbdeff9df | bigcode/the-stack | train |
6d8e2971f1b5795f5d95506f | train | function | def from_row_limits(values, row_limits, name=None):
"""Creates a `RaggedTensor` with rows partitioned by `row_limits`.
Equivalent to: `from_row_splits(values, concat([0, row_limits]))`.
Args:
values: A potentially ragged tensor with shape `[nvals, ...]`.
row_limits: A 1-D int64 tensor with shape `[nrows... | def from_row_limits(values, row_limits, name=None):
| """Creates a `RaggedTensor` with rows partitioned by `row_limits`.
Equivalent to: `from_row_splits(values, concat([0, row_limits]))`.
Args:
values: A potentially ragged tensor with shape `[nvals, ...]`.
row_limits: A 1-D int64 tensor with shape `[nrows]`. Must be sorted in
ascending order. If `n... | _ragged_tensor(values, name='values')
row_starts = ops.convert_to_tensor(row_starts, dtypes.int64, 'row_starts')
row_starts.shape.assert_has_rank(1)
nvals = array_ops.shape(values, out_type=dtypes.int64)[:1]
row_splits = array_ops.concat([row_starts, nvals], axis=0)
return ragged_tensor.RaggedTensor... | 120 | 120 | 403 | 12 | 108 | wenming2014/tensorflow | tensorflow/python/ops/ragged/ragged_factory_ops.py | Python | from_row_limits | from_row_limits | 568 | 599 | 568 | 568 | 08e1f018fec9c19f5895ae69794b0e1217b484d9 | bigcode/the-stack | train |
e15368bd921721e0075b392d | train | function | def from_nested_value_rowids(inner_values,
nested_value_rowids,
nested_nrows=None,
name=None):
"""Creates a `RaggedTensor` from a nested list of `value_rowids` tensors.
Equivalent to:
```python
result = inner_values
for (... | def from_nested_value_rowids(inner_values,
nested_value_rowids,
nested_nrows=None,
name=None):
| """Creates a `RaggedTensor` from a nested list of `value_rowids` tensors.
Equivalent to:
```python
result = inner_values
for (value_rowids, nrows) in reversed(zip(nested_value_rowids, nested_nrows)):
result = from_value_rowids(result, value_rowids, nrows)
```
Args:
inner_values: A potentially r... | 'RaggedFromRowLimits', [values, row_limits]):
values = convert_to_tensor_or_ragged_tensor(values, name='values')
row_limits = ops.convert_to_tensor(row_limits, dtypes.int64, 'row_limits')
row_limits.shape.assert_has_rank(1)
zero = array_ops.zeros([1], dtypes.int64)
row_splits = array_ops.concat([ze... | 143 | 143 | 478 | 25 | 118 | wenming2014/tensorflow | tensorflow/python/ops/ragged/ragged_factory_ops.py | Python | from_nested_value_rowids | from_nested_value_rowids | 602 | 648 | 602 | 605 | 6c9159b205d76337b91876ce666b497d2d51ff8b | bigcode/the-stack | train |
79691080101e28e194746b9e | train | function | def from_row_lengths(values, row_lengths, name=None):
"""Creates a `RaggedTensor` with rows partitioned by `row_lengths`.
The returned `RaggedTensor` corresponds with the python list defined by:
```python
result = [[values.pop(0) for i in range(length)]
for length in row_lengths]
```
Args:
... | def from_row_lengths(values, row_lengths, name=None):
| """Creates a `RaggedTensor` with rows partitioned by `row_lengths`.
The returned `RaggedTensor` corresponds with the python list defined by:
```python
result = [[values.pop(0) for i in range(length)]
for length in row_lengths]
```
Args:
values: A potentially ragged tensor with shape `[nva... | :
raise ValueError('row_splits tensor may not be empty.')
with ops.name_scope(name, 'RaggedFromRowSplits', [values, row_splits]):
values = convert_to_tensor_or_ragged_tensor(values, name='values')
row_splits = ops.convert_to_tensor(row_splits, dtypes.int64, 'row_splits')
row_splits.shape.assert_has_ra... | 126 | 126 | 423 | 12 | 114 | wenming2014/tensorflow | tensorflow/python/ops/ragged/ragged_factory_ops.py | Python | from_row_lengths | from_row_lengths | 490 | 530 | 490 | 490 | ce7d2830f7dd112a4522994afa5d250ed127cab0 | bigcode/the-stack | train |
81f13494bd57fbb0fc8e4b79 | train | class | class VerminArgumentsTests(VerminTest):
def __init__(self, methodName):
super(VerminArgumentsTests, self).__init__(methodName)
self.config = Config.get()
def setUp(self):
self.config.reset()
def tearDown(self):
self.config.reset()
def test_not_enough_args(self):
self.assertContainsDict({"... | class VerminArgumentsTests(VerminTest):
| def __init__(self, methodName):
super(VerminArgumentsTests, self).__init__(methodName)
self.config = Config.get()
def setUp(self):
self.config.reset()
def tearDown(self):
self.config.reset()
def test_not_enough_args(self):
self.assertContainsDict({"code": 1, "usage": True}, parse_args([])... | from multiprocessing import cpu_count
from vermin import parse_args, Config
from .testutils import VerminTest
class VerminArgumentsTests(VerminTest):
| 33 | 256 | 918 | 9 | 23 | hwine/vermin | tests/arguments.py | Python | VerminArgumentsTests | VerminArgumentsTests | 7 | 90 | 7 | 7 | 75cef47f2623fee40aed3faec55f7052346eb6bd | bigcode/the-stack | train |
8b5772609489508916f6b9a7 | train | class | class TargtTypeTest(unittest.TestCase):
def setUp(self):
self.target_type = chembldb.query(TargetType).first()
def test_target_type(self):
self.assertEqual(self.target_type.target_type, "ADMET")
def test_target_desc(self):
self.assertEqual(self.target_type.target_desc, "Target is n... | class TargtTypeTest(unittest.TestCase):
| def setUp(self):
self.target_type = chembldb.query(TargetType).first()
def test_target_type(self):
self.assertEqual(self.target_type.target_type, "ADMET")
def test_target_desc(self):
self.assertEqual(self.target_type.target_desc, "Target is not applicable for an ADMET assay (e.g., ... | import unittest
from pychembldb import chembldb, TargetType
class TargtTypeTest(unittest.TestCase):
| 26 | 64 | 107 | 10 | 15 | kzfm/pychembldb | tests/test_target_type.py | Python | TargtTypeTest | TargtTypeTest | 5 | 16 | 5 | 5 | b0e33f6bb2a1488e8587905362b14e8e4fa121f9 | bigcode/the-stack | train |
a8a27b3f6b4b6f0eb47cd090 | train | class | class ticketCreation(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_reaction_add(self, ctx, user):
# WHEN A USER TRIES TO CREATE A TICKET
if ctx.message.id == modmail.on_message.setupid:
print("works")
# CREATE... | class ticketCreation(commands.Cog):
| def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_reaction_add(self, ctx, user):
# WHEN A USER TRIES TO CREATE A TICKET
if ctx.message.id == modmail.on_message.setupid:
print("works")
# CREATES THE CATEGORY NEEDED FOR MODMAIL
... | Setup Error", description = "The Channel Couldnt Be Found! Please Double Check & Rerun the Command", colour = discord.Color.blurple())
await setup1.edit(embed=errorEmbed)
await setup1.add_reaction('⛔')
cont = False
class ticketCreation(commands.Cog):
| 64 | 64 | 208 | 7 | 56 | Zyb3rWolfi/chilly | Core/Modmail/setup.py | Python | ticketCreation | ticketCreation | 69 | 94 | 69 | 69 | 150bd0b7866543b00cba8558634ca1865d646782 | bigcode/the-stack | train |
d3e126ceadfeb94ea65690e2 | train | function | def setup(bot : commands.Bot):
bot.add_cog(modmail(bot))
bot.add_cog(ticketCreation(bot)) | def setup(bot : commands.Bot):
| bot.add_cog(modmail(bot))
bot.add_cog(ticketCreation(bot)) | (
title = "Modmail Setup Part 2",
description = "The Category Has Been Succesfully Created. The Setup Is Complete",
colour = discord.Color.blurple())
await msg2.edit(embed=finished)
catID = ticketCat.id
def setup(bot : commands... | 63 | 64 | 25 | 7 | 55 | Zyb3rWolfi/chilly | Core/Modmail/setup.py | Python | setup | setup | 97 | 99 | 97 | 97 | fe3ad4f537326d191123812846dfa91218ca58ef | bigcode/the-stack | train |
02fff166fd22a41f2dd84d5f | train | class | class modmail(commands.Cog):
def __init__(self, bot):
self.bot = bot
global cont
cont = False
# COMMAND THAT ACTIVATES SETUP
@commands.command()
async def msetup(self, ctx):
embed = discord.Embed(title = "Modmail Setup Part 1", description = "Please enter the channel you want ... | class modmail(commands.Cog):
| def __init__(self, bot):
self.bot = bot
global cont
cont = False
# COMMAND THAT ACTIVATES SETUP
@commands.command()
async def msetup(self, ctx):
embed = discord.Embed(title = "Modmail Setup Part 1", description = "Please enter the channel you want the user to create a ticket..... | import nextcord
from nextcord import embeds
from nextcord.ext import commands
from nextcord.ext.commands import bot
from nextcord.ext.commands.core import command
import nextcord
import asyncio
discord = nextcord
class modmail(commands.Cog):
| 53 | 157 | 526 | 7 | 45 | Zyb3rWolfi/chilly | Core/Modmail/setup.py | Python | modmail | modmail | 11 | 67 | 11 | 11 | 24cb9455992e0c93b33be79e76fd981b9047c8f0 | bigcode/the-stack | train |
9305455a6696709107bfe135 | train | class | class BW2Package(object):
"""This is a format for saving objects which implement the :ref:`datastore` API. Data is stored as a BZip2-compressed file of JSON data. This archive format is compatible across Python versions, and is, at least in theory, programming-language agnostic.
Validation is done with ``bw2da... | class BW2Package(object):
| """This is a format for saving objects which implement the :ref:`datastore` API. Data is stored as a BZip2-compressed file of JSON data. This archive format is compatible across Python versions, and is, at least in theory, programming-language agnostic.
Validation is done with ``bw2data.validate.bw2package_val... | import os
import warnings
from time import time
from bw2data import projects
from bw2data.logs import get_logger
from bw2data.serialization import JsonSanitizer, JsonWrapper
from bw2data.utils import download_file
from bw_processing import safe_filename
from voluptuous import Invalid
from .errors import InvalidPackag... | 88 | 256 | 1,577 | 6 | 81 | sc-gcoste/brightway2-io | bw2io/package.py | Python | BW2Package | BW2Package | 16 | 205 | 16 | 16 | 89c2e35c54a57c99a18c108a9dddc3f17ea846b5 | bigcode/the-stack | train |
9ca6229c06a9975f6a113c8c | train | function | def download_methods():
logger = get_logger("io-performance.log")
start = time()
filepath = download_file("methods-new.bw2package")
logger.info("Downloading methods package: %.4g" % (time() - start))
start = time()
BW2Package.import_file(filepath)
logger.info("Importing methods package: %.4g... | def download_methods():
| logger = get_logger("io-performance.log")
start = time()
filepath = download_file("methods-new.bw2package")
logger.info("Downloading methods package: %.4g" % (time() - start))
start = time()
BW2Package.import_file(filepath)
logger.info("Importing methods package: %.4g" % (time() - start))
| -new.bw2package")
logger.info("Downloading biosphere package: %.4g" % (time() - start))
start = time()
BW2Package.import_file(filepath)
logger.info("Importing biosphere package: %.4g" % (time() - start))
def download_methods():
| 64 | 64 | 84 | 4 | 60 | sc-gcoste/brightway2-io | bw2io/package.py | Python | download_methods | download_methods | 218 | 225 | 218 | 218 | a44e4260d0746dc67bee187a5791d60e0f4a38be | bigcode/the-stack | train |
ad900772baf6cf5475d97e48 | train | function | def download_biosphere():
logger = get_logger("io-performance.log")
start = time()
filepath = download_file("biosphere-new.bw2package")
logger.info("Downloading biosphere package: %.4g" % (time() - start))
start = time()
BW2Package.import_file(filepath)
logger.info("Importing biosphere packa... | def download_biosphere():
| logger = get_logger("io-performance.log")
start = time()
filepath = download_file("biosphere-new.bw2package")
logger.info("Downloading biosphere package: %.4g" % (time() - start))
start = time()
BW2Package.import_file(filepath)
logger.info("Importing biosphere package: %.4g" % (time() - star... | loaded = cls.load_file(filepath, whitelist)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
if isinstance(loaded, dict):
return cls._create_obj(loaded)
else:
return [cls._create_obj(o) for o in loaded]
def download_biosp... | 64 | 64 | 89 | 6 | 58 | sc-gcoste/brightway2-io | bw2io/package.py | Python | download_biosphere | download_biosphere | 208 | 215 | 208 | 208 | aed01c2375c9c3fab6db10b9cf4ee320f6bd6ad4 | bigcode/the-stack | train |
56ab35d485b2a5a6c391f4e6 | train | class | class TestAuthorize(ProviderBaseMixin, unittest.TestCase):
@mock.patch('edenred.provider.APIProvider.request_resource')
def test_authorize(self, request_resource):
card_token = mock.Mock(spec=str)
description = mock.Mock(spec=str)
amount = mock.Mock(spec=int)
expected_payload =... | class TestAuthorize(ProviderBaseMixin, unittest.TestCase):
@mock.patch('edenred.provider.APIProvider.request_resource')
| def test_authorize(self, request_resource):
card_token = mock.Mock(spec=str)
description = mock.Mock(spec=str)
amount = mock.Mock(spec=int)
expected_payload = {
"Authorize": {
"CardToken": card_token,
"Amount": amount,
"Des... | amount=amount
)
self.assertEqual(request_resource.return_value['Capture'], result)
request_resource.assert_called_once_with(action='Capture', resource='Payment', payload=expected_payload)
class TestAuthorize(ProviderBaseMixin, unittest.TestCase):
@mock.patch('edenred.provider.APIProvider.r... | 64 | 64 | 199 | 25 | 39 | cornershop/python-edenred-payments | tests/test_provider.py | Python | TestAuthorize | TestAuthorize | 373 | 403 | 373 | 375 | f7a9586422e0e85d40a7de560cb4bef2ae1014be | bigcode/the-stack | train |
ea4e8b35612c67232e377c9a | train | class | class TestPay(ProviderBaseMixin, unittest.TestCase):
@mock.patch('edenred.provider.APIProvider.request_resource')
def test_pay(self, request_resource):
card_token = mock.Mock(spec=str)
description = mock.Mock(spec=str)
amount = mock.Mock(spec=int)
expected_payload = {
... | class TestPay(ProviderBaseMixin, unittest.TestCase):
@mock.patch('edenred.provider.APIProvider.request_resource')
| def test_pay(self, request_resource):
card_token = mock.Mock(spec=str)
description = mock.Mock(spec=str)
amount = mock.Mock(spec=int)
expected_payload = {
"Pay": {
"CardToken": card_token,
"Amount": amount,
"Description": d... | description=description
)
self.assertEqual(request_resource.return_value['Authorize'], result)
request_resource.assert_called_once_with(action='Authorize', resource='Payment', payload=expected_payload)
class TestPay(ProviderBaseMixin, unittest.TestCase):
@mock.patch('edenred.provider.APIPr... | 64 | 64 | 197 | 25 | 39 | cornershop/python-edenred-payments | tests/test_provider.py | Python | TestPay | TestPay | 406 | 436 | 406 | 408 | dd4bfaf2b5319580924e1b096b87d92f807ad425 | bigcode/the-stack | train |
6be5f7c9140e8d41e93b6150 | train | class | class TestCreatePaymentMethod(ProviderBaseMixin, unittest.TestCase):
@mock.patch('edenred.provider.APIProvider.request_resource')
def test_create_payment_method(self, request_resource):
card_number = mock.Mock(spec=str)
cvv = mock.Mock(spec=str)
expiration_month = mock.Mock(spec=str)
... | class TestCreatePaymentMethod(ProviderBaseMixin, unittest.TestCase):
@mock.patch('edenred.provider.APIProvider.request_resource')
| def test_create_payment_method(self, request_resource):
card_number = mock.Mock(spec=str)
cvv = mock.Mock(spec=str)
expiration_month = mock.Mock(spec=str)
expiration_year = mock.Mock(spec=str)
encrypted = {
card_number: mock.Mock(spec=str),
cvv: mock.M... | _response(response)
def test_validate_invalid_errors(self):
response = self.create_response({
'Success': False,
"ErrorList": [
{'Code': "ER104", 'Message': "Error 104"},
{'Code': "ER101", 'Message': "Error 101"},
]
})
with... | 108 | 108 | 360 | 27 | 81 | cornershop/python-edenred-payments | tests/test_provider.py | Python | TestCreatePaymentMethod | TestCreatePaymentMethod | 284 | 334 | 284 | 286 | 7a4db40506a08d7a490f2bb7add1fcc3282336b5 | bigcode/the-stack | train |
c0a727a5a4672d6985f27d59 | train | class | class TestAPIProvider(unittest.TestCase):
def test_init(self):
public_key = mock.Mock(spec=PublicKey)
base_url = mock.Mock(spec=str)
client_id = mock.Mock(spec=str)
client_secret = mock.Mock(spec=str)
access_token = mock.Mock(spec=str)
provider = APIProvider(
... | class TestAPIProvider(unittest.TestCase):
| def test_init(self):
public_key = mock.Mock(spec=PublicKey)
base_url = mock.Mock(spec=str)
client_id = mock.Mock(spec=str)
client_secret = mock.Mock(spec=str)
access_token = mock.Mock(spec=str)
provider = APIProvider(
client_id=client_id,
clien... |
import unittest
try:
from unitttest import mock
except ImportError:
import mock
import requests.exceptions
from edenred.provider import APIProvider
from edenred.publickey import PublicKey
from edenred.exceptions import APIError, TransactionErrors, Unauthorized
class TestAPIProvider(unittest.TestCase):
| 64 | 256 | 971 | 8 | 55 | cornershop/python-edenred-payments | tests/test_provider.py | Python | TestAPIProvider | TestAPIProvider | 15 | 141 | 15 | 16 | eb9f2ee8d75a45a14fc429cbcdded486d2c4243f | bigcode/the-stack | train |
2e096fba4b9304881df59592 | train | class | class TestDoRequest(unittest.TestCase):
@mock.patch('edenred.provider.requests')
def test_do_request(self, requests):
payload = mock.Mock(spec=dict)
headers = mock.Mock(spec=dict)
url = mock.Mock(spec=str)
response = requests.post.return_value
result = APIProvider.do_re... | class TestDoRequest(unittest.TestCase):
@mock.patch('edenred.provider.requests')
| def test_do_request(self, requests):
payload = mock.Mock(spec=dict)
headers = mock.Mock(spec=dict)
url = mock.Mock(spec=str)
response = requests.post.return_value
result = APIProvider.do_request(url=url, headers=headers, payload=payload)
self.assertEqual(requests.po... | .return_value,
payload=payload,
headers={'Content-Type': 'application/json; charset=utf-8'}
)
get_endpoint_url.assert_called_once_with(resource=None, action='Login', base_url=base_url)
class TestDoRequest(unittest.TestCase):
@mock.patch('edenred.provider.requests')
| 64 | 64 | 210 | 18 | 46 | cornershop/python-edenred-payments | tests/test_provider.py | Python | TestDoRequest | TestDoRequest | 144 | 168 | 144 | 146 | b3817d35a6d0bc12c9f7e4fdc75521e782b21f93 | bigcode/the-stack | train |
01536475d081ddf289779eb9 | train | class | class TestRequestResource(ProviderBaseMixin, unittest.TestCase):
@mock.patch('edenred.provider.APIProvider.do_request')
@mock.patch('edenred.provider.APIProvider.get_endpoint_url')
@mock.patch('edenred.provider.APIProvider._get_headers')
def test_request_resource(self, _get_headers, get_endpoint_url, d... | class TestRequestResource(ProviderBaseMixin, unittest.TestCase):
@mock.patch('edenred.provider.APIProvider.do_request')
@mock.patch('edenred.provider.APIProvider.get_endpoint_url')
@mock.patch('edenred.provider.APIProvider._get_headers')
| def test_request_resource(self, _get_headers, get_endpoint_url, do_request):
resource = mock.Mock(spec=str)
payload = mock.Mock(spec=dict)
action = mock.Mock(spec=str)
do_request.return_value = {'Success': True}
result = self.provider.request_resource(resource=resource, acti... | Provider.do_request(url=url, headers=headers, payload=payload)
class ProviderBaseMixin(object):
def create_provider(self, access_token=None):
public_key = mock.Mock(spec=PublicKey)
base_url = mock.Mock(spec=str)
client_id = mock.Mock(spec=str)
client_secret = mock.Mock(spec=str)
... | 180 | 180 | 600 | 54 | 126 | cornershop/python-edenred-payments | tests/test_provider.py | Python | TestRequestResource | TestRequestResource | 186 | 244 | 186 | 190 | fe07f430b91d4e0da96382a503ce27ec82525e25 | bigcode/the-stack | train |
e1859e76ff61e648be2839ce | train | class | class TestCapture(ProviderBaseMixin, unittest.TestCase):
@mock.patch('edenred.provider.APIProvider.request_resource')
def test_capture(self, request_resource):
card_token = mock.Mock(spec=str)
authorize_identifier = mock.Mock(spec=str)
description = mock.Mock(spec=str)
amount = ... | class TestCapture(ProviderBaseMixin, unittest.TestCase):
@mock.patch('edenred.provider.APIProvider.request_resource')
| def test_capture(self, request_resource):
card_token = mock.Mock(spec=str)
authorize_identifier = mock.Mock(spec=str)
description = mock.Mock(spec=str)
amount = mock.Mock(spec=int)
expected_payload = {
"Capture": {
"CardToken": card_token,
... | )
self.assertEqual(request_resource.return_value['PaymentMethod'], result)
request_resource.assert_called_once_with(
resource='PaymentMethod', action='Create', payload=expected_payload
)
class TestCapture(ProviderBaseMixin, unittest.TestCase):
@mock.patch('edenred.provid... | 66 | 66 | 221 | 25 | 41 | cornershop/python-edenred-payments | tests/test_provider.py | Python | TestCapture | TestCapture | 337 | 370 | 337 | 339 | aee35ee27714c12bbe4aa560ff1b3a6a51757723 | bigcode/the-stack | train |
61bdf02e1003ba2b81253d55 | train | class | class TestValidateResponses(unittest.TestCase):
def create_response(self, data, status_code=200):
response = mock.Mock()
response.json.return_value = data
response.status_code = status_code
return data
def test_validate_valid_response(self):
response = self.create_respon... | class TestValidateResponses(unittest.TestCase):
| def create_response(self, data, status_code=200):
response = mock.Mock()
response.json.return_value = data
response.status_code = status_code
return data
def test_validate_valid_response(self):
response = self.create_response({'Success': True, "ErrorList": None})
... | _request, validate_response):
validate_response.side_effect = TransactionErrors({}, [])
resource = mock.Mock(spec=str)
action = mock.Mock(spec=str)
payload = mock.Mock(spec=dict)
with self.assertRaises(TransactionErrors):
self.provider.request_resource(resource=resou... | 72 | 72 | 243 | 8 | 64 | cornershop/python-edenred-payments | tests/test_provider.py | Python | TestValidateResponses | TestValidateResponses | 247 | 281 | 247 | 247 | 097e7178abc20e0f4dd797c60bafc2e292c1118b | bigcode/the-stack | train |
421a3f5c1c84265fe0a0ee7a | train | class | class TestRefund(ProviderBaseMixin, unittest.TestCase):
@mock.patch('edenred.provider.APIProvider.request_resource')
def test_refund(self, request_resource):
card_token = mock.Mock(spec=str)
payment_identifier = mock.Mock(spec=str)
resource = 'Payment/{}'.format(payment_identifier)
... | class TestRefund(ProviderBaseMixin, unittest.TestCase):
@mock.patch('edenred.provider.APIProvider.request_resource')
| def test_refund(self, request_resource):
card_token = mock.Mock(spec=str)
payment_identifier = mock.Mock(spec=str)
resource = 'Payment/{}'.format(payment_identifier)
description = mock.Mock(spec=str)
amount = mock.Mock(spec=int)
expected_payload = {
"Pay"... | description=description
)
self.assertEqual(request_resource.return_value['Pay'], result)
request_resource.assert_called_once_with(action='Pay', resource='Payment', payload=expected_payload)
class TestRefund(ProviderBaseMixin, unittest.TestCase):
@mock.patch('edenred.provider.API... | 65 | 65 | 219 | 25 | 40 | cornershop/python-edenred-payments | tests/test_provider.py | Python | TestRefund | TestRefund | 439 | 471 | 439 | 441 | 6dc1322953313992f1da431040e932b352ec244b | bigcode/the-stack | train |
631b84f4c1d23bed085f7218 | train | class | class ProviderBaseMixin(object):
def create_provider(self, access_token=None):
public_key = mock.Mock(spec=PublicKey)
base_url = mock.Mock(spec=str)
client_id = mock.Mock(spec=str)
client_secret = mock.Mock(spec=str)
return APIProvider(
client_id=client_id, client... | class ProviderBaseMixin(object):
| def create_provider(self, access_token=None):
public_key = mock.Mock(spec=PublicKey)
base_url = mock.Mock(spec=str)
client_id = mock.Mock(spec=str)
client_secret = mock.Mock(spec=str)
return APIProvider(
client_id=client_id, client_secret=client_secret, base_url=b... | .Mock(spec=dict)
url = mock.Mock(spec=str)
response = requests_post.return_value
response.raise_for_status.side_effect = requests.exceptions.HTTPError(response=response)
with self.assertRaises(APIError):
APIProvider.do_request(url=url, headers=headers, payload=payload)
class... | 64 | 64 | 113 | 6 | 58 | cornershop/python-edenred-payments | tests/test_provider.py | Python | ProviderBaseMixin | ProviderBaseMixin | 171 | 183 | 171 | 171 | e9870c547c2dd9fac425a920eeebff49536d51f6 | bigcode/the-stack | train |
a452545ab18f15a3f7f8650a | train | function | def get_data_path(datafile):
"""
:param datafile: the file name of a file in the alaska.data module
:return: PosixPath() object containing the full path to the datafile
Build and return a path object for the input datafile
Example: get_data_path("my_wonderful.csv")
"""
with pkg_resources.p... | def get_data_path(datafile):
| """
:param datafile: the file name of a file in the alaska.data module
:return: PosixPath() object containing the full path to the datafile
Build and return a path object for the input datafile
Example: get_data_path("my_wonderful.csv")
"""
with pkg_resources.path(data, datafile) as mypath... | /except can be
# changed to simply `import importlib.resources as pkg_resources`
try:
import importlib.resources as pkg_resources
except ImportError:
# Try backported to PY<37 `importlib_resources`.
import importlib_resources as pkg_resources
def get_data_path(datafile):
| 64 | 64 | 92 | 7 | 56 | FRI-Energy-Analytics/AlasKA | alaska/get_data_path.py | Python | get_data_path | get_data_path | 22 | 32 | 22 | 22 | c865d3663cd8fd78dff5081a20f4ca2b9f38a5e0 | bigcode/the-stack | train |
939fd27b4328906cfcc3eae8 | train | class | class colors:
reset = '\033[0m'
bold = '\033[01m'
disable = '\033[02m'
underline = '\033[04m'
reverse = '\033[07m'
strikethrough = '\033[09m'
invisible = '\033[08m'
class fg:
black = '\033[30m'
red = '\033[31m'
green = '\033[32m'
orange = '\033[33m'
... | class colors:
| reset = '\033[0m'
bold = '\033[01m'
disable = '\033[02m'
underline = '\033[04m'
reverse = '\033[07m'
strikethrough = '\033[09m'
invisible = '\033[08m'
class fg:
black = '\033[30m'
red = '\033[31m'
green = '\033[32m'
orange = '\033[33m'
blue = '\03... | class colors:
| 3 | 87 | 291 | 3 | 0 | alxrsngrtn/simple-coinbase-bot | simplecoinbasebot/color.py | Python | colors | colors | 2 | 36 | 2 | 2 | 632a4f36923b7dad7dbd492a70e3e15a395677d4 | bigcode/the-stack | train |
85b8afd1b00519ac5b7b15f1 | train | class | class Migration(migrations.Migration):
dependencies = [
('piaf', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='article',
name='name',
field=models.CharField(max_length=200),
),
]
| class Migration(migrations.Migration):
| dependencies = [
('piaf', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='article',
name='name',
field=models.CharField(max_length=200),
),
]
| # Generated by Django 2.1 on 2019-10-17 22:44
from django.db import migrations, models
class Migration(migrations.Migration):
| 36 | 64 | 57 | 7 | 28 | powoka/piaf | src/piaf/migrations/0002_auto_20191017_2244.py | Python | Migration | Migration | 6 | 18 | 6 | 7 | d0aecf29f443d576a0450a981f462057550096b3 | bigcode/the-stack | train |
5b02c8125bcf0d018e927b66 | train | class | class VideoUrlStatusManager(models.Manager):
def create_for_video(self, video):
"""Create VideoUrlStatus objects for each failed url in a video
:return: The number of VidoeUrlStatuses created
"""
def check_urls(urls):
for url in urls:
try:
... | class VideoUrlStatusManager(models.Manager):
| def create_for_video(self, video):
"""Create VideoUrlStatus objects for each failed url in a video
:return: The number of VidoeUrlStatuses created
"""
def check_urls(urls):
for url in urls:
try:
r = requests.head(url)
... | return self.url
def __repr__(self):
return '<URL %s>' % self.url
def display(self):
"""For showing the url
This reduces long urls to 50 characters for display.
"""
return self.url[:50]
class VideoUrlStatusManager(models.Manager):
| 64 | 64 | 193 | 8 | 56 | codersquid/richard | src/richard/videos/models.py | Python | VideoUrlStatusManager | VideoUrlStatusManager | 387 | 413 | 387 | 387 | 4d054e98ff514581a79f08eb6a8226513bea4624 | bigcode/the-stack | train |
3cfce74188f375170ff143c6 | train | class | @python_2_unicode_compatible
class Tag(models.Model):
tag = models.CharField(max_length=30)
def __str__(self):
return self.tag
def __repr__(self):
return '<Tag %s>' % self.tag.encode('ascii', 'ignore')
class Meta(object):
ordering = ['tag']
verbose_name = _(u'tag')
... | @python_2_unicode_compatible
class Tag(models.Model):
| tag = models.CharField(max_length=30)
def __str__(self):
return self.tag
def __repr__(self):
return '<Tag %s>' % self.tag.encode('ascii', 'ignore')
class Meta(object):
ordering = ['tag']
verbose_name = _(u'tag')
verbose_name_plural = _(u'tags')
| = ['name']
verbose_name = _(u'speaker')
verbose_name_plural = _(u'speakers')
@models.permalink
def get_absolute_url(self):
return ('videos-speaker', (self.pk, self.slug))
@python_2_unicode_compatible
class Tag(models.Model):
| 64 | 64 | 90 | 13 | 51 | codersquid/richard | src/richard/videos/models.py | Python | Tag | Tag | 123 | 136 | 123 | 124 | d90cc18a820a4b5eaf37c5898339162a373c13b8 | bigcode/the-stack | train |
e8bf31daeebd9d44947c2bf3 | train | class | @python_2_unicode_compatible
class Language(models.Model):
iso639_1 = models.CharField(max_length=3)
name = models.CharField(max_length=20)
def __str__(self):
return self.name
| @python_2_unicode_compatible
class Language(models.Model):
| iso639_1 = models.CharField(max_length=3)
name = models.CharField(max_length=20)
def __str__(self):
return self.name
| repr__(self):
return '<Tag %s>' % self.tag.encode('ascii', 'ignore')
class Meta(object):
ordering = ['tag']
verbose_name = _(u'tag')
verbose_name_plural = _(u'tags')
@python_2_unicode_compatible
class Language(models.Model):
| 64 | 64 | 50 | 13 | 51 | codersquid/richard | src/richard/videos/models.py | Python | Language | Language | 139 | 145 | 139 | 140 | ec62229801769452911c8b50bd84bdfaeee6b4ec | bigcode/the-stack | train |
2a42dec054fe2f8f1da88630 | train | class | @python_2_unicode_compatible
class Video(models.Model):
STATE_LIVE = 1
STATE_DRAFT = 2
STATE_CHOICES = (
(STATE_LIVE, u'Live'),
(STATE_DRAFT, u'Draft'),
)
LOCAL_THUMBNAIL_PATH = 'video/thumbnails/%d.jpg'
state = models.IntegerField(choices=STATE_CHOICES, default=STATE_DRAF... | @python_2_unicode_compatible
class Video(models.Model):
| STATE_LIVE = 1
STATE_DRAFT = 2
STATE_CHOICES = (
(STATE_LIVE, u'Live'),
(STATE_DRAFT, u'Draft'),
)
LOCAL_THUMBNAIL_PATH = 'video/thumbnails/%d.jpg'
state = models.IntegerField(choices=STATE_CHOICES, default=STATE_DRAFT)
title = models.CharField(max_length=255)
sum... | )
class Meta(object):
ordering = ['name']
verbose_name = _(u'speaker')
verbose_name_plural = _(u'speakers')
@models.permalink
def get_absolute_url(self):
return ('videos-speaker', (self.pk, self.slug))
@python_2_unicode_compatible
class Tag(models.Model):
tag = models... | 256 | 256 | 1,623 | 13 | 243 | codersquid/richard | src/richard/videos/models.py | Python | Video | Video | 156 | 363 | 156 | 157 | b7f761706845eae9e42b5b9e2c53eaa77a015cc9 | bigcode/the-stack | train |
a1973619a53a76f6f3471770 | train | class | class ShrodingersSlugRelatedField(serializers.SlugRelatedField):
"""Less fussy SlugRelatedField
It's just like SlugRelatedField, but allows for the object not to
exist. If it doesn't exist, then it'll get created.
"""
def from_native(self, data):
data = data.strip()
if self.queryse... | class ShrodingersSlugRelatedField(serializers.SlugRelatedField):
| """Less fussy SlugRelatedField
It's just like SlugRelatedField, but allows for the object not to
exist. If it doesn't exist, then it'll get created.
"""
def from_native(self, data):
data = data.strip()
if self.queryset is None:
raise Exception('Need "queryset" argument'... | yperlinkedRelatedField(
many=True,
view_name='video-api-view'
)
class Meta:
model = Category
lookup_field = 'slug'
class SpeakerSerializer(serializers.ModelSerializer):
class Meta:
model = Speaker
class ShrodingersSlugRelatedField(serializers.SlugRelatedField):
| 64 | 64 | 159 | 13 | 50 | codersquid/richard | src/richard/videos/models.py | Python | ShrodingersSlugRelatedField | ShrodingersSlugRelatedField | 442 | 461 | 442 | 442 | bce9374024db1f02b360a53c6f9e263c16a350d2 | bigcode/the-stack | train |
2508e880f26c7a724c08dfb2 | train | class | class CategorySerializer(serializers.HyperlinkedModelSerializer):
videos = serializers.HyperlinkedRelatedField(
many=True,
view_name='video-api-view'
)
class Meta:
model = Category
lookup_field = 'slug'
| class CategorySerializer(serializers.HyperlinkedModelSerializer):
| videos = serializers.HyperlinkedRelatedField(
many=True,
view_name='video-api-view'
)
class Meta:
model = Category
lookup_field = 'slug'
| _code = models.IntegerField(null=False, blank=False)
status_message = models.CharField(max_length=255, null=False, blank=True)
url = models.URLField(max_length=255, null=False, blank=False)
video = models.ForeignKey(Video)
class CategorySerializer(serializers.HyperlinkedModelSerializer):
| 64 | 64 | 50 | 10 | 54 | codersquid/richard | src/richard/videos/models.py | Python | CategorySerializer | CategorySerializer | 426 | 434 | 426 | 426 | d9660469d95c51b947e0370a2f96d035b129ecb5 | bigcode/the-stack | train |
a93741f78cc1d15b64eca334 | train | class | class VideoUrlStatus(models.Model):
objects = VideoUrlStatusManager()
check_date = models.DateTimeField(null=False, blank=False)
status_code = models.IntegerField(null=False, blank=False)
status_message = models.CharField(max_length=255, null=False, blank=True)
url = models.URLField(max_length=255,... | class VideoUrlStatus(models.Model):
| objects = VideoUrlStatusManager()
check_date = models.DateTimeField(null=False, blank=False)
status_code = models.IntegerField(null=False, blank=False)
status_message = models.CharField(max_length=255, null=False, blank=True)
url = models.URLField(max_length=255, null=False, blank=False)
video ... | status_code=status_code,
status_message=status_message)
for url, status_code, status_message in check_urls(video.all_urls)
]
if video_url_status:
self.bulk_create(video_url_status)
return collections.Counter(video.status_code for video in video_url_status... | 64 | 64 | 85 | 7 | 57 | codersquid/richard | src/richard/videos/models.py | Python | VideoUrlStatus | VideoUrlStatus | 416 | 423 | 416 | 416 | b40baedce927eec5200b95c45c2dec002dbd9909 | bigcode/the-stack | train |
f32a31079e2c75ebc9717279 | train | class | @python_2_unicode_compatible
class Category(models.Model):
title = models.CharField(
max_length=255,
help_text=_(u'The complete title for the category. e.g. '
u'PyCon 2010'))
description = models.TextField(
blank=True, default=u'',
help_text=USE_MARKDOWN_HELP_... | @python_2_unicode_compatible
class Category(models.Model):
| title = models.CharField(
max_length=255,
help_text=_(u'The complete title for the category. e.g. '
u'PyCon 2010'))
description = models.TextField(
blank=True, default=u'',
help_text=USE_MARKDOWN_HELP_TEXT)
url = models.URLField(
blank=True, defaul... | models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from richard.videos.utils import generate_unique_slug
MIMETYPES_MAP = {
'ogv': 'video/ogg',
'mp4': 'video/mp4',
'webm': 'video/webm',
'... | 116 | 116 | 389 | 13 | 103 | codersquid/richard | src/richard/videos/models.py | Python | Category | Category | 47 | 93 | 47 | 48 | f673d0d922b816d57cb1716838cd65093ca7dbde | bigcode/the-stack | train |
0ff598d1a0a8ade1405f9fa5 | train | class | class VideoSerializer(serializers.ModelSerializer):
category = serializers.SlugRelatedField(many=False, slug_field='title')
language = serializers.SlugRelatedField(
many=False, required=False, slug_field='name')
slug = serializers.SlugField(read_only=True)
# These are a little funky since we de... | class VideoSerializer(serializers.ModelSerializer):
| category = serializers.SlugRelatedField(many=False, slug_field='title')
language = serializers.SlugRelatedField(
many=False, required=False, slug_field='name')
slug = serializers.SlugField(read_only=True)
# These are a little funky since we denormalize them for the API.
speakers = Shrodinge... | : data})
except ObjectDoesNotExist:
obj = self.queryset.model(**{self.slug_field: data})
obj.save()
return obj
except (TypeError, ValueError):
msg = self.error_messages['invalid']
raise ValidationError(msg)
class VideoSerializer(serializers.Mod... | 64 | 64 | 118 | 7 | 57 | codersquid/richard | src/richard/videos/models.py | Python | VideoSerializer | VideoSerializer | 464 | 475 | 464 | 464 | cf002d758a0b7e78a13e1c4f3a02787d003a2f1b | bigcode/the-stack | train |
75a68e21f3ff9e192f6ccb4d | train | class | class SpeakerSerializer(serializers.ModelSerializer):
class Meta:
model = Speaker
| class SpeakerSerializer(serializers.ModelSerializer):
| class Meta:
model = Speaker
| video = models.ForeignKey(Video)
class CategorySerializer(serializers.HyperlinkedModelSerializer):
videos = serializers.HyperlinkedRelatedField(
many=True,
view_name='video-api-view'
)
class Meta:
model = Category
lookup_field = 'slug'
class SpeakerSerializer(serializers.... | 64 | 64 | 16 | 7 | 57 | codersquid/richard | src/richard/videos/models.py | Python | SpeakerSerializer | SpeakerSerializer | 437 | 439 | 437 | 437 | 505d22614d8780682fbfd2c156366294b4e5cf87 | bigcode/the-stack | train |
7201134f72f195df58536c50 | train | class | class VideoManager(models.Manager):
def live(self):
return self.get_query_set().filter(state=Video.STATE_LIVE)
def live_order_by_title(self):
return self.live().order_by('title')
| class VideoManager(models.Manager):
| def live(self):
return self.get_query_set().filter(state=Video.STATE_LIVE)
def live_order_by_title(self):
return self.live().order_by('title')
| _name_plural = _(u'tags')
@python_2_unicode_compatible
class Language(models.Model):
iso639_1 = models.CharField(max_length=3)
name = models.CharField(max_length=20)
def __str__(self):
return self.name
class VideoManager(models.Manager):
| 64 | 64 | 44 | 6 | 57 | codersquid/richard | src/richard/videos/models.py | Python | VideoManager | VideoManager | 148 | 153 | 148 | 148 | 43332ac716bc7c68569a1c5287522fc5376b26f3 | bigcode/the-stack | train |
71bef15da39d9a83d0f6d863 | train | class | @python_2_unicode_compatible
class Speaker(models.Model):
name = models.CharField(max_length=255)
slug = models.SlugField(unique=True)
def __str__(self):
return self.name
def __repr__(self):
return '<Speaker %s: %s>' % (
self.id, self.name.encode('ascii', 'ignore'))
de... | @python_2_unicode_compatible
class Speaker(models.Model):
| name = models.CharField(max_length=255)
slug = models.SlugField(unique=True)
def __str__(self):
return self.name
def __repr__(self):
return '<Speaker %s: %s>' % (
self.id, self.name.encode('ascii', 'ignore'))
def save(self, *args, **kwargs):
if not self.slug:
... | ordering = ["title"]
verbose_name = _(u'category')
verbose_name_plural = _(u'categories')
@models.permalink
def get_absolute_url(self):
return ('videos-category', (self.pk, self.slug))
@python_2_unicode_compatible
class Speaker(models.Model):
| 64 | 64 | 183 | 13 | 51 | codersquid/richard | src/richard/videos/models.py | Python | Speaker | Speaker | 96 | 120 | 96 | 97 | 64975c0d85ee31f620fc3758c60c65431e44e11e | bigcode/the-stack | train |
739885af821b4805327c29fe | train | class | @python_2_unicode_compatible
class RelatedUrl(models.Model):
video = models.ForeignKey(Video, related_name='related_urls')
url = models.URLField(max_length=255)
description = models.CharField(max_length=255, blank=True, default=u'')
def __str__(self):
return self.url
def __repr__(self):
... | @python_2_unicode_compatible
class RelatedUrl(models.Model):
| video = models.ForeignKey(Video, related_name='related_urls')
url = models.URLField(max_length=255)
description = models.CharField(max_length=255, blank=True, default=u'')
def __str__(self):
return self.url
def __repr__(self):
return '<URL %s>' % self.url
def display(self):
... | ,
self.video_ogv_url,
self.video_mp4_url,
self.video_webm_url,
self.video_flv_url,
self.source_url,
]
if url is not None and url != ''
]
@python_2_unicode_compatible
class RelatedU... | 63 | 64 | 120 | 14 | 49 | codersquid/richard | src/richard/videos/models.py | Python | RelatedUrl | RelatedUrl | 366 | 384 | 366 | 367 | 03589f8db3a8c5a2531cdc02adf1f01797924761 | bigcode/the-stack | train |
0ce2f181714332e790ea324a | train | class | class UUIDGenerator(object):
def __init__(self, base = 0):
self._base = base
def next(self):
value = self._base
self._base += 1
return value
| class UUIDGenerator(object):
| def __init__(self, base = 0):
self._base = base
def next(self):
value = self._base
self._base += 1
return value
| class UUIDGenerator(object):
| 5 | 64 | 48 | 5 | 0 | MD-Studio/MDStudio_topology | mdstudio_topology/core/uuid.py | Python | UUIDGenerator | UUIDGenerator | 1 | 10 | 1 | 2 | f0bbed698b1cff26b5e97fc9c795b218057e057e | bigcode/the-stack | train |
ee165cb64488283520ebf94d | train | function | def is_port_in_use(port):
import socket, errno
result = False
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.bind(('localhost', port))
except socket.error as e:
if e.errno == errno.EADDRINUSE:
result = True
else:
# something else raised t... | def is_port_in_use(port):
| import socket, errno
result = False
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.bind(('localhost', port))
except socket.error as e:
if e.errno == errno.EADDRINUSE:
result = True
else:
# something else raised the socket.error exception
... | buff.value = name
libc.prctl(15, byref(buff), 0, 0, 0)
except Exception:
try:
import setproctitle
setproctitle.setproctitle(name)
except Exception:
pass
def is_port_in_use(port):
| 64 | 64 | 92 | 7 | 56 | tkazik/multimaster_fkie | fkie_master_discovery/src/fkie_master_discovery/__init__.py | Python | is_port_in_use | is_port_in_use | 96 | 109 | 96 | 96 | da657befb46e36b8d50ca5c5c9b74f5f115b04b9 | bigcode/the-stack | train |
b4431770666a9b3dcf2d380c | train | function | def set_terminal_name(name):
'''
Change the terminal name.
@param name: New name of the terminal
@type name: str
'''
sys.stdout.write("\x1b]2;%s\x07" % name)
| def set_terminal_name(name):
| '''
Change the terminal name.
@param name: New name of the terminal
@type name: str
'''
sys.stdout.write("\x1b]2;%s\x07" % name)
| ("ROS Master URI: %s", masteruri)
return urlparse(masteruri).port + (600 if zeroconf else 300)
except:
import traceback
print(traceback.format_exc())
return 11911 if zeroconf else 11611
def set_terminal_name(name):
| 64 | 64 | 53 | 6 | 57 | tkazik/multimaster_fkie | fkie_master_discovery/src/fkie_master_discovery/__init__.py | Python | set_terminal_name | set_terminal_name | 67 | 73 | 67 | 67 | 5694bbea78ea25d0f06330cb4c20b623ec4b54a4 | bigcode/the-stack | train |
fbc28728c78ed88ec3b6c9e5 | train | function | def get_default_rtcp_port(zeroconf=False):
try:
from fkie_master_discovery.common import masteruri_from_ros
masteruri = masteruri_from_ros()
# rospy.loginfo("ROS Master URI: %s", masteruri)
return urlparse(masteruri).port + (600 if zeroconf else 300)
except:
import traceb... | def get_default_rtcp_port(zeroconf=False):
| try:
from fkie_master_discovery.common import masteruri_from_ros
masteruri = masteruri_from_ros()
# rospy.loginfo("ROS Master URI: %s", masteruri)
return urlparse(masteruri).port + (600 if zeroconf else 300)
except:
import traceback
print(traceback.format_exc())
... | # MCAST_GROUP = "ff02::1"# ipv6 multicast group
MCAST_GROUP = "226.0.0.0" # ipv4 multicast group
MCAST_PORT = 11511
PROCESS_NAME = "master_discovery"
def get_default_rtcp_port(zeroconf=False):
| 64 | 64 | 101 | 12 | 52 | tkazik/multimaster_fkie | fkie_master_discovery/src/fkie_master_discovery/__init__.py | Python | get_default_rtcp_port | get_default_rtcp_port | 55 | 64 | 55 | 55 | 30512fc0a7875dc8f2aaa5139cc0a23231885cae | bigcode/the-stack | train |
16a5ae6c27c62f742d75f8be | train | function | def main_zeroconf():
'''
Creates and runs the ROS node using zeroconf/avahi for discovering
'''
import fkie_master_discovery.zeroconf as zeroconf
PROCESS_NAME = "zeroconf"
wait_for_free_port()
# setup the loglevel
try:
log_level = getattr(rospy, rospy.get_param('/%s/log_level' % ... | def main_zeroconf():
| '''
Creates and runs the ROS node using zeroconf/avahi for discovering
'''
import fkie_master_discovery.zeroconf as zeroconf
PROCESS_NAME = "zeroconf"
wait_for_free_port()
# setup the loglevel
try:
log_level = getattr(rospy, rospy.get_param('/%s/log_level' % PROCESS_NAME, "INFO")... | discoverer.finish()
except Exception as e:
import traceback
rospy.logerr("%s\nError while start master_discovery: %s" % (traceback.format_exc(), str(e)))
os.kill(os.getpid(), signal.SIGKILL)
time.sleep(10)
def main_zeroconf():
| 68 | 68 | 229 | 7 | 61 | tkazik/multimaster_fkie | fkie_master_discovery/src/fkie_master_discovery/__init__.py | Python | main_zeroconf | main_zeroconf | 156 | 176 | 156 | 156 | 9277e03c134d5d7cbba7b19222a76816c458bedd | bigcode/the-stack | train |
2af14b99e60f74f47d99edc8 | train | function | def set_process_name(name):
'''
Change the process name.
@param name: New process name
@type name: str
'''
try:
from ctypes import cdll, byref, create_string_buffer
libc = cdll.LoadLibrary('libc.so.6')
buff = create_string_buffer(len(name) + 1)
buff.value = name
... | def set_process_name(name):
| '''
Change the process name.
@param name: New process name
@type name: str
'''
try:
from ctypes import cdll, byref, create_string_buffer
libc = cdll.LoadLibrary('libc.so.6')
buff = create_string_buffer(len(name) + 1)
buff.value = name
libc.prctl(15, byref... | else 11611
def set_terminal_name(name):
'''
Change the terminal name.
@param name: New name of the terminal
@type name: str
'''
sys.stdout.write("\x1b]2;%s\x07" % name)
def set_process_name(name):
| 64 | 64 | 135 | 6 | 58 | tkazik/multimaster_fkie | fkie_master_discovery/src/fkie_master_discovery/__init__.py | Python | set_process_name | set_process_name | 76 | 93 | 76 | 76 | c6829863fc333152f8918cfe55d5e4af5225d9f2 | bigcode/the-stack | train |
bc5e50a515f2de9ef8e62b81 | train | function | def main():
'''
Creates and runs the ROS node using multicast messages for discovering
'''
import fkie_master_discovery.master_discovery as master_discovery
wait_for_free_port()
# setup the loglevel
try:
log_level = getattr(rospy, rospy.get_param('/%s/log_level' % PROCESS_NAME, "INFO... | def main():
| '''
Creates and runs the ROS node using multicast messages for discovering
'''
import fkie_master_discovery.master_discovery as master_discovery
wait_for_free_port()
# setup the loglevel
try:
log_level = getattr(rospy, rospy.get_param('/%s/log_level' % PROCESS_NAME, "INFO"))
exce... | tcp_port()
while wait_index < 12 and is_port_in_use(rpc_port):
wait_index += 1
if wait_index == 1:
print('RPC port %d is already in use, is there another instance of master_discovery running?' % rpc_port)
time.sleep(1)
if wait_index > 1:
# give time for shutdown other... | 92 | 92 | 308 | 3 | 89 | tkazik/multimaster_fkie | fkie_master_discovery/src/fkie_master_discovery/__init__.py | Python | main | main | 125 | 153 | 125 | 125 | 2ccec756c5b86a2dba1495d01f22d99c05f37014 | bigcode/the-stack | train |
77a6e15c19728c9f5c2d78b7 | train | function | def wait_for_free_port():
wait_index = 0
rpc_port = get_default_rtcp_port()
while wait_index < 12 and is_port_in_use(rpc_port):
wait_index += 1
if wait_index == 1:
print('RPC port %d is already in use, is there another instance of master_discovery running?' % rpc_port)
ti... | def wait_for_free_port():
| wait_index = 0
rpc_port = get_default_rtcp_port()
while wait_index < 12 and is_port_in_use(rpc_port):
wait_index += 1
if wait_index == 1:
print('RPC port %d is already in use, is there another instance of master_discovery running?' % rpc_port)
time.sleep(1)
if wait_in... | :
s.bind(('localhost', port))
except socket.error as e:
if e.errno == errno.EADDRINUSE:
result = True
else:
# something else raised the socket.error exception
print(e)
s.close()
return result
def wait_for_free_port():
| 64 | 64 | 109 | 6 | 57 | tkazik/multimaster_fkie | fkie_master_discovery/src/fkie_master_discovery/__init__.py | Python | wait_for_free_port | wait_for_free_port | 112 | 122 | 112 | 112 | 3cde4354896101dd52c5610ea92310f3051fc685 | bigcode/the-stack | train |
6d7e827644145238dece8000 | train | class | class DataInterpolation(ObjectDataSelection):
"""
Transfer data from one object to another, or onto a 3D BlockModel
"""
defaults = {
"select_multiple": True,
"h5file": "../../assets/FlinFlon.geoh5",
"objects": "Inversion_VTEM_Model",
"data": ["Iteration_7_model"],
... | class DataInterpolation(ObjectDataSelection):
| """
Transfer data from one object to another, or onto a 3D BlockModel
"""
defaults = {
"select_multiple": True,
"h5file": "../../assets/FlinFlon.geoh5",
"objects": "Inversion_VTEM_Model",
"data": ["Iteration_7_model"],
"core_cell_size": "50, 50, 50",
"dep... | # Copyright (c) 2021 Mira Geoscience Ltd.
#
# This file is part of geoapps.
#
# geoapps is distributed under the terms and conditions of the MIT License
# (see LICENSE file at the root of this source code package).
import discretize
import numpy as np
from geoh5py.objects import BlockModel, ObjectBase
from geoh5py... | 169 | 256 | 4,026 | 7 | 161 | sebhmg/geoapps | geoapps/processing/data_interpolation.py | Python | DataInterpolation | DataInterpolation | 29 | 624 | 29 | 29 | ce55cbba8469e31765f186a5ea1f512af7f33e6b | bigcode/the-stack | train |
bf65c7827d76a9c6075a9e46 | train | class | class AwaitableGetViewResult(GetViewResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return GetViewResult(
accumulated=self.accumulated,
chart=self.chart,
created_on=self.created_on,
dataset=self.... | class AwaitableGetViewResult(GetViewResult):
# pylint: disable=using-constant-test
| def __await__(self):
if False:
yield self
return GetViewResult(
accumulated=self.accumulated,
chart=self.chart,
created_on=self.created_on,
dataset=self.dataset,
display_name=self.display_name,
e_tag=self.e_tag,
... | (self, "timeframe")
@property
@pulumi.getter
def type(self) -> str:
"""
Resource type.
"""
return pulumi.get(self, "type")
class AwaitableGetViewResult(GetViewResult):
# pylint: disable=using-constant-test
| 64 | 64 | 140 | 21 | 43 | pulumi/pulumi-azure-nextgen | sdk/python/pulumi_azure_nextgen/costmanagement/get_view.py | Python | AwaitableGetViewResult | AwaitableGetViewResult | 202 | 223 | 202 | 203 | 1b783e340e9008d7af85c68e166b6c92efdc4d27 | bigcode/the-stack | train |
d8920733747a1de4e0a1390e | train | function | def get_view(view_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetViewResult:
"""
States and configurations of Cost Analysis.
API Version: 2020-06-01.
:param str view_name: View name
"""
__args__ = dict()
__args__['viewName'] = view_name... | def get_view(view_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetViewResult:
| """
States and configurations of Cost Analysis.
API Version: 2020-06-01.
:param str view_name: View name
"""
__args__ = dict()
__args__['viewName'] = view_name
if opts is None:
opts = pulumi.InvokeOptions()
if opts.version is None:
opts.version = _utilities.get_vers... | =self.id,
kpis=self.kpis,
metric=self.metric,
modified_on=self.modified_on,
name=self.name,
pivots=self.pivots,
scope=self.scope,
time_period=self.time_period,
timeframe=self.timeframe,
type=self.type)
def get_vi... | 90 | 90 | 303 | 32 | 58 | pulumi/pulumi-azure-nextgen | sdk/python/pulumi_azure_nextgen/costmanagement/get_view.py | Python | get_view | get_view | 226 | 259 | 226 | 227 | 140eedb788de1bd3f7bb99561fe54a6318e6ebf2 | bigcode/the-stack | train |
d8d4c32c702e503562709147 | train | class | @pulumi.output_type
class GetViewResult:
"""
States and configurations of Cost Analysis.
"""
def __init__(__self__, accumulated=None, chart=None, created_on=None, dataset=None, display_name=None, e_tag=None, id=None, kpis=None, metric=None, modified_on=None, name=None, pivots=None, scope=None, time_peri... | @pulumi.output_type
class GetViewResult:
| """
States and configurations of Cost Analysis.
"""
def __init__(__self__, accumulated=None, chart=None, created_on=None, dataset=None, display_name=None, e_tag=None, id=None, kpis=None, metric=None, modified_on=None, name=None, pivots=None, scope=None, time_period=None, timeframe=None, type=None):
... | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from .. import _utilities, _tables
from ... | 116 | 256 | 1,723 | 11 | 105 | pulumi/pulumi-azure-nextgen | sdk/python/pulumi_azure_nextgen/costmanagement/get_view.py | Python | GetViewResult | GetViewResult | 18 | 199 | 18 | 19 | e37a59ccc9904af4a058045d24ceecbc9237b1fc | bigcode/the-stack | train |
37da86ee22474cf079af3136 | train | class | class ComponentItem(QtWidgets.QFrame):
signal_remove = QtCore.Signal(object)
signal_thumbnail = QtCore.Signal(object)
signal_preview = QtCore.Signal(object)
signal_repre_change = QtCore.Signal(object, object)
preview_text = "PREVIEW"
thumbnail_text = "THUMBNAIL"
def __init__(self, parent,... | class ComponentItem(QtWidgets.QFrame):
| signal_remove = QtCore.Signal(object)
signal_thumbnail = QtCore.Signal(object)
signal_preview = QtCore.Signal(object)
signal_repre_change = QtCore.Signal(object, object)
preview_text = "PREVIEW"
thumbnail_text = "THUMBNAIL"
def __init__(self, parent, main_parent):
super().__init__(... | import os
from Qt import QtCore, QtGui, QtWidgets
from .resources import get_resource
class ComponentItem(QtWidgets.QFrame):
| 30 | 256 | 2,185 | 8 | 21 | jonclothcat/OpenPype | openpype/tools/standalonepublish/widgets/widget_component_item.py | Python | ComponentItem | ComponentItem | 6 | 298 | 6 | 7 | f854f2b5c76aeab7046d396f08c2e36dd308b28e | bigcode/the-stack | train |
48bb20b4ee31e54570130c6a | train | class | class PngFactory:
png_names = None
@classmethod
def init(cls):
cls.png_names = {
"trash": {
"normal": QtGui.QIcon(get_resource("trash.png")),
"hover": QtGui.QIcon(get_resource("trash_hover.png")),
"pressed": QtGui.QIcon(get_resource("trash... | class PngFactory:
| png_names = None
@classmethod
def init(cls):
cls.png_names = {
"trash": {
"normal": QtGui.QIcon(get_resource("trash.png")),
"hover": QtGui.QIcon(get_resource("trash_hover.png")),
"pressed": QtGui.QIcon(get_resource("trash_pressed.png")),
... | self, text, font_size_pt=8, *args, **kwargs):
super(LightingButton, self).__init__(text, *args, **kwargs)
self.setStyleSheet(self.lightingbtnstyle % {
"font_size_pt": font_size_pt
})
self.setCheckable(True)
class PngFactory:
| 70 | 70 | 234 | 5 | 65 | jonclothcat/OpenPype | openpype/tools/standalonepublish/widgets/widget_component_item.py | Python | PngFactory | PngFactory | 357 | 388 | 357 | 357 | 59e58533ca5fc5e0928cebd74c18a39f46c0a98e | bigcode/the-stack | train |
95c36727d05438f28e9ae8b8 | train | class | class LightingButton(QtWidgets.QPushButton):
lightingbtnstyle = """
QPushButton {
font: %(font_size_pt)spt;
text-align: center;
color: #777777;
background-color: transparent;
border-width: 1px;
border-color: #777777;
border-style: solid;
padding-to... | class LightingButton(QtWidgets.QPushButton):
| lightingbtnstyle = """
QPushButton {
font: %(font_size_pt)spt;
text-align: center;
color: #777777;
background-color: transparent;
border-width: 1px;
border-color: #777777;
border-style: solid;
padding-top: 0px;
padding-bottom: 0px;
... | thumbnail': self.is_thumbnail(),
'preview': self.is_preview()
}
if ("frameStart" in self.in_data and "frameEnd" in self.in_data):
data["frameStart"] = self.in_data["frameStart"]
data["frameEnd"] = self.in_data["frameEnd"]
if 'fps' in self.in_data:
... | 99 | 99 | 332 | 9 | 89 | jonclothcat/OpenPype | openpype/tools/standalonepublish/widgets/widget_component_item.py | Python | LightingButton | LightingButton | 301 | 354 | 301 | 301 | 70b4b43d3e3fbe2c40d27f8db2afb672955faa9b | bigcode/the-stack | train |
a9d8619fcb9f631f1980e480 | train | class | class PngButton(QtWidgets.QPushButton):
png_button_style = """
QPushButton {
border: none;
background-color: transparent;
padding-top: 0px;
padding-bottom: 0px;
padding-left: 0px;
padding-right: 0px;
}
QPushButton:hover {}
QPushButton:pressed {}
QP... | class PngButton(QtWidgets.QPushButton):
| png_button_style = """
QPushButton {
border: none;
background-color: transparent;
padding-top: 0px;
padding-bottom: 0px;
padding-left: 0px;
padding-right: 0px;
}
QPushButton:hover {}
QPushButton:pressed {}
QPushButton:disabled {}
QPushButton:ch... | _size_pt
})
self.setCheckable(True)
class PngFactory:
png_names = None
@classmethod
def init(cls):
cls.png_names = {
"trash": {
"normal": QtGui.QIcon(get_resource("trash.png")),
"hover": QtGui.QIcon(get_resource("trash_hover.png")),
... | 256 | 256 | 920 | 10 | 246 | jonclothcat/OpenPype | openpype/tools/standalonepublish/widgets/widget_component_item.py | Python | PngButton | PngButton | 391 | 534 | 391 | 391 | 562400584a42f7d1be253d3f5c7407d8abfbb9ab | bigcode/the-stack | train |
db8128c2dacb5241aa1e8825 | train | class | class LockFixture(fixtures.Fixture):
"""External locking fixture.
This fixture is basically an alternative to the synchronized decorator with
the external flag so that tearDowns and addCleanups will be included in
the lock context for locking between tests. The fixture is recommended to
be the firs... | class LockFixture(fixtures.Fixture):
| """External locking fixture.
This fixture is basically an alternative to the synchronized decorator with
the external flag so that tearDowns and addCleanups will be included in
the lock context for locking between tests. The fixture is recommended to
be the first line in a test method, like so::
... | software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import fixtures
from neutron_lbaas.openstack.commo... | 78 | 78 | 260 | 8 | 69 | citrix-openstack-build/neutron-lbaas | neutron_lbaas/openstack/common/fixture/lockutils.py | Python | LockFixture | LockFixture | 21 | 51 | 21 | 21 | e8772512efc845ddabf785f55a635777696f8946 | bigcode/the-stack | train |
ef300387f5fb90c9220ca226 | train | function | @pytest.fixture()
def recorder(event_loop) -> AsyncAWSXRayRecorder:
"""An X-Ray recorder with local-only, stubbed, segment collection."""
xray_recorder = get_new_stubbed_recorder()
xray_recorder.configure(
service="test", sampling=False, context=AsyncContext(loop=event_loop)
)
with patch("x... | @pytest.fixture()
def recorder(event_loop) -> AsyncAWSXRayRecorder:
| """An X-Ray recorder with local-only, stubbed, segment collection."""
xray_recorder = get_new_stubbed_recorder()
xray_recorder.configure(
service="test", sampling=False, context=AsyncContext(loop=event_loop)
)
with patch("xraysink.asgi.middleware.xray_recorder", xray_recorder), patch(
... | bed_recorder
@pytest.fixture()
def caplog(caplog):
"""
Override the standard caplog fixture to have a more sensible default level on the root logger.
"""
caplog.set_level(logging.DEBUG)
return caplog
@pytest.fixture()
def recorder(event_loop) -> AsyncAWSXRayRecorder:
| 64 | 64 | 180 | 15 | 48 | garyd203/xray-asyncio | tests/conftest.py | Python | recorder | recorder | 21 | 37 | 21 | 22 | 8ced5d3bb4905b47a2c707b5856a7f15dfa82ccb | bigcode/the-stack | train |
a80b9422a44fc66d361c424a | train | function | @pytest.fixture()
def caplog(caplog):
"""
Override the standard caplog fixture to have a more sensible default level on the root logger.
"""
caplog.set_level(logging.DEBUG)
return caplog
| @pytest.fixture()
def caplog(caplog):
| """
Override the standard caplog fixture to have a more sensible default level on the root logger.
"""
caplog.set_level(logging.DEBUG)
return caplog
|
import pytest
from aws_xray_sdk import global_sdk_config
from aws_xray_sdk.core.async_context import AsyncContext
from aws_xray_sdk.core.async_recorder import AsyncAWSXRayRecorder
from .xray_util import get_new_stubbed_recorder
@pytest.fixture()
def caplog(caplog):
| 64 | 64 | 45 | 9 | 54 | garyd203/xray-asyncio | tests/conftest.py | Python | caplog | caplog | 12 | 18 | 12 | 13 | 34e530f505acc2729315524a7e0deb5bfb6cecfe | bigcode/the-stack | train |
67a8808da073fc004692b173 | train | class | class GeneralPostProcessSummarizer(PostProcessSummarizer):
ANALYSER_ORDER: Dict[Type[PostProcessSummarizer], int] = {
UserIdSummarizer: 0,
UserEnvironmentSummarizer: 1,
ProcessesToStopSummarizer: 2,
CompositorStateSummarizer: 3,
FinishScriptsSummarizer: 4,
CPUGoverno... | class GeneralPostProcessSummarizer(PostProcessSummarizer):
| ANALYSER_ORDER: Dict[Type[PostProcessSummarizer], int] = {
UserIdSummarizer: 0,
UserEnvironmentSummarizer: 1,
ProcessesToStopSummarizer: 2,
CompositorStateSummarizer: 3,
FinishScriptsSummarizer: 4,
CPUGovernorStateSummarizer: 5,
CPUEnergyPolicyLevelSummarizer:... | izedProcess, main_context: OptimizationContext):
if process.stopped_processes:
self._fill(summary, process, process.stopped_processes, process.relaunch_stopped_processes)
if process.stopped_after_launch:
self._fill(summary, process, process.stopped_after_launch, process.relaunch... | 157 | 157 | 525 | 13 | 143 | vinifmor/guapow | guapow/service/optimizer/post_process/summary.py | Python | GeneralPostProcessSummarizer | GeneralPostProcessSummarizer | 186 | 243 | 186 | 187 | b9f6516334e9efbcb3d7bc4bcb4daf4d005d6e39 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.