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
a0594bb14abb53f6e9a343a4
train
class
class SideBarDuplicateCommand(sublime_plugin.WindowCommand): def run(self, paths=[], new=False): import functools Window().run_command("hide_panel") view = Window().show_input_panel( "Duplicate As:", new or SideBarSelection(paths).getSelectedItems()[0].path(), ...
class SideBarDuplicateCommand(sublime_plugin.WindowCommand):
def run(self, paths=[], new=False): import functools Window().run_command("hide_panel") view = Window().show_input_panel( "Duplicate As:", new or SideBarSelection(paths).getSelectedItems()[0].path(), functools.partial( self.on_done, SideBa...
("\n".join(items)) if len(items) > 1: sublime.status_message("Items URL copied") else: sublime.status_message("Item URL copied") def is_enabled(self, paths=[]): return CACHED_SELECTION(paths).hasItemsUnderProject() class SideBarDuplicateCommand(sublim...
69
69
232
12
57
52fisher/SideBarEnhancements
SideBar.py
Python
SideBarDuplicateCommand
SideBarDuplicateCommand
1,610
1,641
1,610
1,610
a9f51cbd1cb6dadf4e681b9a4474cbcbde244ec6
bigcode/the-stack
train
4ac5661efbc1ee26bf131f50
train
class
class SideBarFindFilesPathContainingCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if paths == [] and SideBarProject().getDirectories(): paths = SideBarProject().getDirectories() else: paths = [ item.path() for item in SideBar...
class SideBarFindFilesPathContainingCommand(sublime_plugin.WindowCommand):
def run(self, paths=[]): if paths == [] and SideBarProject().getDirectories(): paths = SideBarProject().getDirectories() else: paths = [ item.path() for item in SideBarSelection(paths).getSelectedDirectoriesOrDirnames() ] i...
> 0: return "在后缀名为" + (",".join(items)) + "的文件中………" else: return "在所有文件中……" Object.sidebar_instant_search_id = 0 class SideBarFindFilesPathContainingCommand(sublime_plugin.WindowCommand):
64
64
210
15
48
52fisher/SideBarEnhancements
SideBar.py
Python
SideBarFindFilesPathContainingCommand
SideBarFindFilesPathContainingCommand
673
698
673
673
ada22a8acf399ee57d4791ccbd2f0d77e4bd2e79
bigcode/the-stack
train
fc89f532df77a4fbacdf9238
train
class
class SideBarRevealCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): if len(paths) > 1: paths = SideBarSelection(paths).getSelectedDirectoriesOrDirnames() else: paths = SideBarSelection(paths).getSelectedItems() for item in paths: item.reveal...
class SideBarRevealCommand(sublime_plugin.WindowCommand):
def run(self, paths=[]): if len(paths) > 1: paths = SideBarSelection(paths).getSelectedDirectoriesOrDirnames() else: paths = SideBarSelection(paths).getSelectedItems() for item in paths: item.reveal() def is_enabled(self, paths=[]): return CAC...
(file): send2trash(file) if s.get("close_affected_buffers_when_deleting_even_if_dirty", False): item.closeViews() except: pass SideBarProject().refresh() window_set_status(key, "") class SideBarRevealCommand(sublime_plugin.W...
63
64
92
12
51
52fisher/SideBarEnhancements
SideBar.py
Python
SideBarRevealCommand
SideBarRevealCommand
2,158
2,168
2,158
2,158
499da12a4a14003433040c8960fed303551b6c18
bigcode/the-stack
train
f5a4b394c9c29c1517739386
train
class
class SideBarProjectItemAddCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): project = SideBarProject() for item in SideBarSelection(paths).getSelectedDirectories(): project.add(item.path()) def is_enabled(self, paths=[]): return ( CACHED_SELECTION(...
class SideBarProjectItemAddCommand(sublime_plugin.WindowCommand):
def run(self, paths=[]): project = SideBarProject() for item in SideBarSelection(paths).getSelectedDirectories(): project.add(item.path()) def is_enabled(self, paths=[]): return ( CACHED_SELECTION(paths).hasDirectories() and CACHED_SELECTION(paths).ha...
def run(self, paths=[]): item = SideBarItem( os.path.dirname(sublime.packages_path()) + "/Settings/SideBarEnhancements.json", False, ) item.dirnameCreate() item.edit() class SideBarProjectItemAddCommand(sublime_plugin.WindowCommand):
64
64
85
14
50
52fisher/SideBarEnhancements
SideBar.py
Python
SideBarProjectItemAddCommand
SideBarProjectItemAddCommand
2,192
2,202
2,192
2,192
4c6a201593c518929db31fa4cab18c3a10e00c6c
bigcode/the-stack
train
492e134bc7ab061b469c26fa
train
function
def Window(window=None): return window if window else sublime.active_window()
def Window(window=None):
return window if window else sublime.active_window()
(self): pass def plugin_loaded(): global Pref, s s = sublime.load_settings("Side Bar.sublime-settings") Pref = Pref() Pref.load() s.clear_on_change("reload") s.add_on_change("reload", lambda: Pref.load()) def Window(window=None):
64
64
15
5
59
52fisher/SideBarEnhancements
SideBar.py
Python
Window
Window
72
73
72
72
6c6d9f6e855fe539c7101e92e91ead367f6ee430
bigcode/the-stack
train
f0d63940e8bf1aaae8965f09
train
class
class SideBarNewDirectoryCommand(sublime_plugin.WindowCommand): def run(self, paths=[], name=""): import functools Window().run_command("hide_panel") Window().show_input_panel( "Folder Name:", name, functools.partial(self.on_done, paths, False), ...
class SideBarNewDirectoryCommand(sublime_plugin.WindowCommand):
def run(self, paths=[], name=""): import functools Window().run_command("hide_panel") Window().show_input_panel( "Folder Name:", name, functools.partial(self.on_done, paths, False), None, None, ) def on_done(self, path...
Directory2Command(sublime_plugin.WindowCommand): def run(self, paths=[], name=""): import functools Window().run_command("hide_panel") Window().show_input_panel( "Folder Name:", name, functools.partial( SideBarNewDirectoryCommand(Window())...
90
90
301
13
77
52fisher/SideBarEnhancements
SideBar.py
Python
SideBarNewDirectoryCommand
SideBarNewDirectoryCommand
190
229
190
190
0ac05298d1d0d63438ba8b23ca600a97a6f0269e
bigcode/the-stack
train
91118f1310097bccce65812d
train
class
class zzzzzSideBarCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): pass def is_visible(self, paths=[]): # <- WORKS AS AN ONPOPUPSHOWN Cache.cached = False return False
class zzzzzSideBarCommand(sublime_plugin.WindowCommand):
def run(self, paths=[]): pass def is_visible(self, paths=[]): # <- WORKS AS AN ONPOPUPSHOWN Cache.cached = False return False
_donated_to_sidebar_enhancements_developer", False) == "https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=DD4SL2AHYJGBW" ) class zzzzzSideBarCommand(sublime_plugin.WindowCommand):
64
64
57
14
50
52fisher/SideBarEnhancements
SideBar.py
Python
zzzzzSideBarCommand
zzzzzSideBarCommand
2,774
2,780
2,774
2,774
bc341dcfd7f0bfd835542304c94fb0a2a66e1a41
bigcode/the-stack
train
bf5f26ca24785da075c1af2e
train
class
class SideBarCopyCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): s = sublime.load_settings("SideBarEnhancements/Clipboard.sublime-settings") items = [] for item in SideBarSelection(paths).getSelectedItemsWithoutChildItems(): items.append(item.path()) if l...
class SideBarCopyCommand(sublime_plugin.WindowCommand):
def run(self, paths=[]): s = sublime.load_settings("SideBarEnhancements/Clipboard.sublime-settings") items = [] for item in SideBarSelection(paths).getSelectedItemsWithoutChildItems(): items.append(item.path()) if len(items) > 0: s.set("cut", "") ...
") else: sublime.status_message("Item cut") def is_enabled(self, paths=[]): return ( CACHED_SELECTION(paths).len() > 0 and CACHED_SELECTION(paths).hasProjectDirectories() is False ) class SideBarCopyCommand(sublime_plugin.WindowCommand):
64
64
142
12
52
52fisher/SideBarEnhancements
SideBar.py
Python
SideBarCopyCommand
SideBarCopyCommand
880
896
880
880
7b3b3fb9853a4a53ba6b9f659f9dcc7c48c365a8
bigcode/the-stack
train
f9dddbd64187b7602254e61b
train
class
class SideBarPasteCommand(sublime_plugin.WindowCommand): def run(self, paths=[], in_parent="False", test="True", replace="False"): key = "paste-" + str(time.time()) SideBarPasteThread(paths, in_parent, test, replace, key).start() def is_enabled(self, paths=[], in_parent=False): s = subl...
class SideBarPasteCommand(sublime_plugin.WindowCommand):
def run(self, paths=[], in_parent="False", test="True", replace="False"): key = "paste-" + str(time.time()) SideBarPasteThread(paths, in_parent, test, replace, key).start() def is_enabled(self, paths=[], in_parent=False): s = sublime.load_settings("SideBarEnhancements/Clipboard.sublime-...
(items)) if len(items) > 1: sublime.status_message("Items copied") else: sublime.status_message("Item copied") def is_enabled(self, paths=[]): return CACHED_SELECTION(paths).len() > 0 class SideBarPasteCommand(sublime_plugin.WindowCommand):
64
64
175
12
51
52fisher/SideBarEnhancements
SideBar.py
Python
SideBarPasteCommand
SideBarPasteCommand
899
914
899
899
3bedc911a9b16934f7a2f8abd6ec5a1ee7004a8d
bigcode/the-stack
train
49b859b95b2fe1d50955f64e
train
class
class SideBarFilesOpenWithEditApplicationsCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): platform = "" if sublime.platform() == "osx": platform = "OSX" elif sublime.platform() == "windows": platform = "Windows" else: platform = "Li...
class SideBarFilesOpenWithEditApplicationsCommand(sublime_plugin.WindowCommand):
def run(self, paths=[]): platform = "" if sublime.platform() == "osx": platform = "OSX" elif sublime.platform() == "windows": platform = "Windows" else: platform = "Linux" item = SideBarItem( os.path.join( subli...
return CACHED_SELECTION(paths).hasFiles() def is_visible(self, paths=[]): return not s.get("disabled_menuitem_edit", False) and not s.get( "disabled_menuitem_edit_to_right", False ) class SideBarOpenCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): for item ...
164
164
548
16
148
52fisher/SideBarEnhancements
SideBar.py
Python
SideBarFilesOpenWithEditApplicationsCommand
SideBarFilesOpenWithEditApplicationsCommand
363
455
363
363
ff2d0ed84c1083464b91871f241267014572a8b4
bigcode/the-stack
train
eb6d25a213ca90c937af0032
train
class
class view_locations_stack_listener(sublime_plugin.EventListener): def on_activated(self, v): global view_locations_stack if ( v and v.file_name() and (not view_locations_stack or view_locations_stack[-1] != v.file_name()) ): view_locations_sta...
class view_locations_stack_listener(sublime_plugin.EventListener):
def on_activated(self, v): global view_locations_stack if ( v and v.file_name() and (not view_locations_stack or view_locations_stack[-1] != v.file_name()) ): view_locations_stack.append(v.file_name()) view_locations_stack = view_lo...
) > 1: sublime.status_message("Items copied") else: sublime.status_message("Item copied") def is_enabled(self, paths=[]): return CACHED_SELECTION(paths).len() > 0 view_locations_stack = [] class view_locations_stack_listener(sublime_plugin.EventListener):
63
64
80
12
51
52fisher/SideBarEnhancements
SideBar.py
Python
view_locations_stack_listener
view_locations_stack_listener
1,246
1,255
1,246
1,246
055940157882d3d1a8a3f50768f0767d61bc2299
bigcode/the-stack
train
c585e9bcdc4a982084b001ae
train
class
class SideBarNewFileCommand(sublime_plugin.WindowCommand): def run(self, paths=[], name=""): import functools Window().run_command("hide_panel") Window().show_input_panel( "File Name:", name, functools.partial(self.on_done, paths, False), None...
class SideBarNewFileCommand(sublime_plugin.WindowCommand):
def run(self, paths=[], name=""): import functools Window().run_command("hide_panel") Window().show_input_panel( "File Name:", name, functools.partial(self.on_done, paths, False), None, None, ) def on_done(self, paths,...
("SideBar-" + key, name) class Object: pass class Cache: pass Cache = Cache() Cache.cached = False class aaaaaSideBarCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): pass def is_visible(self, paths=[]): # <- WORKS AS AN ONPOPUPSHOWN Cache.cached = SideBarSelectio...
102
102
342
13
88
52fisher/SideBarEnhancements
SideBar.py
Python
SideBarNewFileCommand
SideBarNewFileCommand
109
157
109
109
e7cfa58511f1a433a9f0a16f4b3bcd4707b6e7ed
bigcode/the-stack
train
a6c443ec67098c42773abab6
train
class
class SideBarCopyDirPathCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): items = [] for item in SideBarSelection(paths).getSelectedDirectoriesOrDirnames(): items.append(item.path()) if len(items) > 0: sublime.set_clipboard("\n".join(items)) ...
class SideBarCopyDirPathCommand(sublime_plugin.WindowCommand):
def run(self, paths=[]): items = [] for item in SideBarSelection(paths).getSelectedDirectoriesOrDirnames(): items.append(item.path()) if len(items) > 0: sublime.set_clipboard("\n".join(items)) if len(items) > 1: sublime.status_message("Ite...
if len(items) > 1: sublime.status_message("Items copied") else: sublime.status_message("Item copied") def is_enabled(self, paths=[]): return CACHED_SELECTION(paths).len() > 0 class SideBarCopyDirPathCommand(sublime_plugin.WindowCommand):
64
64
142
14
49
52fisher/SideBarEnhancements
SideBar.py
Python
SideBarCopyDirPathCommand
SideBarCopyDirPathCommand
1,130
1,147
1,130
1,130
8b61c40e161874711ffa643e1a3961c5d4031c8b
bigcode/the-stack
train
c9821e2a56853db3021f687e
train
class
class SideBarStatusBarFileSize(sublime_plugin.EventListener): def on_activated(self, v): if v.file_name() and s.get("statusbar_file_size", False): try: self.show(v, hurry_size(os.path.getsize(v.file_name()))) except: pass def on_post_save(self, v)...
class SideBarStatusBarFileSize(sublime_plugin.EventListener):
def on_activated(self, v): if v.file_name() and s.get("statusbar_file_size", False): try: self.show(v, hurry_size(os.path.getsize(v.file_name()))) except: pass def on_post_save(self, v): if v.file_name() and s.get("statusbar_file_size", Fa...
subprocess for item in SideBarSelection(paths).getSelectedDirectoriesOrDirnames(): subprocess.Popen(["open", item.name()], cwd=item.dirname()) def is_visible(self, paths=[]): return sublime.platform() == "osx" class SideBarStatusBarFileSize(sublime_plugin.EventListener):
64
64
135
14
50
52fisher/SideBarEnhancements
SideBar.py
Python
SideBarStatusBarFileSize
SideBarStatusBarFileSize
2,661
2,677
2,661
2,661
5ec59aa90939d99e319d6da41dae21037abbddbe
bigcode/the-stack
train
e40991b00b1aa8433350ece3
train
class
class SideBarCopyTagScriptCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): items = [] for item in SideBarSelection(paths).getSelectedFilesWithExtension("js"): items.append( '<script type="text/javascript" src="' + item.pathAbsoluteFromProjec...
class SideBarCopyTagScriptCommand(sublime_plugin.WindowCommand):
def run(self, paths=[]): items = [] for item in SideBarSelection(paths).getSelectedFilesWithExtension("js"): items.append( '<script type="text/javascript" src="' + item.pathAbsoluteFromProjectEncoded() + '"></script>' ) ...
else: sublime.status_message("Item copied") def is_enabled(self, paths=[]): return ( CACHED_SELECTION(paths).hasFilesWithExtension("css") and CACHED_SELECTION(paths).hasItemsUnderProject() ) class SideBarCopyTagScriptCommand(sublime_plugin.WindowC...
64
64
162
14
50
52fisher/SideBarEnhancements
SideBar.py
Python
SideBarCopyTagScriptCommand
SideBarCopyTagScriptCommand
1,492
1,513
1,492
1,492
d1b38e0649dee3574a606d10a32888457a1e9aa1
bigcode/the-stack
train
82f5fff4f0d7bf5530f4ae29
train
class
class SideBarEnhancementsWriteToViewCommand(sublime_plugin.TextCommand): def run(self, edit, content, position, searchTerm): if Object.sidebar_instant_search_id == searchTerm: view = self.view view.replace(edit, sublime.Region(0, view.size()), content) view.sel().clear() ...
class SideBarEnhancementsWriteToViewCommand(sublime_plugin.TextCommand):
def run(self, edit, content, position, searchTerm): if Object.sidebar_instant_search_id == searchTerm: view = self.view view.replace(edit, sublime.Region(0, view.size()), content) view.sel().clear() view.sel().add(sublime.Region(position, position)) ...
for s in self.ignore_paths if s in path ] def match_string(self, path): return self.searchTerm in path and not [ 1 for s in self.ignore_paths if s in path ] class SideBarEnhancementsWriteToViewCommand(sublime_plugin.TextCommand):
63
64
88
16
47
52fisher/SideBarEnhancements
SideBar.py
Python
SideBarEnhancementsWriteToViewCommand
SideBarEnhancementsWriteToViewCommand
848
855
848
848
25aa94b696338101e460da2c38c3d48f95fb41a1
bigcode/the-stack
train
14adf11df2723fe06a24a9af
train
class
class SideBarCopyPathRelativeFromProjectCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): items = [] for item in SideBarSelection(paths).getSelectedItems(): items.append(item.pathRelativeFromProject()) if len(items) > 0: sublime.set_clipboard("\n".join(...
class SideBarCopyPathRelativeFromProjectCommand(sublime_plugin.WindowCommand):
def run(self, paths=[]): items = [] for item in SideBarSelection(paths).getSelectedItems(): items.append(item.pathRelativeFromProject()) if len(items) > 0: sublime.set_clipboard("\n".join(items)) if len(items) > 1: sublime.status_message("...
len(items) > 1: sublime.status_message("Items copied") else: sublime.status_message("Item copied") def is_enabled(self, paths=[]): return CACHED_SELECTION(paths).len() > 0 class SideBarCopyPathRelativeFromProjectCommand(sublime_plugin.WindowCommand):
64
64
136
16
47
52fisher/SideBarEnhancements
SideBar.py
Python
SideBarCopyPathRelativeFromProjectCommand
SideBarCopyPathRelativeFromProjectCommand
1,167
1,184
1,167
1,167
7bb98759edbce3340c66e5f683b01f31eb264246
bigcode/the-stack
train
618b9128779902d9bffb7a0d
train
class
class SideBarNewFile2Command(sublime_plugin.WindowCommand): def run(self, paths=[], name=""): import functools Window().run_command("hide_panel") Window().show_input_panel( "File Name:", name, functools.partial(SideBarNewFileCommand(Window()).on_done, pat...
class SideBarNewFile2Command(sublime_plugin.WindowCommand):
def run(self, paths=[], name=""): import functools Window().run_command("hide_panel") Window().show_input_panel( "File Name:", name, functools.partial(SideBarNewFileCommand(Window()).on_done, paths, True), None, None, )
: item.create() item.edit() except: sublime.error_message( "Unable to create file:\n\n" + item.path() ) self.run(paths, name) re...
64
64
78
14
50
52fisher/SideBarEnhancements
SideBar.py
Python
SideBarNewFile2Command
SideBarNewFile2Command
160
171
160
160
15d0fd2321c8471a71d6a817d954db52be23374f
bigcode/the-stack
train
dfb820dbe16e4ea599b2d46a
train
class
class SideBarFolderCloseOtherViewsCommand(sublime_plugin.WindowCommand): def run(self, paths=[]): to_close = self.others_views(paths) for view in to_close: view.close() def others_views(self, paths=[]): window = Window() opened = [] selected = [] for...
class SideBarFolderCloseOtherViewsCommand(sublime_plugin.WindowCommand):
def run(self, paths=[]): to_close = self.others_views(paths) for view in to_close: view.close() def others_views(self, paths=[]): window = Window() opened = [] selected = [] for view in window.views(): opened.append(view) for item...
views = views + item.views() return CACHED_SELECTION(paths).hasDirectories() and len(views) > 0 def is_visible(self, paths=[]): return not s.get("disabled_menuitem_folder_close", False) class SideBarFolderCloseOtherViewsCommand(sublime_plugin.WindowCommand):
64
64
177
15
49
52fisher/SideBarEnhancements
SideBar.py
Python
SideBarFolderCloseOtherViewsCommand
SideBarFolderCloseOtherViewsCommand
286
310
286
286
f72625a03074c8aab1ae4f49ad6b1e0cc4cdd323
bigcode/the-stack
train
1ec39f32db3ddc493038b1c7
train
function
def cli(command): info = subprocess.STARTUPINFO() info.dwFlags = subprocess.STARTF_USESHOWWINDOW info.wShowWindow = 0 p = subprocess.Popen( command, startupinfo=info, stdin=subprocess.PIPE, stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=platform.sys...
def cli(command):
info = subprocess.STARTUPINFO() info.dwFlags = subprocess.STARTF_USESHOWWINDOW info.wShowWindow = 0 p = subprocess.Popen( command, startupinfo=info, stdin=subprocess.PIPE, stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=platform.system() == "Windows"...
hurry_size try: from urllib import unquote as urlunquote except ImportError: from urllib.parse import unquote as urlunquote from .SideBarAPI import SideBarItem, SideBarSelection, SideBarProject Pref = {} s = {} Cache = {} def cli(command):
63
64
129
4
59
52fisher/SideBarEnhancements
SideBar.py
Python
cli
cli
25
44
25
25
fe0cd3f9d604c765d754ed00ac0886f657c0e1ef
bigcode/the-stack
train
7dd65b8cf9faeeae117966da
train
function
def on_enter(event_data): """ State logic for starting up. This state should only be entered from either the sleeping or taking darks states. """ pocs = event_data.model pocs.next_state = 'parking' # Prepare the hardware pocs.observatory.prepare_cameras() pocs.observatory.mount.unpark()...
def on_enter(event_data):
""" State logic for starting up. This state should only be entered from either the sleeping or taking darks states. """ pocs = event_data.model pocs.next_state = 'parking' # Prepare the hardware pocs.observatory.prepare_cameras() pocs.observatory.mount.unpark() # Check if we need t...
def on_enter(event_data):
6
64
135
6
0
AstroHuntsman/huntsman-pocs
src/huntsman/pocs/states/huntsman/starting.py
Python
on_enter
on_enter
2
19
2
2
f10f41a745b2179cefc946ca5f24737a1c7a635c
bigcode/the-stack
train
8bc7eb48e361b6cc1ed91c1c
train
function
def count_paths(g, start="start", seen=[]): """ >>> count_paths(read_input('ex1')) 10 >>> count_paths(read_input('ex2')) 19 >>> count_paths(read_input('ex3')) 226 """ npaths = 0 for nxt in g[start]: # print(" " * len(seen) + f"{start} -> {nxt} : {seen}") if nxt =...
def count_paths(g, start="start", seen=[]):
""" >>> count_paths(read_input('ex1')) 10 >>> count_paths(read_input('ex2')) 19 >>> count_paths(read_input('ex3')) 226 """ npaths = 0 for nxt in g[start]: # print(" " * len(seen) + f"{start} -> {nxt} : {seen}") if nxt == "end": npaths += 1 eli...
" and b != "start": g[a] = g.get(a, []) + [b] if b != "end" and a != "start": g[b] = g.get(b, []) + [a] return g def count_paths(g, start="start", seen=[]):
64
64
143
12
51
fcharlier/AdventOfCode
2021/day12/pt1.py
Python
count_paths
count_paths
26
43
26
26
ba266517ca7164620aa6f9ebbd257338524d4999
bigcode/the-stack
train
10954e2bc733f4b420a951a5
train
function
def read_input(filename): """ >>> g = read_input('ex1') >>> len(g) 5 >>> g["start"] ['A', 'b'] >>> g.get("end") >>> g.get("A") ['c', 'b', 'end'] """ g = {} with open(filename) as fd: for line in fd: a, b = line.strip().split("-") if a != "e...
def read_input(filename):
""" >>> g = read_input('ex1') >>> len(g) 5 >>> g["start"] ['A', 'b'] >>> g.get("end") >>> g.get("A") ['c', 'b', 'end'] """ g = {} with open(filename) as fd: for line in fd: a, b = line.strip().split("-") if a != "end" and b != "start": ...
#!/usr/bin/python def read_input(filename):
10
64
152
5
4
fcharlier/AdventOfCode
2021/day12/pt1.py
Python
read_input
read_input
4
23
4
4
a0ef11e6da48ff0855a48960fba78ccdcdf94bfa
bigcode/the-stack
train
ebd5060485a208f253a51df4
train
class
class QotdGame(Game): """ Each game must extend Game """ class Meta: # A Game extending core.game.models.Game should be set as proxy proxy = True def __init__(self, *args, **kwargs): # Set parent's fields self._meta.get_field('verbose_name').default = "Question of the Day" ...
class QotdGame(Game):
""" Each game must extend Game """ class Meta: # A Game extending core.game.models.Game should be set as proxy proxy = True def __init__(self, *args, **kwargs): # Set parent's fields self._meta.get_field('verbose_name').default = "Question of the Day" self._meta.get_...
_noop('has given a wrong answer to QotD.') signals.addActivity.send(sender=None, user_from=self, user_to=self, message=signal_msg, action=action_msg, game=Qotd...
177
177
590
7
169
iulianstana/wouso
wouso/games/qotd/models.py
Python
QotdGame
QotdGame
78
153
78
78
a4a82f21c07bc87f66e6d14dc2df46b56decce9c
bigcode/the-stack
train
675ed7ab2424def612656a58
train
class
class QotdUser(Player): """ Extension of the User object, customized for qotd """ last_answered = models.DateTimeField(null=True, blank=True, default=None) last_answer = models.IntegerField(default=0, blank=True) last_answer_correct = models.BooleanField(default=0, blank=True) my_question = models.F...
class QotdUser(Player):
""" Extension of the User object, customized for qotd """ last_answered = models.DateTimeField(null=True, blank=True, default=None) last_answer = models.IntegerField(default=0, blank=True) last_answer_correct = models.BooleanField(default=0, blank=True) my_question = models.ForeignKey(Question, rela...
from datetime import date, datetime, time from django.conf import settings from django.db import models from django.http import Http404 from django.utils.translation import ugettext_noop from random import randint, shuffle from wouso.core.user.models import Player from wouso.core.game.models import Game from wouso.core...
107
138
463
7
99
iulianstana/wouso
wouso/games/qotd/models.py
Python
QotdUser
QotdUser
15
75
15
15
73330ac6a2f45998c440c2a7c1cdd1df1b3fab86
bigcode/the-stack
train
1d5b29ab9ea142c57f3003c5
train
function
def command(fn): args = get_args() params = get_function_arguments(fn) params = merge_dict(params, args) def wrapper(*args, **kwargs): return fn(**params) return wrapper
def command(fn):
args = get_args() params = get_function_arguments(fn) params = merge_dict(params, args) def wrapper(*args, **kwargs): return fn(**params) return wrapper
# imports - module imports from sbml2json.cli.util import * from sbml2json.cli.parser import get_args from sbml2json.util._dict import merge_dict from sbml2json.util.types import get_function_arguments def command(fn):
55
64
50
4
50
achillesrasquinha/sbml2json
src/sbml2json/cli/__init__.py
Python
command
command
7
17
7
7
1ec6e0b214423404f46b88e675b64308b958efc9
bigcode/the-stack
train
b615ad1816f40c661a582a93
train
class
class SimpleConfig(Logger): """ The SimpleConfig class is responsible for handling operations involving configuration files. There are two different sources of possible configuration values: 1. Command line options. 2. User configuration (in the user's config directory) They are tak...
class SimpleConfig(Logger):
""" The SimpleConfig class is responsible for handling operations involving configuration files. There are two different sources of possible configuration values: 1. Command line options. 2. User configuration (in the user's config directory) They are taken in order (1. overrides co...
, 2] FEE_DEPTH_TARGETS = [10000000, 5000000, 2000000, 1000000, 500000, 200000, 100000] FEE_LN_ETA_TARGET = 2 # note: make sure the network is asking for estimates for this target # satoshi per kbyte FEERATE_MAX_DYNAMIC = 1500000 FEERATE_WARNING_HIGH_FEE = 600000 FEERATE_FALLBACK_STATIC_FEE = 150000 FEERATE_DEFAULT_RE...
256
256
5,012
5
250
GZR0/electrum
electrum/simple_config.py
Python
SimpleConfig
SimpleConfig
46
639
46
46
4362a11d0ef9de4242a06f9dcaaebb81bab68995
bigcode/the-stack
train
370959275e2cd8fae52f6682
train
function
def read_user_config(path): """Parse and store the user config settings in electrum.conf into user_config[].""" if not path: return {} config_path = os.path.join(path, "config") if not os.path.exists(config_path): return {} try: with open(config_path, "r", encoding='utf-8') a...
def read_user_config(path):
"""Parse and store the user config settings in electrum.conf into user_config[].""" if not path: return {} config_path = os.path.join(path, "config") if not os.path.exists(config_path): return {} try: with open(config_path, "r", encoding='utf-8') as f: data = f.re...
set_base_unit(self, unit): assert unit in base_units.keys() self.decimal_point = base_unit_name_to_decimal_point(unit) self.set_key('decimal_point', self.decimal_point, True) def get_decimal_point(self): return self.decimal_point def read_user_config(path):
64
64
127
6
57
GZR0/electrum
electrum/simple_config.py
Python
read_user_config
read_user_config
642
658
642
642
bcdbb8b6433f4e527a8933c1af23fbabf99aa6b3
bigcode/the-stack
train
1d738c5b0b7242eec0b66980
train
class
class RotationTransform(Transform): """ This method returns a copy of this image, rotated the given number of degrees counter clockwise around its center. """ def __init__(self, h, w, angle, expand=True, center=None, interp=None): """ Args: h, w (int): original image siz...
class RotationTransform(Transform):
""" This method returns a copy of this image, rotated the given number of degrees counter clockwise around its center. """ def __init__(self, h, w, angle, expand=True, center=None, interp=None): """ Args: h, w (int): original image size angle (float): degrees...
bilinear", Image.BICUBIC: "bicubic", } mode = _PIL_RESIZE_TO_INTERPOLATE_MODE[interp_method] align_corners = None if mode == "nearest" else False img = F.interpolate( img, (self.new_h, self.new_w), mode=mode, align_corners=align_corners ...
256
256
899
6
250
mmabrouk/detectron2
detectron2/data/transforms/transform.py
Python
RotationTransform
RotationTransform
162
247
162
162
235f4bd6d647669c869fb98c6f7174e70479f516
bigcode/the-stack
train
4ce4680b08780084c64e97f9
train
class
class ExtentTransform(Transform): """ Extracts a subregion from the source image and scales it to the output size. The fill color is used to map pixels from the source rect that fall outside the source image. See: https://pillow.readthedocs.io/en/latest/PIL.html#PIL.ImageTransform.ExtentTransform ...
class ExtentTransform(Transform):
""" Extracts a subregion from the source image and scales it to the output size. The fill color is used to map pixels from the source rect that fall outside the source image. See: https://pillow.readthedocs.io/en/latest/PIL.html#PIL.ImageTransform.ExtentTransform """ def __init__(self, sr...
Copyright (c) Facebook, Inc. and its affiliates. """ See "Data Augmentation" tutorial for an overview of the system: https://detectron2.readthedocs.io/tutorials/augmentation.html """ import numpy as np import torch import torch.nn.functional as F from fvcore.transforms.transform import ( CropTransform, HFlip...
162
162
540
7
155
mmabrouk/detectron2
detectron2/data/transforms/transform.py
Python
ExtentTransform
ExtentTransform
36
91
36
36
bd6f370d257953f3d55c4109c47f3dc806a3fa15
bigcode/the-stack
train
36d8609889763431aa0da8ec
train
class
class ColorTransform(Transform): """ Generic wrapper for any photometric transforms. These transformations should only affect the color space and not the coordinate space of the image (e.g. annotation coordinates such as bounding boxes should not be changed) """ def __init__(self, o...
class ColorTransform(Transform):
""" Generic wrapper for any photometric transforms. These transformations should only affect the color space and not the coordinate space of the image (e.g. annotation coordinates such as bounding boxes should not be changed) """ def __init__(self, op): """ Args: ...
True, None, self.interp ) crop = CropTransform( (rotation.bound_w - self.w) // 2, (rotation.bound_h - self.h) // 2, self.w, self.h ) return TransformList([rotation, crop]) class ColorTransform(Transform):
64
64
175
6
58
mmabrouk/detectron2
detectron2/data/transforms/transform.py
Python
ColorTransform
ColorTransform
250
279
250
250
14719708c879fd0165a4bf6795dabc82a7eff4b2
bigcode/the-stack
train
59c315f3620305671668994d
train
function
def Resize_rotated_box(transform, rotated_boxes): """ Apply the resizing transform on rotated boxes. For details of how these (approximation) formulas are derived, please refer to :meth:`RotatedBoxes.scale`. Args: rotated_boxes (ndarray): Nx5 floating point array of (x_center, y_cen...
def Resize_rotated_box(transform, rotated_boxes):
""" Apply the resizing transform on rotated boxes. For details of how these (approximation) formulas are derived, please refer to :meth:`RotatedBoxes.scale`. Args: rotated_boxes (ndarray): Nx5 floating point array of (x_center, y_center, width, height, angle_degrees) format ...
, y_center, width, height, angle_degrees) format in absolute coordinates. """ # Transform x_center rotated_boxes[:, 0] = transform.width - rotated_boxes[:, 0] # Transform angle rotated_boxes[:, 4] = -rotated_boxes[:, 4] return rotated_boxes def Resize_rotated_box(transform, rotated_b...
80
80
269
10
69
mmabrouk/detectron2
detectron2/data/transforms/transform.py
Python
Resize_rotated_box
Resize_rotated_box
323
344
323
323
8511d727a711a9beed3723522c25b0ddde330520
bigcode/the-stack
train
f8302a52beffed1e7e878b21
train
function
def HFlip_rotated_box(transform, rotated_boxes): """ Apply the horizontal flip transform on rotated boxes. Args: rotated_boxes (ndarray): Nx5 floating point array of (x_center, y_center, width, height, angle_degrees) format in absolute coordinates. """ # Transform x_...
def HFlip_rotated_box(transform, rotated_boxes):
""" Apply the horizontal flip transform on rotated boxes. Args: rotated_boxes (ndarray): Nx5 floating point array of (x_center, y_center, width, height, angle_degrees) format in absolute coordinates. """ # Transform x_center rotated_boxes[:, 0] = transform.width ...
/ """ if not callable(op): raise ValueError("op parameter should be callable") super().__init__(op) def apply_image(self, img): img = Image.fromarray(img) return np.asarray(super().apply_image(img)) def HFlip_rotated_box(transform, rotated_boxes):
64
64
114
11
53
mmabrouk/detectron2
detectron2/data/transforms/transform.py
Python
HFlip_rotated_box
HFlip_rotated_box
307
320
307
307
1167cd6d6e1b921813c3a39df59cf0e01cc4a926
bigcode/the-stack
train
d35268fe05a9053f4b094218
train
class
class ResizeTransform(Transform): """ Resize the image to a target size. """ def __init__(self, h, w, new_h, new_w, interp=None): """ Args: h, w (int): original image size new_h, new_w (int): new image size interp: PIL interpolation methods, defaults ...
class ResizeTransform(Transform):
""" Resize the image to a target size. """ def __init__(self, h, w, new_h, new_w, interp=None): """ Args: h, w (int): original image size new_h, new_w (int): new image size interp: PIL interpolation methods, defaults to bilinear. """ #...
source coordinates into output coordinates # and then map the new origin to the corner of the output image. h, w = self.output_size x0, y0, x1, y1 = self.src_rect new_coords = coords.astype(np.float32) new_coords[:, 0] -= 0.5 * (x0 + x1) new_coords[:, 1] -= 0.5 * (y0 + y...
202
202
675
6
195
mmabrouk/detectron2
detectron2/data/transforms/transform.py
Python
ResizeTransform
ResizeTransform
94
159
94
94
708a9fe6ed2e4b866068c3141aa30fde37762975
bigcode/the-stack
train
8c31d03864a5010389fcd81c
train
class
class PILColorTransform(ColorTransform): """ Generic wrapper for PIL Photometric image transforms, which affect the color space and not the coordinate space of the image """ def __init__(self, op): """ Args: op (Callable): operation to be applied to the image...
class PILColorTransform(ColorTransform):
""" Generic wrapper for PIL Photometric image transforms, which affect the color space and not the coordinate space of the image """ def __init__(self, op): """ Args: op (Callable): operation to be applied to the image, which takes in a PIL Im...
self._set_attributes(locals()) def apply_image(self, img): return self.op(img) def apply_coords(self, coords): return coords def inverse(self): return NoOpTransform() def apply_segmentation(self, segmentation): return segmentation class PILColorTransform(ColorTransfo...
64
64
156
7
56
mmabrouk/detectron2
detectron2/data/transforms/transform.py
Python
PILColorTransform
PILColorTransform
282
304
282
282
13a20e9db130eb3334b2e80817976838ad157c12
bigcode/the-stack
train
002a7628a4ebdc64440bb917
train
function
def callMason(key): headers = {'authorization': "basic " + key} r = requests.get("https://api.staging.masonamerica.net/v1/default/device", headers=headers) j = r.json() for x in j["data"]: print("DeviceID: " + x["id"] + ", lastcheckin " + x["lastcheckin"])
def callMason(key):
headers = {'authorization': "basic " + key} r = requests.get("https://api.staging.masonamerica.net/v1/default/device", headers=headers) j = r.json() for x in j["data"]: print("DeviceID: " + x["id"] + ", lastcheckin " + x["lastcheckin"])
import sys import requests import json def callMason(key):
15
64
81
6
8
Grimkey/MasonPythonProto
mason.py
Python
callMason
callMason
5
11
5
5
459b446c1ddb273ae9c5b70818695b832c51ba84
bigcode/the-stack
train
9c296e026f20e6349b6ba566
train
class
class Solution: def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ dummy = None while(head): cur = head head = head.next cur.next = dummy dummy = cur return dummy
class Solution:
def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ dummy = None while(head): cur = head head = head.next cur.next = dummy dummy = cur return dummy
just use head = head.next. Use two pointers, one at the current node, one at the previous node. ''' # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution:
64
64
65
3
60
Awesomeyaya/Leetcode-Two-pointer
Linkedlist/Reverse Linked list #206.py
Python
Solution
Solution
17
29
17
17
87f92698563ff5cb9982f877d7945fa33d4de4d6
bigcode/the-stack
train
e828b372758a718c0abb2b3c
train
function
def PadImage(vol, padsize): dim = vol.shape padsize = np.asarray(padsize, dtype=int) dim2 = dim+2*padsize temp = np.zeros(dim2, dtype=float) temp[padsize:dim[0]+padsize, padsize:dim[1]+padsize, padsize:dim[2]+padsize] = vol return temp
def PadImage(vol, padsize):
dim = vol.shape padsize = np.asarray(padsize, dtype=int) dim2 = dim+2*padsize temp = np.zeros(dim2, dtype=float) temp[padsize:dim[0]+padsize, padsize:dim[1]+padsize, padsize:dim[2]+padsize] = vol return temp
time import strftime, time #import rotation #from rotation import rotateit from scipy.ndimage.interpolation import rotate import matplotlib.pyplot as plt import matplotlib.image as mpimg import sys #import tensorflow as tf #tf.compat.v1.enable_eager_execution() def PadImage(vol, padsize):
64
64
91
8
56
CoreyB33/tbi_ct_lesion_segmentation
utils/patch_ops.py
Python
PadImage
PadImage
21
29
21
21
db5cfd3afaa18750a8ce7d1d749ff62d81e0ce8f
bigcode/the-stack
train
12ab4bfcb5c00c0c2eb70b40
train
function
def CreatePatchesForTraining(atlasdir, plane, patchsize, max_patch=150000, num_channels=1): ''' Params: - TODO - healthy: bool, False if not going over the healthy dataset, true otherwise ''' # get filenames # Adding in flair patch t1_names = os.listdir(atlasdir) flair_nam...
def CreatePatchesForTraining(atlasdir, plane, patchsize, max_patch=150000, num_channels=1):
''' Params: - TODO - healthy: bool, False if not going over the healthy dataset, true otherwise ''' # get filenames # Adding in flair patch t1_names = os.listdir(atlasdir) flair_names = os.listdir(atlasdir) mask_names = os.listdir(atlasdir) t1_names = [x for x in ...
0]: I + dsize[0], # J - dsize[1]:J + dsize[1], # K] # MaskPatch_unrotated=MaskPatch_unrotated.astype('float64') # MaskPatch_rotated=rotate(MaskPatch_unrotated,a,reshape=False,mode='nearest') # MaskPatch_rotated=M...
256
256
1,452
26
229
CoreyB33/tbi_ct_lesion_segmentation
utils/patch_ops.py
Python
CreatePatchesForTraining
CreatePatchesForTraining
382
518
382
382
d515a84483c6b3c2db8f0fc0ceccf1253db3872f
bigcode/the-stack
train
b16a0710551227734f800037
train
function
def get_center_coords(ct, mask, ratio): ''' Gets coordinates for center pixel of all patches. Params: - ct: 3D ndarray, image data from which to find healthy coordinates - mask: 3D ndarray, image data from which to find coordinates - ratio: float in [0,1]. If 0 or 1...
def get_center_coords(ct, mask, ratio):
''' Gets coordinates for center pixel of all patches. Params: - ct: 3D ndarray, image data from which to find healthy coordinates - mask: 3D ndarray, image data from which to find coordinates - ratio: float in [0,1]. If 0 or 1, skip intersection calculation for spee...
b_reformat = [(x, y, z) for x, y, z in zip(b[0], b[1], b[2])] elif len(a) == 2: a_reformat = [(x, y) for x, y in zip(a[0], a[1])] b_reformat = [(x, y) for x, y in zip(b[0], b[1])] else: # TODO: proper error handling print("Shape mismatch") intersection = set(a_reformat) & s...
153
153
511
10
142
CoreyB33/tbi_ct_lesion_segmentation
utils/patch_ops.py
Python
get_center_coords
get_center_coords
67
112
67
67
44d834666d913c77e67a7f48f7fcd0d5b3c1af09
bigcode/the-stack
train
6ed2bce5b3e93d549ae216d8
train
function
def get_intersection(a, b): ''' Gets intersection of coordinate arrays a and b returned from np.nonzero()-style functions. Used to find valid centers for healthy patches. TODO: CURRENTLY ONLY WORKS ON 3D ARRAYS Params: - a: tuple of N np.arrays, where N is the dimension of the original ima...
def get_intersection(a, b):
''' Gets intersection of coordinate arrays a and b returned from np.nonzero()-style functions. Used to find valid centers for healthy patches. TODO: CURRENTLY ONLY WORKS ON 3D ARRAYS Params: - a: tuple of N np.arrays, where N is the dimension of the original image - b: tuple of N n...
.compat.v1.enable_eager_execution() def PadImage(vol, padsize): dim = vol.shape padsize = np.asarray(padsize, dtype=int) dim2 = dim+2*padsize temp = np.zeros(dim2, dtype=float) temp[padsize:dim[0]+padsize, padsize:dim[1]+padsize, padsize:dim[2]+padsize] = vol return temp def g...
107
107
359
8
98
CoreyB33/tbi_ct_lesion_segmentation
utils/patch_ops.py
Python
get_intersection
get_intersection
32
64
32
32
0402ee001ce1690731ff24f2ad08e6b89bebbe37
bigcode/the-stack
train
7b277a8a95cabe7b5edf7258
train
function
def get_patches(invols, mask, patchsize, maxpatch, num_channels): rng = random.SystemRandom() mask = np.asarray(mask, dtype=np.float32) patch_size = np.asarray(patchsize, dtype=int) dsize = np.floor(patchsize/2).astype(dtype=int) # find indices of all lesions in mask volume mask_lesion_indices...
def get_patches(invols, mask, patchsize, maxpatch, num_channels):
rng = random.SystemRandom() mask = np.asarray(mask, dtype=np.float32) patch_size = np.asarray(patchsize, dtype=int) dsize = np.floor(patchsize/2).astype(dtype=int) # find indices of all lesions in mask volume mask_lesion_indices = np.nonzero(mask) mask_lesion_indices = np.asarray(mask_lesi...
0, 0), (0, 0, 0), } # mask lesion patches lesion_coords = np.nonzero(mask) # cuurently only works for 3D input images lesion_coords = [(x, y, z) for x, y, z in zip(lesion_coords[0], lesion_coords[1], ...
256
256
3,029
19
236
CoreyB33/tbi_ct_lesion_segmentation
utils/patch_ops.py
Python
get_patches
get_patches
115
379
115
115
9bacabac23be202bd1b243242049e52a65edc4c0
bigcode/the-stack
train
e4729f17c066c261d5956029
train
function
def _tpu_host_device_name(job, task): """Returns the device name for the CPU device on `task` of `job`.""" if job is None: return "/task:%d/device:CPU:0" % task else: return "/job:%s/task:%d/device:CPU:0" % (job, task)
def _tpu_host_device_name(job, task):
"""Returns the device name for the CPU device on `task` of `job`.""" if job is None: return "/task:%d/device:CPU:0" % task else: return "/job:%s/task:%d/device:CPU:0" % (job, task)
.""" if job is None: return "/task:%d/device:TPU:%d" % (task, device) else: return "/job:%s/task:%d/device:TPU:%d" % (job, task, device) def _tpu_host_device_name(job, task):
64
64
75
11
53
chuanqi129/tensorflow
tensorflow/python/tpu/topology.py
Python
_tpu_host_device_name
_tpu_host_device_name
35
40
35
35
194f5304d730f249b3d771d275c0bf3aa025ae0f
bigcode/the-stack
train
ffb23058face4150e3f7a6a8
train
function
def _tpu_device_name(job, task, device): """Returns the device name for the TPU `device` on `task` of `job`.""" if job is None: return "/task:%d/device:TPU:%d" % (task, device) else: return "/job:%s/task:%d/device:TPU:%d" % (job, task, device)
def _tpu_device_name(job, task, device):
"""Returns the device name for the TPU `device` on `task` of `job`.""" if job is None: return "/task:%d/device:TPU:%d" % (task, device) else: return "/job:%s/task:%d/device:TPU:%d" % (job, task, device)
future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from six.moves import xrange # pylint: disable=redefined-builtin from tensorflow.core.protobuf.tpu import topology_pb2 def _tpu_device_name(job, task, device):
64
64
85
12
51
chuanqi129/tensorflow
tensorflow/python/tpu/topology.py
Python
_tpu_device_name
_tpu_device_name
27
32
27
27
b2c821259be686b399d20c6c22ffa80a3d4cfd69
bigcode/the-stack
train
11bf4ac1252a112e46270905
train
class
class Topology(object): """Describes a set of TPU devices. Represents both the shape of the physical mesh, and the mapping between TensorFlow TPU devices to physical mesh coordinates. """ def __init__(self, serialized=None, mesh_shape=None, device_coordinates=None): """Builds a Topology object. If ...
class Topology(object):
"""Describes a set of TPU devices. Represents both the shape of the physical mesh, and the mapping between TensorFlow TPU devices to physical mesh coordinates. """ def __init__(self, serialized=None, mesh_shape=None, device_coordinates=None): """Builds a Topology object. If `serialized` is not `Non...
. # See the License for the specific language governing permissions and # limitations under the License. # ====================================== """Defines the `Topology` class, that describes a TPU fabric topology.""" from __future__ import absolute_import from __future__ import division from __future__ import print...
256
256
1,784
5
251
chuanqi129/tensorflow
tensorflow/python/tpu/topology.py
Python
Topology
Topology
43
233
43
43
5d183fe606fff67225abfd0970b433ec6d9f1ca3
bigcode/the-stack
train
b77d10db3a28fb9543edf7b6
train
function
@app.command() def run() -> None: """Loop eternally and run schedulers at configured times.""" for s in ALL_SCHEDULERS: job = getattr(schedule.every(s.period), s.time_unit) if s.at: job = job.at(s.at) job.do(s).tag(s.name) log.info("Starting Schedule") for j in schedu...
@app.command() def run() -> None:
"""Loop eternally and run schedulers at configured times.""" for s in ALL_SCHEDULERS: job = getattr(schedule.every(s.period), s.time_unit) if s.at: job = job.at(s.at) job.do(s).tag(s.name) log.info("Starting Schedule") for j in schedule.jobs: log.info("%s: %s"...
language governing permissions and # limitations under the License. import logging from time import sleep import schedule import typer from orchestrator.schedules import ALL_SCHEDULERS log = logging.getLogger(__name__) app: typer.Typer = typer.Typer() @app.command() def run() -> None:
64
64
132
9
55
Georgi2704/orchestrator-core
orchestrator/cli/scheduler.py
Python
run
run
28
43
28
29
e2dc9773c766092e6d7dccfbff8d145c4f7c99b2
bigcode/the-stack
train
4016126b27a42962b4729f0e
train
function
@app.command() def force(keyword: str) -> None: """Force the execution of (a) scheduler(s) based on a keyword.""" for s in ALL_SCHEDULERS: if keyword in s.name or keyword in s.__name__: s()
@app.command() def force(keyword: str) -> None:
"""Force the execution of (a) scheduler(s) based on a keyword.""" for s in ALL_SCHEDULERS: if keyword in s.name or keyword in s.__name__: s()
ALL_SCHEDULERS: at_str = f"@ {s.at} " if s.at else "" typer.echo(f"{s.name}: {s.__name__} {at_str}every {s.period} {s.time_unit}") @app.command() def force(keyword: str) -> None:
63
64
56
12
51
Georgi2704/orchestrator-core
orchestrator/cli/scheduler.py
Python
force
force
54
59
54
55
1458d2b37cff8fd54c5d905f24ee64f44a7f979f
bigcode/the-stack
train
543c72d9a28fb1c097cc0b51
train
function
@app.command() def show_schedule() -> None: """Show the currently configured schedule.""" for s in ALL_SCHEDULERS: at_str = f"@ {s.at} " if s.at else "" typer.echo(f"{s.name}: {s.__name__} {at_str}every {s.period} {s.time_unit}")
@app.command() def show_schedule() -> None:
"""Show the currently configured schedule.""" for s in ALL_SCHEDULERS: at_str = f"@ {s.at} " if s.at else "" typer.echo(f"{s.name}: {s.__name__} {at_str}every {s.period} {s.time_unit}")
schedule.jobs: log.info("%s: %s", ", ".join(j.tags), j) while True: schedule.run_pending() idle = schedule.idle_seconds() log.info("Sleeping for %d seconds", idle) sleep(idle) @app.command() def show_schedule() -> None:
64
64
73
10
54
Georgi2704/orchestrator-core
orchestrator/cli/scheduler.py
Python
show_schedule
show_schedule
46
51
46
47
3bfc673f244b29cccd35063d392ae3f182023d36
bigcode/the-stack
train
b08328da0284ab78a450557d
train
class
class _BaseRequestContextManager(Coroutine[Any, Any, _RetType], Generic[_RetType]): __slots__ = ('_coro', '_resp') def __init__( self, coro: Coroutine['asyncio.Future[...
class _BaseRequestContextManager(Coroutine[Any, Any, _RetType], Generic[_RetType]):
__slots__ = ('_coro', '_resp') def __init__( self, coro: Coroutine['asyncio.Future[Any]', None, _RetType] ) -> None: self._coro = coro def send(self, arg: None) -> 'asyncio.Future[Any]': return self._coro.send(arg) def throw(self, arg: BaseException) -> Non...
__aexit__(self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType]) -> None: await self.close() class _BaseRequestContextManager(Coroutine[Any, ...
70
70
236
26
44
ods/aiohttp
aiohttp/client.py
Python
_BaseRequestContextManager
_BaseRequestContextManager
902
933
902
906
33fbc0b1e8ef5a82b38a7f805dc3df73c990df1d
bigcode/the-stack
train
7c1d4148fd7c1cf944965fca
train
class
class _WSRequestContextManager(_BaseRequestContextManager[ ClientWebSocketResponse]): async def __aexit__(self, exc_type: Optional[Type[BaseException]], exc: Optional[BaseException], tb: Optional[TracebackType]) -> None: await s...
class _WSRequestContextManager(_BaseRequestContextManager[ ClientWebSocketResponse]):
async def __aexit__(self, exc_type: Optional[Type[BaseException]], exc: Optional[BaseException], tb: Optional[TracebackType]) -> None: await self._resp.close()
If you # would like to close a connection you must do that # explicitly. Otherwise connection error handling should kick in # and close/recycle the connection as required. self._resp.release() class _WSRequestContextManager(_BaseRequestContextManager[ ClientWebSocketResponse]):...
64
64
65
18
46
ods/aiohttp
aiohttp/client.py
Python
_WSRequestContextManager
_WSRequestContextManager
949
955
949
950
ab0637c9d910bd67861114124073a825f81f82ae
bigcode/the-stack
train
545b5e366259ca22a27d087b
train
class
class ClientSession: """First-class interface for making HTTP requests.""" ATTRS = frozenset([ '_source_traceback', '_connector', 'requote_redirect_url', '_loop', '_cookie_jar', '_connector_owner', '_default_auth', '_version', '_json_serialize', '_requote_redirect_url', ...
class ClientSession:
"""First-class interface for making HTTP requests.""" ATTRS = frozenset([ '_source_traceback', '_connector', 'requote_redirect_url', '_loop', '_cookie_jar', '_connector_owner', '_default_auth', '_version', '_json_serialize', '_requote_redirect_url', '_timeout', '...
SSLContext = object # type: ignore @attr.s(frozen=True, slots=True) class ClientTimeout: total = attr.ib(type=float, default=None) connect = attr.ib(type=float, default=None) sock_read = attr.ib(type=float, default=None) sock_connect = attr.ib(type=float, default=None) # pool_queue_timeout = at...
256
256
5,837
4
252
ods/aiohttp
aiohttp/client.py
Python
ClientSession
ClientSession
85
899
85
85
33001708296d472d91e55781804bfad9475ac4b9
bigcode/the-stack
train
7541d79db0d6a3906ca2138d
train
function
def request( method: str, url: StrOrURL, *, params: Optional[Mapping[str, str]]=None, data: Any=None, json: Any=None, headers: LooseHeaders=None, skip_auto_headers: Optional[Iterable[str]]=None, auth: Optional[BasicAuth]=None, allow_redirects: bool...
def request( method: str, url: StrOrURL, *, params: Optional[Mapping[str, str]]=None, data: Any=None, json: Any=None, headers: LooseHeaders=None, skip_auto_headers: Optional[Iterable[str]]=None, auth: Optional[BasicAuth]=None, allow_redirects: bool...
"""Constructs and sends a request. Returns response object. method - HTTP method url - request url params - (optional) Dictionary or bytes to be sent in the query string of the new request data - (optional) Dictionary, bytes, or file-like object to send in the body of the request jso...
def request( method: str, url: StrOrURL, *, params: Optional[Mapping[str, str]]=None, data: Any=None, json: Any=None, headers: LooseHeaders=None, skip_auto_headers: Optional[Iterable[str]]=None, auth: Optional[BasicAuth]=None, allow_redirects: bool...
217
217
726
217
0
ods/aiohttp
aiohttp/client.py
Python
request
request
982
1,066
982
1,005
af18c314a09c6cba5c9d3176f9f9232f67699f89
bigcode/the-stack
train
943a632ba4a1617f5a1fecc5
train
class
class _RequestContextManager(_BaseRequestContextManager[ClientResponse]): async def __aexit__(self, exc_type: Optional[Type[BaseException]], exc: Optional[BaseException], tb: Optional[TracebackType]) -> None: # We're basing behavior on ...
class _RequestContextManager(_BaseRequestContextManager[ClientResponse]):
async def __aexit__(self, exc_type: Optional[Type[BaseException]], exc: Optional[BaseException], tb: Optional[TracebackType]) -> None: # We're basing behavior on the exception as it can be caused by # user code unrelated to the ...
__(self) -> Generator[Any, None, _RetType]: return self.__await__() async def __aenter__(self) -> _RetType: self._resp = await self._coro return self._resp class _RequestContextManager(_BaseRequestContextManager[ClientResponse]):
64
64
129
14
49
ods/aiohttp
aiohttp/client.py
Python
_RequestContextManager
_RequestContextManager
936
946
936
936
94affb213229c13ac58ca93831abda01d2100b60
bigcode/the-stack
train
fc9f2cc593dba1a89bc4d705
train
class
@attr.s(frozen=True, slots=True) class ClientTimeout: total = attr.ib(type=float, default=None) connect = attr.ib(type=float, default=None) sock_read = attr.ib(type=float, default=None) sock_connect = attr.ib(type=float, default=None)
@attr.s(frozen=True, slots=True) class ClientTimeout:
total = attr.ib(type=float, default=None) connect = attr.ib(type=float, default=None) sock_read = attr.ib(type=float, default=None) sock_connect = attr.ib(type=float, default=None)
('ClientSession', 'ClientTimeout', 'ClientWebSocketResponse', 'request')) try: from ssl import SSLContext except ImportError: # pragma: no cover SSLContext = object # type: ignore @attr.s(frozen=True, slots=True) class ClientTimeout:
64
64
60
14
49
ods/aiohttp
aiohttp/client.py
Python
ClientTimeout
ClientTimeout
58
63
58
59
f3f7a047f874b4ecb1e3268caac2761faa5311c0
bigcode/the-stack
train
7b6ef10198c1a51aeef9824c
train
class
class _SessionRequestContextManager: __slots__ = ('_coro', '_resp', '_session') def __init__(self, coro: Coroutine['asyncio.Future[Any]', None, ClientResponse], session: ClientSession) -> None: self._coro = coro self._resp = None # type: Optional[ClientRespon...
class _SessionRequestContextManager:
__slots__ = ('_coro', '_resp', '_session') def __init__(self, coro: Coroutine['asyncio.Future[Any]', None, ClientResponse], session: ClientSession) -> None: self._coro = coro self._resp = None # type: Optional[ClientResponse] self._session = session ...
RequestContextManager[ ClientWebSocketResponse]): async def __aexit__(self, exc_type: Optional[Type[BaseException]], exc: Optional[BaseException], tb: Optional[TracebackType]) -> None: await self._resp.close() class _SessionRequ...
64
64
176
7
57
ods/aiohttp
aiohttp/client.py
Python
_SessionRequestContextManager
_SessionRequestContextManager
958
979
958
959
a81d45fdc388b84f2f3943e82639c076c2875ba8
bigcode/the-stack
train
e491a534c40b0f38c1cecd37
train
function
@api_view(['GET']) def api_overview(request): api_urls = { 'View All Movies': '/api/movies/', 'View All Genres': '/api/genres/', 'SingleMo detail': '/api/movie/<id>', 'Search by movie': '/api/movies?search=<movie-name>', 'Search by genre': '/api/movies?search=<genre-name>', ...
@api_view(['GET']) def api_overview(request):
api_urls = { 'View All Movies': '/api/movies/', 'View All Genres': '/api/genres/', 'SingleMo detail': '/api/movie/<id>', 'Search by movie': '/api/movies?search=<movie-name>', 'Search by genre': '/api/movies?search=<genre-name>', 'Search by field': '/api/movies?search=...
ListAPIView from rest_framework.pagination import PageNumberPagination, LimitOffsetPagination from rest_framework.filters import SearchFilter, OrderingFilter from .serializers import MovieSerializer, GenreSerializer from .models import Movie, Genre # Create your views here. @api_view(['GET']) def api_overview(reque...
64
64
154
12
52
subhakr11droy/IMDB-API
api/views.py
Python
api_overview
api_overview
15
28
15
16
16b4ad0c4b1e5fc7b44bcaa9b007086a9202844c
bigcode/the-stack
train
a98fb062345ea1bc1d4f7561
train
class
class GenreListView(ListAPIView): queryset = Genre.objects.all() serializer_class = GenreSerializer pagination_class = LimitOffsetPagination filter_backends = [OrderingFilter] search_fields = ['name']
class GenreListView(ListAPIView):
queryset = Genre.objects.all() serializer_class = GenreSerializer pagination_class = LimitOffsetPagination filter_backends = [OrderingFilter] search_fields = ['name']
queryset = Movie.objects.all() serializer_class = MovieSerializer pagination_class = LimitOffsetPagination filter_backends = (SearchFilter, OrderingFilter) search_fields = ['name', 'director', 'popularity', 'imdb_score', 'genre__name'] class GenreListView(ListAPIView):
64
64
45
7
57
subhakr11droy/IMDB-API
api/views.py
Python
GenreListView
GenreListView
66
71
66
66
6ab8f64378b42a766458ffed880b25b08997aa7d
bigcode/the-stack
train
556858de40ade43164268ed8
train
function
@api_view(['GET']) def movie_list(request): movies = Movie.objects.all() serializer = MovieSerializer(movies, many=True) return Response(serializer.data)
@api_view(['GET']) def movie_list(request):
movies = Movie.objects.all() serializer = MovieSerializer(movies, many=True) return Response(serializer.data)
Search with Pagination ': '/api/movies?search=<movie-name>&limit=<#>', 'Search with multi-field': '/api/movies?search=<movie-name>,<director-name>,<genre-name>,...', } return Response(api_urls) @api_view(['GET']) def movie_list(request):
64
64
35
11
53
subhakr11droy/IMDB-API
api/views.py
Python
movie_list
movie_list
31
35
31
32
53f6219ab3f83ca35fbd0accb3285bd87712e536
bigcode/the-stack
train
939605a24a002c08f3f2e162
train
function
@api_view(['GET']) def movie_details(request, id): movies = Movie.objects.get(pk=id) serializer = MovieSerializer(movies, many=False) return Response(serializer.data)
@api_view(['GET']) def movie_details(request, id):
movies = Movie.objects.get(pk=id) serializer = MovieSerializer(movies, many=False) return Response(serializer.data)
serializer = MovieSerializer(movies, many=True) return Response(serializer.data) @api_view(['GET']) def genre_list(request): genres = Genre.objects.all() serializer = GenreSerializer(genres, many=True) return Response(serializer.data) @api_view(['GET']) def movie_details(request, id):
64
64
39
13
51
subhakr11droy/IMDB-API
api/views.py
Python
movie_details
movie_details
45
49
45
46
b0c7543ef7aea3f2f129cbdd5709fba91d62c38b
bigcode/the-stack
train
d4babf95b0ad6a42c4b54160
train
function
@api_view(['GET']) def genre_list(request): genres = Genre.objects.all() serializer = GenreSerializer(genres, many=True) return Response(serializer.data)
@api_view(['GET']) def genre_list(request):
genres = Genre.objects.all() serializer = GenreSerializer(genres, many=True) return Response(serializer.data)
<director-name>,<genre-name>,...', } return Response(api_urls) @api_view(['GET']) def movie_list(request): movies = Movie.objects.all() serializer = MovieSerializer(movies, many=True) return Response(serializer.data) @api_view(['GET']) def genre_list(request):
64
64
35
11
53
subhakr11droy/IMDB-API
api/views.py
Python
genre_list
genre_list
38
42
38
39
662594aa1c64b541b2b2366c9bf5dd150c881c9d
bigcode/the-stack
train
f7759a81bcafda6ca677480b
train
class
class MovieListView(ListAPIView): queryset = Movie.objects.all() serializer_class = MovieSerializer pagination_class = LimitOffsetPagination filter_backends = (SearchFilter, OrderingFilter) search_fields = ['name', 'director', 'popularity', 'imdb_score', 'genre__name']
class MovieListView(ListAPIView):
queryset = Movie.objects.all() serializer_class = MovieSerializer pagination_class = LimitOffsetPagination filter_backends = (SearchFilter, OrderingFilter) search_fields = ['name', 'director', 'popularity', 'imdb_score', 'genre__name']
GET']) def movie_details(request, id): movies = Movie.objects.get(pk=id) serializer = MovieSerializer(movies, many=False) return Response(serializer.data) ''' Using default search filter makes all this CRUD operations trivial API using search filter implementation ''' class MovieListView(ListAPIVi...
63
64
65
7
56
subhakr11droy/IMDB-API
api/views.py
Python
MovieListView
MovieListView
58
63
58
58
efd80f762e4e7b05cdb70f4cfa9468642b6b4a05
bigcode/the-stack
train
9346022b0915c449c2892d9f
train
function
def parent() -> object: return gui.ElectrumGui.gui
def parent() -> object:
return gui.ElectrumGui.gui
.culianu@gmail.com> # # MIT License # from . import utils from . import gui from oregano.i18n import _, language from .uikit_bindings import * from .custom_objc import * from collections import namedtuple from oregano import bitcoin def parent() -> object:
64
64
15
6
57
MrNaif2018/Oregano
ios/ElectronCash/oregano_gui/ios_native/private_key_dialog.py
Python
parent
parent
15
16
15
15
813547edaa82925bc97929e41f65b1cd15b25423
bigcode/the-stack
train
5a63b3170d6a713bfd27fb6e
train
class
class PrivateKeyDialog(PrivateKeyDialogBase): @objc_method def init(self) -> ObjCInstance: self = ObjCInstance(send_super(__class__, self, 'init')) self.title = _("Private Key") return self @objc_method def dealloc(self) -> None: utils.nspy_pop(self) ...
class PrivateKeyDialog(PrivateKeyDialogBase): @objc_method
def init(self) -> ObjCInstance: self = ObjCInstance(send_super(__class__, self, 'init')) self.title = _("Private Key") return self @objc_method def dealloc(self) -> None: utils.nspy_pop(self) send_super(__class__, self, 'dealloc') @objc_method def lo...
# # This file is: # Copyright (C) 2018 Calin Culianu <calin.culianu@gmail.com> # # MIT License # from . import utils from . import gui from oregano.i18n import _, language from .uikit_bindings import * from .custom_objc import * from collections import namedtuple from oregano import bitcoin def parent() -> object:...
133
226
756
16
117
MrNaif2018/Oregano
ios/ElectronCash/oregano_gui/ios_native/private_key_dialog.py
Python
PrivateKeyDialog
PrivateKeyDialog
20
102
20
22
34284391dfd8e16b2e8480bdedf01cf70fe417ca
bigcode/the-stack
train
0c26828bc3b524ff04dc923d
train
function
def on_course_publish(course_key): """ Will receive a delegated 'course_published' signal from cms/djangoapps/contentstore/signals.py and kick off a celery task to update the credit course requirements. IMPORTANT: It is assumed that the edx-proctoring subsystem has been appropriate refreshed with a...
def on_course_publish(course_key):
""" Will receive a delegated 'course_published' signal from cms/djangoapps/contentstore/signals.py and kick off a celery task to update the credit course requirements. IMPORTANT: It is assumed that the edx-proctoring subsystem has been appropriate refreshed with any on_publish event workflow *BEFOR...
receivers of course publication signals. """ import logging from django.dispatch import receiver from django.utils import timezone from opaque_keys.edx.keys import CourseKey from openedx.core.djangoapps.signals.signals import COURSE_GRADE_CHANGED log = logging.getLogger(__name__) def on_course_publish(course_key)...
64
64
167
7
57
osoco/better-ways-of-thinking-about-software
Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/openedx/core/djangoapps/credit/signals.py
Python
on_course_publish
on_course_publish
17
32
17
17
327ef3af5230c4c315a49e14b29168424344d67b
bigcode/the-stack
train
6348450624b0c3302abc4d6b
train
function
@receiver(COURSE_GRADE_CHANGED) def listen_for_grade_calculation(sender, user, course_grade, course_key, deadline, **kwargs): # pylint: disable=unused-argument """Receive 'MIN_GRADE_REQUIREMENT_STATUS' signal and update minimum grade requirement status. Args: sender: None user(User): User Mode...
@receiver(COURSE_GRADE_CHANGED) def listen_for_grade_calculation(sender, user, course_grade, course_key, deadline, **kwargs): # pylint: disable=unused-argument
"""Receive 'MIN_GRADE_REQUIREMENT_STATUS' signal and update minimum grade requirement status. Args: sender: None user(User): User Model object course_grade(CourseGrade): CourseGrade object course_key(CourseKey): The key for the course deadline(datetime): Course end date ...
event workflow *BEFORE* this method is called. """ # Import here, because signal is registered at startup, but items in tasks # are not yet able to be loaded from openedx.core.djangoapps.credit import api, tasks if api.is_credit_course(course_key): tasks.update_credit_course_requirements....
138
138
462
40
98
osoco/better-ways-of-thinking-about-software
Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/openedx/core/djangoapps/credit/signals.py
Python
listen_for_grade_calculation
listen_for_grade_calculation
35
96
35
36
165671267805a04da4b55c244cfaf00ed1a248cc
bigcode/the-stack
train
2474eabbafb7c99bc7604227
train
function
def resize(image, output_shape, order=1, mode='constant', cval=0, clip=True, preserve_range=False, anti_aliasing=False, anti_aliasing_sigma=None): """A wrapper for Scikit-Image resize(). Scikit-Image generates warnings on every call to resize() if it doesn't receive the right parameters. The righ...
def resize(image, output_shape, order=1, mode='constant', cval=0, clip=True, preserve_range=False, anti_aliasing=False, anti_aliasing_sigma=None):
"""A wrapper for Scikit-Image resize(). Scikit-Image generates warnings on every call to resize() if it doesn't receive the right parameters. The right parameters depend on the version of skimage. This solves the problem by using different parameters per version. And it provides a central place to c...
1, 1]) return np.around(np.multiply(boxes, scale) + shift).astype(np.int32) def resize(image, output_shape, order=1, mode='constant', cval=0, clip=True, preserve_range=False, anti_aliasing=False, anti_aliasing_sigma=None):
64
64
189
39
25
ruihan0495/EfficientDet
utils/helper.py
Python
resize
resize
33
46
33
34
afea08f307eccc94260892b89f6061b4cc2af0e6
bigcode/the-stack
train
585fe64545a6c6a0b8393ce9
train
function
def denorm_boxes(boxes, shape): """Converts boxes from normalized coordinates to pixel coordinates. boxes: [N, (y1, x1, y2, x2)] in normalized coordinates shape: [..., (height, width)] in pixels Note: In pixel coordinates (y2, x2) is outside the box. But in normalized coordinates it's inside the box...
def denorm_boxes(boxes, shape):
"""Converts boxes from normalized coordinates to pixel coordinates. boxes: [N, (y1, x1, y2, x2)] in normalized coordinates shape: [..., (height, width)] in pixels Note: In pixel coordinates (y2, x2) is outside the box. But in normalized coordinates it's inside the box. Returns: [N, (y1, ...
.array([h - 1, w - 1, h - 1, w - 1]) shift = np.array([0, 0, 1, 1]) return np.divide((boxes - shift), scale).astype(np.float32) def denorm_boxes(boxes, shape):
64
64
182
9
55
ruihan0495/EfficientDet
utils/helper.py
Python
denorm_boxes
denorm_boxes
19
31
19
19
09684f585437adcfe5490f99bb02ebd7dfbb3df9
bigcode/the-stack
train
d29aa12eea35abf1f74a7245
train
function
def norm_boxes(boxes, shape): """Converts boxes from pixel coordinates to normalized coordinates. boxes: [N, (y1, x1, y2, x2)] in pixel coordinates shape: [..., (height, width)] in pixels Note: In pixel coordinates (y2, x2) is outside the box. But in normalized coordinates it's inside the box. R...
def norm_boxes(boxes, shape):
"""Converts boxes from pixel coordinates to normalized coordinates. boxes: [N, (y1, x1, y2, x2)] in pixel coordinates shape: [..., (height, width)] in pixels Note: In pixel coordinates (y2, x2) is outside the box. But in normalized coordinates it's inside the box. Returns: [N, (y1, x1, y...
import skimage.transform import numpy as np def norm_boxes(boxes, shape):
18
64
177
8
9
ruihan0495/EfficientDet
utils/helper.py
Python
norm_boxes
norm_boxes
4
16
4
4
f5afb65c2f89176dfc6230f5086cb32e730ec1ef
bigcode/the-stack
train
e0c5058f94e4c2371f8b3544
train
function
def genclass(n): classes = ['1000', '1100', '1110', '1101', '1010', '1001', '1011', '1111', '0100', '0110', '0101', '0111', '0010', '0011', '0001', '0000'] people = [] for i in range(n): people.append(random.choice(classes)) return people
def genclass(n):
classes = ['1000', '1100', '1110', '1101', '1010', '1001', '1011', '1111', '0100', '0110', '0101', '0111', '0010', '0011', '0001', '0000'] people = [] for i in range(n): people.append(random.choice(classes)) return people
sd = 0.1 # Checks if array *i* is equal to one at index *n* # Used to check the class information of our driver def checker(i,n): if i[n] == '1': return 1 else: return 0 def genclass(n):
64
64
93
5
58
wfurine/htdrive
datagen.py
Python
genclass
genclass
58
63
58
58
999e2a8eded2eb7eac7a2176c06be1668bab2e37
bigcode/the-stack
train
c57d24e96c19931c319afca5
train
function
def checker(i,n): if i[n] == '1': return 1 else: return 0
def checker(i,n):
if i[n] == '1': return 1 else: return 0
0, 0, 0], [0, 0, 0, 0]]]) sd = 0.1 # Checks if array *i* is equal to one at index *n* # Used to check the class information of our driver def checker(i,n):
64
64
25
5
58
wfurine/htdrive
datagen.py
Python
checker
checker
52
56
52
52
0ad45ce57f2324a6a9ea95e42e61b69929771611
bigcode/the-stack
train
4432f961596d225fe71f65f4
train
function
def function(n, betas=betas_list, beta_weight=1): final = [] mylist = genclass(n) a = 0 # create numpy array to store actual classes # array with shape ([class], 4) classes_actual = numpy.zeros(shape=(n, 4)) for i in mylist: ovr = [] for j in range(9): values = [random.gauss(0, sd), random.gauss(0, ...
def function(n, betas=betas_list, beta_weight=1):
final = [] mylist = genclass(n) a = 0 # create numpy array to store actual classes # array with shape ([class], 4) classes_actual = numpy.zeros(shape=(n, 4)) for i in mylist: ovr = [] for j in range(9): values = [random.gauss(0, sd), random.gauss(0, sd), random.gauss(0, sd), random.gauss(0, s...
): classes = ['1000', '1100', '1110', '1101', '1010', '1001', '1011', '1111', '0100', '0110', '0101', '0111', '0010', '0011', '0001', '0000'] people = [] for i in range(n): people.append(random.choice(classes)) return people def function(n, betas=betas_list, beta_weight=1):
105
105
351
16
88
wfurine/htdrive
datagen.py
Python
function
function
67
105
67
67
ba5b254860807f8edacd63adc458b276a00b06e4
bigcode/the-stack
train
fec39c843b5b66b8865a72bd
train
function
def _pad_arrs_to_max_length(arrs, pad_val, use_shared_mem, dtype, round_to=None): """Inner Implementation of the Pad batchify Parameters ---------- arrs : list pad_val : number use_shared_mem : bool, default False round_to : int Returns ------- ret : NDArray """ _arr = _...
def _pad_arrs_to_max_length(arrs, pad_val, use_shared_mem, dtype, round_to=None):
"""Inner Implementation of the Pad batchify Parameters ---------- arrs : list pad_val : number use_shared_mem : bool, default False round_to : int Returns ------- ret : NDArray """ _arr = _np if is_np_array() else nd _arr_cls = _np.ndarray if is_np_array() else nd.ND...
_arr.stack(*data) elif isinstance(data[0], (tuple, list)): data = zip(*data) return [self.__call__(i) for i in data] else: out = np.asarray(data) dtype = out.dtype if self._use_shared_mem: return _arr.array(out, ctx=Device('cpu...
146
146
487
24
122
t-triobox/incubator-mxnet
python/mxnet/gluon/data/batchify.py
Python
_pad_arrs_to_max_length
_pad_arrs_to_max_length
104
154
104
104
825723a2b4d04f40f49789ec630d2c8a915920c4
bigcode/the-stack
train
188cfff71bd553c201803c05
train
class
class Append(object): r"""Loosely return list of the input data samples. There is no constraint of shape for any of the input samples, however, you will only be able to apply single batch operations since the output have different shapes. Examples -------- >>> a = [1, 2, 3, 4] >>> b = [4, 5,...
class Append(object):
r"""Loosely return list of the input data samples. There is no constraint of shape for any of the input samples, however, you will only be able to apply single batch operations since the output have different shapes. Examples -------- >>> a = [1, 2, 3, 4] >>> b = [4, 5, 6] >>> c = [8, 2]...
s] else: out = arrs else: if use_shared_mem: out = [_arr.array(x, ctx=Device('cpu_shared', 0)) for x in arrs] else: out = [_arr.array(x) for x in arrs] # add batch axis if expand: out = [x.expand_dims(axis=batch_axis) for x in out] ret...
95
95
318
4
90
t-triobox/incubator-mxnet
python/mxnet/gluon/data/batchify.py
Python
Append
Append
279
315
279
279
a9bd750d1f490cec85f4bfa361a3b1ff4dbafb80
bigcode/the-stack
train
f587220d4ba765e7f72aec93
train
class
class Pad(object): """Pad the input ndarrays along the specific padding axis and stack them to get the output. Input of the function will be N samples. Each sample should contain a single element that can be 1) numpy.ndarray, 2) mxnet.nd.NDArray, 3) list of numbers. You can set the `pad_val` to determin...
class Pad(object):
"""Pad the input ndarrays along the specific padding axis and stack them to get the output. Input of the function will be N samples. Each sample should contain a single element that can be 1) numpy.ndarray, 2) mxnet.nd.NDArray, 3) list of numbers. You can set the `pad_val` to determine the padding value...
_axis in range(len(ret_shape)): curr_lengths = [ele.shape[pad_axis] for ele in arrs] max_size = max(curr_lengths) if round_to is not None: max_size = round_to * math.ceil(max_size / round_to) ret_shape[pad_axis] = max_size ret_shape = (len(arrs), ) + tuple(ret_shape) ...
256
256
1,160
4
251
t-triobox/incubator-mxnet
python/mxnet/gluon/data/batchify.py
Python
Pad
Pad
157
257
157
157
f5818c00ea358f323a258f1eb796729477da71d3
bigcode/the-stack
train
219d31c7955534a53810e58d
train
function
def _append_arrs(arrs, use_shared_mem=False, expand=False, batch_axis=0): """Internal impl for returning appened arrays as list.""" _arr = _np if is_np_array() else nd if isinstance(arrs[0], _arr.NDArray): if use_shared_mem: out = [x.as_in_context(Device('cpu_shared', 0)) for x in arrs] ...
def _append_arrs(arrs, use_shared_mem=False, expand=False, batch_axis=0):
"""Internal impl for returning appened arrays as list.""" _arr = _np if is_np_array() else nd if isinstance(arrs[0], _arr.NDArray): if use_shared_mem: out = [x.as_in_context(Device('cpu_shared', 0)) for x in arrs] else: out = arrs else: if use_shared_mem: ...
mx_handle__(self): from ._internal import PadBatchify return PadBatchify(pad_val=self._pad_val, dtype=self._dtype if self._dtype is not None else -1) def _append_arrs(arrs, use_shared_mem=False, expand=False, batch_axis=0):
64
64
178
21
43
t-triobox/incubator-mxnet
python/mxnet/gluon/data/batchify.py
Python
_append_arrs
_append_arrs
259
276
259
259
6300bd0cfd79eee9c43f78b8a80f771cf36dda72
bigcode/the-stack
train
2598968a46042ca4a7783c7e
train
class
class Group(object): """Wrap multiple batchify functions together. The input functions will be applied to the corresponding input fields. Each data sample should be a list or tuple containing multiple attributes. The `i`th batchify function stored in `Group` will be applied on the `i`th attribute. For e...
class Group(object):
"""Wrap multiple batchify functions together. The input functions will be applied to the corresponding input fields. Each data sample should be a list or tuple containing multiple attributes. The `i`th batchify function stored in `Group` will be applied on the `i`th attribute. For example, each data...
>>> batchify.Append()([a, b, c]) [ [[1. 2. 3. 4.]] <NDArray 1x4 @cpu_shared(0)>, [[4. 5. 6.]] <NDArray 1x3 @cpu_shared(0)>, [[8. 2.]] <NDArray 1x2 @cpu_shared(0)> ] """ def __init__(self, expand=True, batch_axis=0, use_shared_mem=False): self._expand = expand se...
223
223
745
4
219
t-triobox/incubator-mxnet
python/mxnet/gluon/data/batchify.py
Python
Group
Group
317
389
317
317
0400f38c9fa802e757956aa984c52adb6b2f4a2d
bigcode/the-stack
train
c450553ac46ba407becdf6ba
train
class
class Stack(object): r"""Stack the input data samples to construct the batch. The N input samples must have the same shape/length and will be stacked to construct a batch. Examples -------- >>> from mxnet.gluon.data import batchify >>> # Stack multiple lists >>> a = [1, 2, 3, 4] >>> b = ...
class Stack(object):
r"""Stack the input data samples to construct the batch. The N input samples must have the same shape/length and will be stacked to construct a batch. Examples -------- >>> from mxnet.gluon.data import batchify >>> # Stack multiple lists >>> a = [1, 2, 3, 4] >>> b = [4, 5, 6, 8] >>> ...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
247
247
825
4
242
t-triobox/incubator-mxnet
python/mxnet/gluon/data/batchify.py
Python
Stack
Stack
30
102
30
30
c668ca7f2817563c25770378cba915186a01b969
bigcode/the-stack
train
0b52223d4d8873faa5394e25
train
class
class AsList(object): """Simply forward the list of input data. This is particularly useful when the Dataset contains textual data and in conjonction with the `Group` batchify function. Examples -------- >>> a = ([1, 2, 3, 4], "I am using MXNet") >>> b = ([5, 7, 2, 5], "Gluon rocks!") >>...
class AsList(object):
"""Simply forward the list of input data. This is particularly useful when the Dataset contains textual data and in conjonction with the `Group` batchify function. Examples -------- >>> a = ([1, 2, 3, 4], "I am using MXNet") >>> b = ([5, 7, 2, 5], "Gluon rocks!") >>> c = ([1, 2, 3, 4], "...
for fn in self._fn] self._handle = GroupBatchify(functions=mx_fn) except Exception as e: raise NotImplementedError( "GroupBatchify requires all internal batchify functions supported by backend." + str(e)) return self._handle cl...
64
64
205
5
58
t-triobox/incubator-mxnet
python/mxnet/gluon/data/batchify.py
Python
AsList
AsList
391
415
391
391
73ea8e7f944c1619bd8c93c33000885f12949630
bigcode/the-stack
train
7513330a87878b3d2a622cb3
train
class
class ValidateContentFetcherIsReady(object): """ Validates that anything that looks like a regex passes as a regex """ def __init__(self, message=None): self.message = message def __call__(self, form, field): from changedetectionio import content_fetcher import urllib3.exce...
class ValidateContentFetcherIsReady(object):
""" Validates that anything that looks like a regex passes as a regex """ def __init__(self, message=None): self.message = message def __call__(self, form, field): from changedetectionio import content_fetcher import urllib3.exceptions # Better would be a radiohand...
process_formdata(self, valuelist): if valuelist: self.data = {} # Remove empty strings cleaned = list(filter(None, valuelist[0].split("\n"))) for s in cleaned: parts = s.strip().split(":", 1) if len(parts) == 2: ...
104
105
352
8
96
Devv5G/TimCD
changedetectionio/forms.py
Python
ValidateContentFetcherIsReady
ValidateContentFetcherIsReady
106
147
106
106
77048243dad0d0c64260964ac8c46def4e2e1843
bigcode/the-stack
train
6001c6c520987af688584ba8
train
class
class watchForm(commonSettingsForm): url = html5.URLField("URL", [validators.URL(require_tld=False)]) tag = StringField("Group tag", [validators.Optional(), validators.Length(max=35)]) minutes_between_check = html5.IntegerField( "Maximum time in seconds until recheck.", [validators.Optiona...
class watchForm(commonSettingsForm):
url = html5.URLField("URL", [validators.URL(require_tld=False)]) tag = StringField("Group tag", [validators.Optional(), validators.Length(max=35)]) minutes_between_check = html5.IntegerField( "Maximum time in seconds until recheck.", [validators.Optional(), validators.NumberRange(min=1)], ...
Field( u"Fetch Method", choices=content_fetcher.available_fetchers(), validators=[ValidateContentFetcherIsReady()], ) extract_title_as_title = BooleanField( "Extract <title> from document and use as watch title", default=False ) class watchForm(commonSettingsForm):
64
64
157
7
57
Devv5G/TimCD
changedetectionio/forms.py
Python
watchForm
watchForm
277
293
277
278
71ad1c45ed81f8d7cd6c179fa561963ba9ab6f65
bigcode/the-stack
train
542e37731d865aab57ba2ca1
train
class
class ValidateCSSJSONInput(object): """ Filter validation @todo CSS validator ;) """ def __init__(self, message=None): self.message = message def __call__(self, form, field): if "json:" in field.data: from jsonpath_ng.exceptions import JsonPathParserError, JsonPathL...
class ValidateCSSJSONInput(object):
""" Filter validation @todo CSS validator ;) """ def __init__(self, message=None): self.message = message def __call__(self, form, field): if "json:" in field.data: from jsonpath_ng.exceptions import JsonPathParserError, JsonPathLexerError from jsonpath_...
internally we dont wrap in / line = line.strip("/") try: re.compile(line) except re.error: message = field.gettext( "RegEx '%s' is not a valid regular expression." ) r...
64
64
150
7
57
Devv5G/TimCD
changedetectionio/forms.py
Python
ValidateCSSJSONInput
ValidateCSSJSONInput
212
232
212
212
f7b3a66a4a05538d22c57c6685a841016d7046fb
bigcode/the-stack
train
3efcf07085f5b940a9bf0526
train
class
class ValidateAppRiseServers(object): """ Validates that each URL given is compatible with AppRise """ def __init__(self, message=None): self.message = message def __call__(self, form, field): import apprise apobj = apprise.Apprise() for server_url in field.data: ...
class ValidateAppRiseServers(object):
""" Validates that each URL given is compatible with AppRise """ def __init__(self, message=None): self.message = message def __call__(self, form, field): import apprise apobj = apprise.Apprise() for server_url in field.data: if not apobj.add(server_ur...
>' raise ValidationError(message) except Exception as e: message = field.gettext( "Content fetcher '%s' did not respond properly, unable to use it.\n %s" ) raise ValidationError(message % (field.data, e)) class ValidateApp...
64
64
115
7
57
Devv5G/TimCD
changedetectionio/forms.py
Python
ValidateAppRiseServers
ValidateAppRiseServers
150
168
150
150
f1be899f49eda409da8838659dde2881af1d5e9c
bigcode/the-stack
train
9f7fb7f0ff71feba9ac847a9
train
class
class StringDictKeyValue(StringField): widget = widgets.TextArea() def _value(self): if self.data: output = u"" for k in self.data.keys(): output += "{}: {}\r\n".format(k, self.data[k]) return output else: return u"" # incomi...
class StringDictKeyValue(StringField):
widget = widgets.TextArea() def _value(self): if self.data: output = u"" for k in self.data.keys(): output += "{}: {}\r\n".format(k, self.data[k]) return output else: return u"" # incoming def process_formdata(self, value...
-zero in length if len(valuelist[0].strip()) > 0: self.encrypted_password = self.build_password(valuelist[0]) self.data = "" else: self.data = False # Separated by key:value class StringDictKeyValue(StringField):
64
64
170
8
55
Devv5G/TimCD
changedetectionio/forms.py
Python
StringDictKeyValue
StringDictKeyValue
78
103
78
78
35dae2fa99d810166cd408cbf4a46372cfadb129
bigcode/the-stack
train
71aa0d014ee95f886bbe2f11
train
class
class commonSettingsForm(Form): notification_urls = StringListField( "Notification URL List", validators=[validators.Optional(), ValidateAppRiseServers()], ) notification_title = StringField( "Notification Title", default=default_notification_title, validators=[valid...
class commonSettingsForm(Form):
notification_urls = StringListField( "Notification URL List", validators=[validators.Optional(), ValidateAppRiseServers()], ) notification_title = StringField( "Notification Title", default=default_notification_title, validators=[validators.Optional(), ValidateTokensL...
= False is needed even for the test harness "http://localhost:5005.." to run url = html5.URLField("URL", [validators.URL(require_tld=False)]) tag = StringField("Group tag", [validators.Optional(), validators.Length(max=35)]) class commonSettingsForm(Form):
63
64
200
6
57
Devv5G/TimCD
changedetectionio/forms.py
Python
commonSettingsForm
commonSettingsForm
245
274
245
246
306774222dbc88fea4114897e72be6762f490bb3
bigcode/the-stack
train
02cf9ce449fdf1922331db14
train
class
class ValidateListRegex(object): """ Validates that anything that looks like a regex passes as a regex """ def __init__(self, message=None): self.message = message def __call__(self, form, field): for line in field.data: if line[0] == "/" and line[-1] == "/": ...
class ValidateListRegex(object):
""" Validates that anything that looks like a regex passes as a regex """ def __init__(self, message=None): self.message = message def __call__(self, form, field): for line in field.data: if line[0] == "/" and line[-1] == "/": # Because internally we do...
regex = re.compile("{.*?}") for p in re.findall(regex, field.data): if not p.strip("{}") in notification.valid_tokens: message = field.gettext("Token '%s' is not a valid token.") raise ValidationError(message % (p)) class ValidateListRegex(object):
64
64
135
6
58
Devv5G/TimCD
changedetectionio/forms.py
Python
ValidateListRegex
ValidateListRegex
189
209
189
189
54227000d0c16c314f1e771122f4f6be295ace87
bigcode/the-stack
train
640a3eaf3aaa2000716ef150
train
class
class quickWatchForm(Form): # https://wtforms.readthedocs.io/en/2.3.x/fields/#module-wtforms.fields.html5 # `require_tld` = False is needed even for the test harness "http://localhost:5005.." to run url = html5.URLField("URL", [validators.URL(require_tld=False)]) tag = StringField("Group tag", [validato...
class quickWatchForm(Form): # https://wtforms.readthedocs.io/en/2.3.x/fields/#module-wtforms.fields.html5 # `require_tld` = False is needed even for the test harness "http://localhost:5005.." to run
url = html5.URLField("URL", [validators.URL(require_tld=False)]) tag = StringField("Group tag", [validators.Optional(), validators.Length(max=35)])
match anything? class quickWatchForm(Form): # https://wtforms.readthedocs.io/en/2.3.x/fields/#module-wtforms.fields.html5 # `require_tld` = False is needed even for the test harness "http://localhost:5005.." to run
64
64
98
61
3
Devv5G/TimCD
changedetectionio/forms.py
Python
quickWatchForm
quickWatchForm
238
242
238
240
657b4ec564236403c50c30fbec004b7da9e73118
bigcode/the-stack
train
94e31981efd46247616515f8
train
class
class SaltyPasswordField(StringField): widget = widgets.PasswordInput() encrypted_password = "" def build_password(self, password): import hashlib import base64 import secrets # Make a new salt on every new password and store it with the password salt = secrets.toke...
class SaltyPasswordField(StringField):
widget = widgets.PasswordInput() encrypted_password = "" def build_password(self, password): import hashlib import base64 import secrets # Make a new salt on every new password and store it with the password salt = secrets.token_bytes(32) key = hashlib.pbkd...
if valuelist: # Remove empty strings cleaned = list(filter(None, valuelist[0].split("\n"))) self.data = [x.strip() for x in cleaned] p = 1 else: self.data = [] class SaltyPasswordField(StringField):
63
64
191
8
55
Devv5G/TimCD
changedetectionio/forms.py
Python
SaltyPasswordField
SaltyPasswordField
49
74
49
49
426f24e0909ab4a69ced2a30d51190605a3dc6e3
bigcode/the-stack
train
25555d272e53cf85024d06e7
train
class
class StringListField(StringField): widget = widgets.TextArea() def _value(self): if self.data: return "\r\n".join(self.data) else: return u"" # incoming def process_formdata(self, valuelist): if valuelist: # Remove empty strings ...
class StringListField(StringField):
widget = widgets.TextArea() def _value(self): if self.data: return "\r\n".join(self.data) else: return u"" # incoming def process_formdata(self, valuelist): if valuelist: # Remove empty strings cleaned = list(filter(None, valuelis...
from wtforms.validators import ValidationError from wtforms.fields import html5 from changedetectionio import content_fetcher import re from changedetectionio.notification import ( default_notification_format, valid_notification_formats, default_notification_body, default_notification_title, ) class S...
64
64
114
7
57
Devv5G/TimCD
changedetectionio/forms.py
Python
StringListField
StringListField
29
46
29
29
e976ad46149355f2044a273ba410b496db3b971c
bigcode/the-stack
train
8ddb3795b493c75fdaea1315
train
class
class globalSettingsForm(commonSettingsForm): proxies = TextAreaField( "Proxy List", ) bad_proxies = TextAreaField( "Bad Proxy List", render_kw={'readonly' : True} ) use_proxy = BooleanField( "Use proxy from the above list to fetch data?", default=False ) password = S...
class globalSettingsForm(commonSettingsForm):
proxies = TextAreaField( "Proxy List", ) bad_proxies = TextAreaField( "Bad Proxy List", render_kw={'readonly' : True} ) use_proxy = BooleanField( "Use proxy from the above list to fetch data?", default=False ) password = SaltyPasswordField() minutes_between_check ...
("Title") ignore_text = StringListField("Ignore Text", [ValidateListRegex()]) headers = StringDictKeyValue("Request Headers") trigger_text = StringListField( "Trigger/wait for text", [validators.Optional(), ValidateListRegex()] ) class globalSettingsForm(commonSettingsForm):
64
64
149
8
56
Devv5G/TimCD
changedetectionio/forms.py
Python
globalSettingsForm
globalSettingsForm
296
313
296
296
6f03147f33bfd47faea4a89d26fa87d196da4809
bigcode/the-stack
train
4a1160e76119e23aeb82b7ae
train
class
class ValidateTokensList(object): """ Validates that a {token} is from a valid set """ def __init__(self, message=None): self.message = message def __call__(self, form, field): from changedetectionio import notification regex = re.compile("{.*?}") for p in re.finda...
class ValidateTokensList(object):
""" Validates that a {token} is from a valid set """ def __init__(self, message=None): self.message = message def __call__(self, form, field): from changedetectionio import notification regex = re.compile("{.*?}") for p in re.findall(regex, field.data): ...
apobj = apprise.Apprise() for server_url in field.data: if not apobj.add(server_url): message = field.gettext( "'%s' is not a valid AppRise URL." % (server_url) ) raise ValidationError(message) class ValidateTokensList(object):
64
64
117
6
58
Devv5G/TimCD
changedetectionio/forms.py
Python
ValidateTokensList
ValidateTokensList
171
186
171
171
4b70afa68dac509c92dbc73e39d2e8125bdafa62
bigcode/the-stack
train
240cd87b1330ebe074348d3d
train
class
class AutoElectiveClientException(AutoElectiveException): code = -1 desc = "AutoElectiveException" def __init__(self, *args, **kwargs): response = kwargs.pop("response", None) self.response = response msg = "[%d] %s" % ( self.__class__.code, kwargs.pop("msg"...
class AutoElectiveClientException(AutoElectiveException):
code = -1 desc = "AutoElectiveException" def __init__(self, *args, **kwargs): response = kwargs.pop("response", None) self.response = response msg = "[%d] %s" % ( self.__class__.code, kwargs.pop("msg", self.__class__.desc) ) super().__init__(m...
MultiPECourseError", ] class AutoElectiveException(Exception): """ Abstract Exception for AutoElective """ class UserInputException(AutoElectiveException, ValueError): """ 由于用户的输入数据不当而引发的错误 """ class AutoElectiveClientException(AutoElectiveException):
63
64
102
12
51
xiaotianxt/PKUElective2021Spring
autoelective/exceptions.py
Python
AutoElectiveClientException
AutoElectiveClientException
62
74
62
63
39060d82b9553b6f84747ba042b3a61b4a4c9dbc
bigcode/the-stack
train
0cc9158de747e3220f5af917
train
class
class IAAAException(AutoElectiveClientException): code = 200 desc = "IAAAException"
class IAAAException(AutoElectiveClientException):
code = 200 desc = "IAAAException"
ElectiveClientException): code = 103 desc = r"some operations failed for unknown reasons" class UnexceptedHTMLFormat(AutoElectiveClientException): code = 104 desc = r"unable to parse HTML content" class IAAAException(AutoElectiveClientException):
64
64
25
11
53
xiaotianxt/PKUElective2021Spring
autoelective/exceptions.py
Python
IAAAException
IAAAException
106
108
106
106
61143c5bde4a5404219205cb788d3070c5e1b833
bigcode/the-stack
train
cd17b1e47e3334e5e7a67c7b
train
class
class MultiPECourseError(TimeoutError): code = 332 desc = "学校规定每学期只能修一门体育课。"
class MultiPECourseError(TimeoutError):
code = 332 desc = "学校规定每学期只能修一门体育课。"
课。" class ExamTimeConflictError(TipsException): code = 330 desc = "考试时间冲突" class QuotaLimitedError(TipsException): code = 331 desc = "该课程选课人数已满。" class MultiPECourseError(TimeoutError):
64
64
32
9
54
xiaotianxt/PKUElective2021Spring
autoelective/exceptions.py
Python
MultiPECourseError
MultiPECourseError
227
229
227
227
a784a9aafa2ea66a25e328fbff254eeeb8534a2b
bigcode/the-stack
train
31992d4f0fadb08a21fc2b38
train
class
class NotAgreedToSelectionAgreement(SystemException): code = 319 desc = "只有同意选课协议才可以继续选课! "
class NotAgreedToSelectionAgreement(SystemException):
code = 319 desc = "只有同意选课协议才可以继续选课! "
317 desc = "无验证信息。" # 仅辅双登录时会出现 class SharedSessionError(SystemException): code = 318 desc = "你与他人共享了回话,请退出浏览器重新登录。" class NotAgreedToSelectionAgreement(SystemException):
64
64
33
10
53
xiaotianxt/PKUElective2021Spring
autoelective/exceptions.py
Python
NotAgreedToSelectionAgreement
NotAgreedToSelectionAgreement
174
176
174
174
317ba054bfde9a8ab32b80d3b072e154ae45c916
bigcode/the-stack
train
6fb95800cb574f35db01859d
train
class
class NoAuthInfoError(SystemException): code = 317 desc = "无验证信息。" # 仅辅双登录时会出现
class NoAuthInfoError(SystemException):
code = 317 desc = "无验证信息。" # 仅辅双登录时会出现
段" class CourseIndexError(SystemException): code = 315 desc = "索引错误。" class CaptchaError(SystemException): code = 316 desc = "验证码不正确。" class RecognizerError(SystemException): pass class NoAuthInfoError(SystemException):
64
64
32
8
55
xiaotianxt/PKUElective2021Spring
autoelective/exceptions.py
Python
NoAuthInfoError
NoAuthInfoError
166
168
166
166
0a421416ec0df91497c10e516333ed3bad643e96
bigcode/the-stack
train
8cfaf40baa519df5464ca53d
train
class
class CourseIndexError(SystemException): code = 315 desc = "索引错误。"
class CourseIndexError(SystemException):
code = 315 desc = "索引错误。"
code = 313 desc = "您尚未登录或者会话超时,请重新登录." # 相当于 token 失效 class NotInOperationTimeError(SystemException): code = 314 desc = "不在操作时段" class CourseIndexError(SystemException):
64
64
22
7
57
xiaotianxt/PKUElective2021Spring
autoelective/exceptions.py
Python
CourseIndexError
CourseIndexError
155
157
155
155
ba4f4b36400d0cf52dee00c976852fad769fdf15
bigcode/the-stack
train
3c3d23e5fca60132975614c6
train
class
class ElectiveException(AutoElectiveClientException): code = 300 desc = "ElectiveException"
class ElectiveException(AutoElectiveClientException):
code = 300 desc = "ElectiveException"
code = 211 desc = "User ID or Password is incorrect" class IAAAForbiddenError(IAAANotSuccessError): code = 212 desc = "You are FORBIDDEN. Please sign in after a half hour" class ElectiveException(AutoElectiveClientException):
64
64
25
11
53
xiaotianxt/PKUElective2021Spring
autoelective/exceptions.py
Python
ElectiveException
ElectiveException
130
132
130
130
dc0833030632c61c8c6e42a934d3d7574f0d14e0
bigcode/the-stack
train
925c413e8652a67a536e52a1
train
class
class MultiEnglishCourseError(TipsException): code = 329 desc = "学校规定每学期只能修一门英语课,因此您不能选择该课。"
class MultiEnglishCourseError(TipsException):
code = 329 desc = "学校规定每学期只能修一门英语课,因此您不能选择该课。"
code = 327 desc = "您本学期所选课程的总学分已经超过规定学分上限。" class MutexCourseError(TipsException): code = 328 desc = "只能选其一门。" class MultiEnglishCourseError(TipsException):
64
64
38
9
54
xiaotianxt/PKUElective2021Spring
autoelective/exceptions.py
Python
MultiEnglishCourseError
MultiEnglishCourseError
215
217
215
215
5e2dc89d69a0bc908b5bc705851373c812b72e91
bigcode/the-stack
train
28be4239d19a69f48abf0e33
train
class
class ExamTimeConflictError(TipsException): code = 330 desc = "考试时间冲突"
class ExamTimeConflictError(TipsException):
code = 330 desc = "考试时间冲突"
code = 328 desc = "只能选其一门。" class MultiEnglishCourseError(TipsException): code = 329 desc = "学校规定每学期只能修一门英语课,因此您不能选择该课。" class ExamTimeConflictError(TipsException):
64
64
24
9
54
xiaotianxt/PKUElective2021Spring
autoelective/exceptions.py
Python
ExamTimeConflictError
ExamTimeConflictError
219
221
219
219
947cfad4fbd4c7382f3051017eaa0bcf6fda2edf
bigcode/the-stack
train
da7b3a087abd45b5371780a6
train
class
class StatusCodeError(AutoElectiveClientException): code = 101 desc = "response.status_code != 200" def __init__(self, *args, **kwargs): r = kwargs.get("response") if r is not None and "msg" not in kwargs: kwargs["msg"] = "%s. response status code: %s" % (self.__class__.code, r....
class StatusCodeError(AutoElectiveClientException):
code = 101 desc = "response.status_code != 200" def __init__(self, *args, **kwargs): r = kwargs.get("response") if r is not None and "msg" not in kwargs: kwargs["msg"] = "%s. response status code: %s" % (self.__class__.code, r.status_code) super().__init__(*args, **kwarg...
) self.response = response msg = "[%d] %s" % ( self.__class__.code, kwargs.pop("msg", self.__class__.desc) ) super().__init__(msg, *args, **kwargs) class StatusCodeError(AutoElectiveClientException):
64
64
101
11
53
xiaotianxt/PKUElective2021Spring
autoelective/exceptions.py
Python
StatusCodeError
StatusCodeError
77
85
77
77
e0d32092cd24764fc88d432e00b8eec2a80173dd
bigcode/the-stack
train