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
c6fe4ff03f4606593cb8c3c5
train
class
class PostProcessSummary: def __init__(self, pids_alive: Optional[Set[int]], user_id: Optional[int], user_env: Optional[Dict[str, str]], restore_compositor: Optional[bool], previous_cpu_states: Optional[List[CPUState]], previous_gpus_states: Optional[Dict[Type[GPUDriver], List[GPUState]]], ...
class PostProcessSummary:
def __init__(self, pids_alive: Optional[Set[int]], user_id: Optional[int], user_env: Optional[Dict[str, str]], restore_compositor: Optional[bool], previous_cpu_states: Optional[List[CPUState]], previous_gpus_states: Optional[Dict[Type[GPUDriver], List[GPUState]]], pids_to_stop: Opt...
from abc import ABC, abstractmethod from typing import List, Optional, Dict, Set, Type, Tuple from guapow.common.model import ScriptSettings from guapow.service.optimizer.gpu import GPUState, GPUDriver from guapow.service.optimizer.task.model import CPUState, OptimizedProcess, OptimizationContext class PostProcessSumm...
72
169
564
5
66
vinifmor/guapow
guapow/service/optimizer/post_process/summary.py
Python
PostProcessSummary
PostProcessSummary
9
45
9
10
75e3214bc8d8affc8c40fd98979f0986fa58b241
bigcode/the-stack
train
01b2075bfa79145ce7126b2b
train
class
class PostProcessSummarizer(ABC): @abstractmethod async def fill(self, summary: PostProcessSummary, process: OptimizedProcess, main_context: OptimizationContext): pass
class PostProcessSummarizer(ABC): @abstractmethod
async def fill(self, summary: PostProcessSummary, process: OptimizedProcess, main_context: OptimizationContext): pass
_use=None, keep_compositor_disabled=None, processes_not_relaunch=None, processes_to_relaunch=None, dead_pids=None, keep_mouse_hidden=None, restore_mouse_cursor=None, keep_cpu_energy_policy=None, restore_cpu_energy_policy=None) class PostProcessSummarizer(ABC): @abstractmethod
64
64
41
14
50
vinifmor/guapow
guapow/service/optimizer/post_process/summary.py
Python
PostProcessSummarizer
PostProcessSummarizer
48
52
48
50
d7d6d8c823692febdec507458416ff3b35a1df74
bigcode/the-stack
train
c3e55a2bc2c10b07983355c1
train
class
class UserEnvironmentSummarizer(PostProcessSummarizer): async def fill(self, summary: PostProcessSummary, process: OptimizedProcess, main_context: OptimizationContext): if not process.alive and process.user_env: if summary.user_env is None: summary.user_env = {} sum...
class UserEnvironmentSummarizer(PostProcessSummarizer):
async def fill(self, summary: PostProcessSummary, process: OptimizedProcess, main_context: OptimizationContext): if not process.alive and process.user_env: if summary.user_env is None: summary.user_env = {} summary.user_env.update(process.user_env)
_cpu_energy_policy=None, restore_cpu_energy_policy=None) class PostProcessSummarizer(ABC): @abstractmethod async def fill(self, summary: PostProcessSummary, process: OptimizedProcess, main_context: OptimizationContext): pass class UserEnvironmentSummarizer(PostProcessSummarizer):
64
64
70
12
51
vinifmor/guapow
guapow/service/optimizer/post_process/summary.py
Python
UserEnvironmentSummarizer
UserEnvironmentSummarizer
55
62
55
56
cb9d0d43d875803f203599893084f830387768f1
bigcode/the-stack
train
925694a25157f34af5e1ffde
train
class
class GPUStateSummarizer(PostProcessSummarizer): async def fill(self, summary: PostProcessSummary, process: OptimizedProcess, main_context: OptimizationContext): if process.previous_gpus_states: if process.alive: if summary.gpus_in_use is None: summary.gpus_i...
class GPUStateSummarizer(PostProcessSummarizer):
async def fill(self, summary: PostProcessSummary, process: OptimizedProcess, main_context: OptimizationContext): if process.previous_gpus_states: if process.alive: if summary.gpus_in_use is None: summary.gpus_in_use = {} for driver, states in ...
: PostProcessSummary, process: OptimizedProcess, main_context: OptimizationContext): if process.cpu_energy_policy_changed: if process.alive: summary.keep_cpu_energy_policy = True else: summary.restore_cpu_energy_policy = True class GPUStateSummarizer(PostP...
64
64
184
12
51
vinifmor/guapow
guapow/service/optimizer/post_process/summary.py
Python
GPUStateSummarizer
GPUStateSummarizer
125
144
125
126
0fcd2aabeed4e60ddbafda1e494b7eec22a9330e
bigcode/the-stack
train
40b57d17ba2adfe315434979
train
class
class FinishScriptsSummarizer(PostProcessSummarizer): async def fill(self, summary: PostProcessSummary, process: OptimizedProcess, main_context: OptimizationContext): if not process.alive and process.post_scripts: if summary.post_scripts is None: summary.post_scripts = {} ...
class FinishScriptsSummarizer(PostProcessSummarizer):
async def fill(self, summary: PostProcessSummary, process: OptimizedProcess, main_context: OptimizationContext): if not process.alive and process.post_scripts: if summary.post_scripts is None: summary.post_scripts = {} summary.post_scripts[process.created_at] = proce...
self._fill(summary, process, process.stopped_processes, process.relaunch_stopped_processes) if process.stopped_after_launch: self._fill(summary, process, process.stopped_after_launch, process.relaunch_stopped_after_launch) class FinishScriptsSummarizer(PostProcessSummarizer):
64
64
75
12
52
vinifmor/guapow
guapow/service/optimizer/post_process/summary.py
Python
FinishScriptsSummarizer
FinishScriptsSummarizer
176
183
176
177
a43b978ca4b49b83223d2ae91ab5c04ac474015e
bigcode/the-stack
train
7b35cbde716e81f38c90b255
train
class
class UserIdSummarizer(PostProcessSummarizer): async def fill(self, summary: PostProcessSummary, process: OptimizedProcess, main_context: OptimizationContext): if not process.alive and process.user_id is not None: summary.user_id = process.user_id
class UserIdSummarizer(PostProcessSummarizer):
async def fill(self, summary: PostProcessSummary, process: OptimizedProcess, main_context: OptimizationContext): if not process.alive and process.user_id is not None: summary.user_id = process.user_id
summary: PostProcessSummary, process: OptimizedProcess, main_context: OptimizationContext): if not process.alive and process.user_env: if summary.user_env is None: summary.user_env = {} summary.user_env.update(process.user_env) class UserIdSummarizer(PostProcessSummariz...
64
64
59
12
52
vinifmor/guapow
guapow/service/optimizer/post_process/summary.py
Python
UserIdSummarizer
UserIdSummarizer
65
69
65
66
034d921b58bf197007dfa0290eb3b792952bd843
bigcode/the-stack
train
7f7d9dfb81d7dc49d771a358
train
class
class ProcessesToRelaunchSummarizer(PostProcessSummarizer): def _fill(self, summary: PostProcessSummary, process: OptimizedProcess, processes: Dict[str, Optional[str]], relaunch: Optional[bool]): if process.alive: if summary.processes_not_relaunch is None: summary.processes_not_...
class ProcessesToRelaunchSummarizer(PostProcessSummarizer):
def _fill(self, summary: PostProcessSummary, process: OptimizedProcess, processes: Dict[str, Optional[str]], relaunch: Optional[bool]): if process.alive: if summary.processes_not_relaunch is None: summary.processes_not_relaunch = set() summary.processes_not_relaunch....
s.id for s in states}) summary.gpus_in_use[driver] = ids else: if summary.previous_gpus_states is None: summary.previous_gpus_states = {} for driver, gpus_states in process.previous_gpus_states.items(): states = sum...
101
101
338
15
86
vinifmor/guapow
guapow/service/optimizer/post_process/summary.py
Python
ProcessesToRelaunchSummarizer
ProcessesToRelaunchSummarizer
147
173
147
148
1064ca5f19332a7e63c9009685c6920136581034
bigcode/the-stack
train
e6da75e1f2928eebfb1c6c48
train
class
class ProcessesToStopSummarizer(PostProcessSummarizer): async def fill(self, summary: PostProcessSummary, process: OptimizedProcess, main_context: OptimizationContext): if not process.alive and process.related_pids and summary.pids_alive: if summary.pids_to_stop is None: summary...
class ProcessesToStopSummarizer(PostProcessSummarizer):
async def fill(self, summary: PostProcessSummary, process: OptimizedProcess, main_context: OptimizationContext): if not process.alive and process.related_pids and summary.pids_alive: if summary.pids_to_stop is None: summary.pids_to_stop = set() summary.pids_to_stop.u...
Summarizer): async def fill(self, summary: PostProcessSummary, process: OptimizedProcess, main_context: OptimizationContext): if not process.alive and process.user_id is not None: summary.user_id = process.user_id class ProcessesToStopSummarizer(PostProcessSummarizer):
64
64
97
13
50
vinifmor/guapow
guapow/service/optimizer/post_process/summary.py
Python
ProcessesToStopSummarizer
ProcessesToStopSummarizer
72
79
72
73
ced1728d1fbc367e9ef2a7b8bd90966c7e0bf0af
bigcode/the-stack
train
52df091fa5c7713a64756b02
train
class
class CPUEnergyPolicyLevelSummarizer(PostProcessSummarizer): async def fill(self, summary: PostProcessSummary, process: OptimizedProcess, main_context: OptimizationContext): if process.cpu_energy_policy_changed: if process.alive: summary.keep_cpu_energy_policy = True ...
class CPUEnergyPolicyLevelSummarizer(PostProcessSummarizer):
async def fill(self, summary: PostProcessSummary, process: OptimizedProcess, main_context: OptimizationContext): if process.cpu_energy_policy_changed: if process.alive: summary.keep_cpu_energy_policy = True else: summary.restore_cpu_energy_policy = Tru...
: if process.alive: summary.cpus_in_use = True else: if summary.previous_cpus_states is None: summary.previous_cpus_states = [] summary.previous_cpus_states.append(process.previous_cpu_state) class CPUEnergyPolicyLevelSummarize...
64
64
74
15
49
vinifmor/guapow
guapow/service/optimizer/post_process/summary.py
Python
CPUEnergyPolicyLevelSummarizer
CPUEnergyPolicyLevelSummarizer
115
122
115
116
b97a1a35ce207f00d21f6f1c558a4f0c2146d5b3
bigcode/the-stack
train
07caa3eafce73940ae6f24d4
train
class
class CompositorStateSummarizer(PostProcessSummarizer): async def fill(self, summary: PostProcessSummary, process: OptimizedProcess, main_context: OptimizationContext): if process.requires_compositor_disabled: if process.alive: summary.keep_compositor_disabled = True ...
class CompositorStateSummarizer(PostProcessSummarizer):
async def fill(self, summary: PostProcessSummary, process: OptimizedProcess, main_context: OptimizationContext): if process.requires_compositor_disabled: if process.alive: summary.keep_compositor_disabled = True elif main_context.compositor_disabled_context is not Non...
if process.requires_mouse_hidden: if process.alive: summary.keep_mouse_hidden = True elif await main_context.is_mouse_cursor_hidden(): # if the mouse cursor was hidden by the Optimizer summary.restore_mouse_cursor = True class CompositorStateSummarizer(PostProce...
64
64
80
13
50
vinifmor/guapow
guapow/service/optimizer/post_process/summary.py
Python
CompositorStateSummarizer
CompositorStateSummarizer
92
99
92
93
c1242e654ecd7c4cb7f0fbcfeb617a21efbe3c64
bigcode/the-stack
train
e15779cb5d91c8d19001a314
train
class
class MouseCursorStateSummarizer(PostProcessSummarizer): async def fill(self, summary: PostProcessSummary, process: OptimizedProcess, main_context: OptimizationContext): if process.requires_mouse_hidden: if process.alive: summary.keep_mouse_hidden = True elif await m...
class MouseCursorStateSummarizer(PostProcessSummarizer):
async def fill(self, summary: PostProcessSummary, process: OptimizedProcess, main_context: OptimizationContext): if process.requires_mouse_hidden: if process.alive: summary.keep_mouse_hidden = True elif await main_context.is_mouse_cursor_hidden(): # if the mouse curs...
_pids and summary.pids_alive: if summary.pids_to_stop is None: summary.pids_to_stop = set() summary.pids_to_stop.update({pid for pid in process.related_pids if pid in summary.pids_alive}) class MouseCursorStateSummarizer(PostProcessSummarizer):
64
64
89
13
51
vinifmor/guapow
guapow/service/optimizer/post_process/summary.py
Python
MouseCursorStateSummarizer
MouseCursorStateSummarizer
82
89
82
83
a78fbdde22a08b9d9075418eacc9c4e65ecf3a54
bigcode/the-stack
train
6a7c5b750f5e371f791f3248
train
class
class CPUGovernorStateSummarizer(PostProcessSummarizer): async def fill(self, summary: PostProcessSummary, process: OptimizedProcess, main_context: OptimizationContext): if process.previous_cpu_state: if process.alive: summary.cpus_in_use = True else: ...
class CPUGovernorStateSummarizer(PostProcessSummarizer):
async def fill(self, summary: PostProcessSummary, process: OptimizedProcess, main_context: OptimizationContext): if process.previous_cpu_state: if process.alive: summary.cpus_in_use = True else: if summary.previous_cpus_states is None: ...
main_context: OptimizationContext): if process.requires_compositor_disabled: if process.alive: summary.keep_compositor_disabled = True elif main_context.compositor_disabled_context is not None: summary.restore_compositor = True class CPUGovernorStateSumma...
64
64
94
15
48
vinifmor/guapow
guapow/service/optimizer/post_process/summary.py
Python
CPUGovernorStateSummarizer
CPUGovernorStateSummarizer
102
112
102
103
288ee7d817675334b5c0a5fa463d225ce8d6bedd
bigcode/the-stack
train
3075566c3f1dd2be1c7a3449
train
class
class NavigationToolbar2Mac(_macosx.NavigationToolbar2, NavigationToolbar2): def __init__(self, canvas): NavigationToolbar2.__init__(self, canvas) def _init_toolbar(self): basedir = os.path.join(rcParams['datapath'], "images") _macosx.NavigationToolbar2.__init__(self, basedir) def...
class NavigationToolbar2Mac(_macosx.NavigationToolbar2, NavigationToolbar2):
def __init__(self, canvas): NavigationToolbar2.__init__(self, canvas) def _init_toolbar(self): basedir = os.path.join(rcParams['datapath'], "images") _macosx.NavigationToolbar2.__init__(self, basedir) def draw_rubberband(self, event, x0, y0, x1, y1): self.canvas.set_rubberb...
_axes_change(fig): 'this will be called whenever the current axes is changed' if self.toolbar != None: self.toolbar.update() self.canvas.figure.add_axobserver(notify_axes_change) if matplotlib.is_interactive(): self.show() self.canvas.draw_idle() def...
86
86
289
17
69
prcalopa/reactable-autocalibration
autocalibration/lib/python2.7/site-packages/matplotlib/backends/backend_macosx.py
Python
NavigationToolbar2Mac
NavigationToolbar2Mac
152
185
152
153
cb8041c25c653f5b85ffca03c6871a45c70a3915
bigcode/the-stack
train
56e60f086f8e951af41ba172
train
class
@_Backend.export class _BackendMac(_Backend): FigureCanvas = FigureCanvasMac FigureManager = FigureManagerMac @staticmethod def trigger_manager_draw(manager): # For performance reasons, we don't want to redraw the figure after # each draw command. Instead, we mark the figure as invalid,...
@_Backend.export class _BackendMac(_Backend):
FigureCanvas = FigureCanvasMac FigureManager = FigureManagerMac @staticmethod def trigger_manager_draw(manager): # For performance reasons, we don't want to redraw the figure after # each draw command. Instead, we mark the figure as invalid, so that it # will be redrawn as soon ...
return canvas def set_message(self, message): _macosx.NavigationToolbar2.set_message(self, message.encode('utf-8')) ######################################################################## # # Now just provide the standard names that backend.__init__ is expecting # ######################################...
64
64
137
12
51
prcalopa/reactable-autocalibration
autocalibration/lib/python2.7/site-packages/matplotlib/backends/backend_macosx.py
Python
_BackendMac
_BackendMac
194
210
194
195
a0edd713bf6d18b1ab0f610f059f9e677c57a676
bigcode/the-stack
train
7175abd4fd073cf2b4426758
train
class
class FigureManagerMac(_macosx.FigureManager, FigureManagerBase): """ Wrap everything up into a window for the pylab interface """ def __init__(self, canvas, num): FigureManagerBase.__init__(self, canvas, num) title = "Figure %d" % num _macosx.FigureManager.__init__(self, canvas,...
class FigureManagerMac(_macosx.FigureManager, FigureManagerBase):
""" Wrap everything up into a window for the pylab interface """ def __init__(self, canvas, num): FigureManagerBase.__init__(self, canvas, num) title = "Figure %d" % num _macosx.FigureManager.__init__(self, canvas, title) if rcParams['toolbar']=='toolbar2': se...
callbacks : list Sequence of (func, args, kwargs) where ``func(*args, **kwargs)`` will be executed by the timer every *interval*. """ return TimerMac(*args, **kwargs) class FigureManagerMac(_macosx.FigureManager, FigureManagerBase):
64
64
199
16
48
prcalopa/reactable-autocalibration
autocalibration/lib/python2.7/site-packages/matplotlib/backends/backend_macosx.py
Python
FigureManagerMac
FigureManagerMac
124
149
124
124
992ce3de7aae1a2c5fd89bd348f978c1a15c3615
bigcode/the-stack
train
b336e323271af804a541d4a2
train
class
class FigureCanvasMac(_macosx.FigureCanvas, FigureCanvasAgg): """ The canvas the figure renders into. Calls the draw and print fig methods, creates the renderers, etc... Events such as button presses, mouse movements, and key presses are handled in the C code and the base class methods button_...
class FigureCanvasMac(_macosx.FigureCanvas, FigureCanvasAgg):
""" The canvas the figure renders into. Calls the draw and print fig methods, creates the renderers, etc... Events such as button presses, mouse movements, and key presses are handled in the C code and the base class methods button_press_event, button_release_event, motion_notify_event, ke...
run loops for timer events. Attributes ---------- interval : int The time between timer events in milliseconds. Default is 1000 ms. single_shot : bool Boolean flag indicating whether this timer should operate as single shot (run once and then stop). Defaults to False. callb...
148
148
494
16
132
prcalopa/reactable-autocalibration
autocalibration/lib/python2.7/site-packages/matplotlib/backends/backend_macosx.py
Python
FigureCanvasMac
FigureCanvasMac
51
121
51
51
de3eb675439cfa4d014ee9fc8d9912cd9c440116
bigcode/the-stack
train
6ecb23e18059c0c2dc2259b0
train
class
class TimerMac(_macosx.Timer, TimerBase): ''' Subclass of :class:`backend_bases.TimerBase` that uses CoreFoundation run loops for timer events. Attributes ---------- interval : int The time between timer events in milliseconds. Default is 1000 ms. single_shot : bool Boolean ...
class TimerMac(_macosx.Timer, TimerBase):
''' Subclass of :class:`backend_bases.TimerBase` that uses CoreFoundation run loops for timer events. Attributes ---------- interval : int The time between timer events in milliseconds. Default is 1000 ms. single_shot : bool Boolean flag indicating whether this timer should ...
import matplotlib from matplotlib.backends import _macosx from .backend_agg import RendererAgg, FigureCanvasAgg ######################################################################## # # The following functions and classes are for pylab and implement # window/figure managers, etc... # #############################...
64
64
149
12
51
prcalopa/reactable-autocalibration
autocalibration/lib/python2.7/site-packages/matplotlib/backends/backend_macosx.py
Python
TimerMac
TimerMac
30
47
30
30
fbbe9bbadb0f7f94111f5e54e335b2f84da0acb9
bigcode/the-stack
train
7021493f1c881d4929ed27b1
train
class
class Migration(migrations.Migration): dependencies = [ ('tasks', '0015_data_migration'), ] operations = [ migrations.RemoveField( model_name='timeframe', name='end_attribute', ), migrations.RemoveField( model_name='timeframe', ...
class Migration(migrations.Migration):
dependencies = [ ('tasks', '0015_data_migration'), ] operations = [ migrations.RemoveField( model_name='timeframe', name='end_attribute', ), migrations.RemoveField( model_name='timeframe', name='start_attribute', ), ...
# -*- coding: utf-8 -*- # Generated by Django 1.11.14 on 2018-08-29 15:41 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration):
52
64
102
7
44
Raspeanut/rdmo
rdmo/tasks/migrations/0016_remove_timeframe.py
Python
Migration
Migration
8
30
8
9
e9111ce9bf051c46695ad56c9bd1a4f627bdfb93
bigcode/the-stack
train
f5962b5e37f0635b7b5833f8
train
function
@blueprint.route('/WGS/<scope_type>/<scope_id>') def get_boundary_wgs(scope_type, scope_id): return boundary.get_boundary_REST(2019, "WGS", scope_type, scope_id)
@blueprint.route('/WGS/<scope_type>/<scope_id>') def get_boundary_wgs(scope_type, scope_id):
return boundary.get_boundary_REST(2019, "WGS", scope_type, scope_id)
get_sub_boundary_year(year, subscope_type, scope_type, scope_id): return boundary.get_sub_boundaries_REST(year, "", subscope_type, scope_type, scope_id) @blueprint.route('/WGS/<scope_type>/<scope_id>') def get_boundary_wgs(scope_type, scope_id):
64
64
47
26
38
ESDLMapEditorESSIM/boundary-service
app/boundary/routes.py
Python
get_boundary_wgs
get_boundary_wgs
42
44
42
43
7a99cfc6b2cc0d4c4ac16d6acf92c4522dc8ba38
bigcode/the-stack
train
4cac05008a498477af613e48
train
function
@blueprint.route('/<subscope_type>/<scope_type>/<scope_id>') def get_sub_boundary(subscope_type, scope_type, scope_id): return boundary.get_sub_boundaries_REST(2019, "", subscope_type, scope_type, scope_id)
@blueprint.route('/<subscope_type>/<scope_type>/<scope_id>') def get_sub_boundary(subscope_type, scope_type, scope_id):
return boundary.get_sub_boundaries_REST(2019, "", subscope_type, scope_type, scope_id)
_type>/<scope_id>') def get_boundary(scope_type, scope_id): return boundary.get_boundary_REST(2019, "", scope_type, scope_id) @blueprint.route('/<subscope_type>/<scope_type>/<scope_id>') def get_sub_boundary(subscope_type, scope_type, scope_id):
64
64
55
31
33
ESDLMapEditorESSIM/boundary-service
app/boundary/routes.py
Python
get_sub_boundary
get_sub_boundary
27
29
27
28
a0b9acbc9a5cdff6f563882cbd9635371c524a97
bigcode/the-stack
train
187673abc80e5228bd433cd9
train
function
@blueprint.route('/WGS/<scope_type>/<scope_id>/<year>') def get_boundary_wgs_year(scope_type, scope_id, year): return boundary.get_boundary_REST(year, "WGS", scope_type, scope_id)
@blueprint.route('/WGS/<scope_type>/<scope_id>/<year>') def get_boundary_wgs_year(scope_type, scope_id, year):
return boundary.get_boundary_REST(year, "WGS", scope_type, scope_id)
') def get_boundary_wgs(scope_type, scope_id): return boundary.get_boundary_REST(2019, "WGS", scope_type, scope_id) @blueprint.route('/WGS/<scope_type>/<scope_id>/<year>') def get_boundary_wgs_year(scope_type, scope_id, year):
64
64
50
31
33
ESDLMapEditorESSIM/boundary-service
app/boundary/routes.py
Python
get_boundary_wgs_year
get_boundary_wgs_year
47
49
47
48
8b682a9c6b66d12b6273c5c065959fcf92f0a49a
bigcode/the-stack
train
3a1fdab4c0201049e3d3bcd9
train
function
@blueprint.route('/YEAR/<year>/<subscope_type>/<scope_type>/<scope_id>') def get_sub_boundary_year(year, subscope_type, scope_type, scope_id): return boundary.get_sub_boundaries_REST(year, "", subscope_type, scope_type, scope_id)
@blueprint.route('/YEAR/<year>/<subscope_type>/<scope_type>/<scope_id>') def get_sub_boundary_year(year, subscope_type, scope_type, scope_id):
return boundary.get_sub_boundaries_REST(year, "", subscope_type, scope_type, scope_id)
get_boundary_year(scope_type, scope_id, year): return boundary.get_boundary_REST(year, "", scope_type, scope_id) @blueprint.route('/YEAR/<year>/<subscope_type>/<scope_type>/<scope_id>') def get_sub_boundary_year(year, subscope_type, scope_type, scope_id):
64
64
59
37
27
ESDLMapEditorESSIM/boundary-service
app/boundary/routes.py
Python
get_sub_boundary_year
get_sub_boundary_year
37
39
37
38
9d21c2bd51c796209130bdc2d6ba2922118a8a76
bigcode/the-stack
train
c871c36a6a5bf7a91fcf1cc5
train
function
@blueprint.route('/<scope_type>/<scope_id>') def get_boundary(scope_type, scope_id): return boundary.get_boundary_REST(2019, "", scope_type, scope_id)
@blueprint.route('/<scope_type>/<scope_id>') def get_boundary(scope_type, scope_id):
return boundary.get_boundary_REST(2019, "", scope_type, scope_id)
# TNO - Initial implementation # Manager: # TNO from app.boundary import blueprint from app.boundary.boundary import Boundary boundary = Boundary() boundary.db_connect() @blueprint.route('/<scope_type>/<scope_id>') def get_boundary(scope_type, scope_id):
64
64
40
22
42
ESDLMapEditorESSIM/boundary-service
app/boundary/routes.py
Python
get_boundary
get_boundary
22
24
22
23
5727dc234f9f693bd47fc9c26431cdcbe9861185
bigcode/the-stack
train
3ad40c8fc027dc9d482e93d8
train
function
@blueprint.route('/YEAR/<year>/<scope_type>/<scope_id>') def get_boundary_year(scope_type, scope_id, year): return boundary.get_boundary_REST(year, "", scope_type, scope_id)
@blueprint.route('/YEAR/<year>/<scope_type>/<scope_id>') def get_boundary_year(scope_type, scope_id, year):
return boundary.get_boundary_REST(year, "", scope_type, scope_id)
_sub_boundary(subscope_type, scope_type, scope_id): return boundary.get_sub_boundaries_REST(2019, "", subscope_type, scope_type, scope_id) @blueprint.route('/YEAR/<year>/<scope_type>/<scope_id>') def get_boundary_year(scope_type, scope_id, year):
64
64
44
28
36
ESDLMapEditorESSIM/boundary-service
app/boundary/routes.py
Python
get_boundary_year
get_boundary_year
32
34
32
33
fe6222f9960f60a34f30a45aaf5432016e3f99f1
bigcode/the-stack
train
b4abd54731d5ef727c1d39e9
train
function
def main(): __version__ = '2.14.2' start_time = time.time() parser = argparse.ArgumentParser(prog='MitoHiFi') parser._action_groups.pop() required = parser.add_argument_group('required arguments') optional = parser.add_argument_group('optional arguments') mutually_exclusive_gr...
def main():
__version__ = '2.14.2' start_time = time.time() parser = argparse.ArgumentParser(prog='MitoHiFi') parser._action_groups.pop() required = parser.add_argument_group('required arguments') optional = parser.add_argument_group('optional arguments') mutually_exclusive_group = required.add_...
import concurrent.futures from concurrent.futures import wait import logging import shutil import subprocess import time import warnings import pandas as pd import argparse import parse_blast from Bio import SeqIO import sys import os import cleanUpCWD import fetch import filterfasta import findFrameShi...
140
256
4,913
4
135
marcelauliano/CCS_mito
mitohifi.py
Python
main
main
29
373
29
30
f510fa53d7b6c46e0a7055eecbdd9e78bcc781ed
bigcode/the-stack
train
fc11e9052c1929d878232496
train
class
class role_prop(loxi.OFObject): subtypes = {} def __init__(self, type=None): if type != None: self.type = type else: self.type = 0 return def pack(self): packed = [] packed.append(struct.pack("!H", self.type)) packed.append(struct.pa...
class role_prop(loxi.OFObject):
subtypes = {} def __init__(self, type=None): if type != None: self.type = type else: self.type = 0 return def pack(self): packed = [] packed.append(struct.pack("!H", self.type)) packed.append(struct.pack("!H", 0)) # placeholder for l...
Copyright (c) 2012, 2013 Big Switch Networks, Inc. # See the file LICENSE.pyloxi which should have been included in the source distribution # Automatically generated by LOXI from template module.py # Do not modify import struct import loxi import util import loxi.generic_util import sys ofp = sys.modules['loxi.of14...
90
90
301
9
81
sathishms77/test
ofagent/loxi/of14/role_prop.py
Python
role_prop
role_prop
30
74
30
30
0bdc2035db7e94cca68e6f24fe6bf0aef0387f3f
bigcode/the-stack
train
6cbc7df8f5d096834fc4571e
train
class
class experimenter(role_prop): subtypes = {} type = 65535 def __init__(self, experimenter=None, exp_type=None): if experimenter != None: self.experimenter = experimenter else: self.experimenter = 0 if exp_type != None: self.exp_type = exp_type ...
class experimenter(role_prop):
subtypes = {} type = 65535 def __init__(self, experimenter=None, exp_type=None): if experimenter != None: self.experimenter = experimenter else: self.experimenter = 0 if exp_type != None: self.exp_type = exp_type else: self.ex...
obj.type = reader.read("!H")[0] _length = reader.read("!H")[0] orig_reader = reader reader = orig_reader.slice(_length, 4) return obj def __eq__(self, other): if type(self) != type(other): return False if self.type != other.type: return False return True ...
131
132
441
6
125
sathishms77/test
ofagent/loxi/of14/role_prop.py
Python
experimenter
experimenter
77
134
77
77
705914ed832bf99fd1811b5a4e3e9f52367abd51
bigcode/the-stack
train
19b4110bd5c5c69f6a31fca1
train
function
@router.post('/predict') def predict(item: Item): """ Make prediction based on features listed in Request Body. ### Request Body - `goal`: positive integer. US $. - `length`: positive integer. Number of days. - `description`: string - `category`: string; valid categories: ...
@router.post('/predict') def predict(item: Item):
""" Make prediction based on features listed in Request Body. ### Request Body - `goal`: positive integer. US $. - `length`: positive integer. Number of days. - `description`: string - `category`: string; valid categories: {'Academic', ...
goal: int = Field(..., example=50000) length: int = Field(..., example=30) description: str = Field(..., example='tabletop board game') category: str = Field(..., example='Tabletop Games') def to_df(self): """Convert pydantic object to pandas dataframe with 1 row.""" return pd.DataF...
249
249
833
12
236
Build-Week-Kickstart-Success-dstt38/datascience
app/api/predict.py
Python
predict
predict
82
241
82
83
a622d302aa3fc482f2740e3fba1e7ea521c011cf
bigcode/the-stack
train
e1f73d2426f9eb3e991f4d40
train
class
class Item(BaseModel): """Use this data model to parse the request body JSON.""" goal: int = Field(..., example=50000) length: int = Field(..., example=30) description: str = Field(..., example='tabletop board game') category: str = Field(..., example='Tabletop Games') def to_df(self): ...
class Item(BaseModel):
"""Use this data model to parse the request body JSON.""" goal: int = Field(..., example=50000) length: int = Field(..., example=30) description: str = Field(..., example='tabletop board game') category: str = Field(..., example='Tabletop Games') def to_df(self): """Convert pydantic ob...
', 'Stationery', 'Tabletop Games', 'Technology', 'Television', 'Textiles', 'Theater', 'Thrillers', 'Vegan', 'Video', 'Video Games', 'Wearables', 'Web', 'Webcomics', 'Webseries', 'Woodworking', 'Workshops', 'World Music'] class Item(BaseModel):
76
76
255
5
71
Build-Week-Kickstart-Success-dstt38/datascience
app/api/predict.py
Python
Item
Item
52
80
52
52
8b71fb2003d7acb24512d117862a7cdff8d7a8a4
bigcode/the-stack
train
2ebb9361ee00335b18674101
train
class
class Test_gapBetweenRanges(unittest.TestCase): def test_gapBetweenRanges(self): self.assertEquals(-5, gapBetweenRanges((0,10),(15,25))) self.assertEquals( 0, gapBetweenRanges((0,10),(9,20))) self.assertEquals( 2, gapBetweenRanges((20,30),(10,18)))
class Test_gapBetweenRanges(unittest.TestCase):
def test_gapBetweenRanges(self): self.assertEquals(-5, gapBetweenRanges((0,10),(15,25))) self.assertEquals( 0, gapBetweenRanges((0,10),(9,20))) self.assertEquals( 2, gapBetweenRanges((20,30),(10,18)))
, 3) ] tolerance = 15 passFail,exceeds = determineWithinTolerance(diffsAndErrors, tolerance) self.assertEquals(passFail,False) self.assertEquals(exceeds, [-3,-7,0,0]) class Test_gapBetweenRanges(unittest.TestCase):
64
64
77
9
55
bbc/dvbcss-synctiming
tests/test_stats.py
Python
Test_gapBetweenRanges
Test_gapBetweenRanges
67
73
67
68
4461699ebbd9ca4d74380b89d468bf5e3d79b8ef
bigcode/the-stack
train
7a7ec988a7949936898797ce
train
class
class Test_determineWithinTolerance(unittest.TestCase): def test_determineWithinTolerance(self): diffsAndErrors = [ (10, 2), (3, 2), (-1, 3), (5, 3) ] tolerance = 15 passFail,exceeds = determineWithinTolerance(diffsAndE...
class Test_determineWithinTolerance(unittest.TestCase):
def test_determineWithinTolerance(self): diffsAndErrors = [ (10, 2), (3, 2), (-1, 3), (5, 3) ] tolerance = 15 passFail,exceeds = determineWithinTolerance(diffsAndErrors, tolerance) self.assertEquals(passFail,True...
specific language governing permissions and # limitations under the License. """ Unit-tests for code that does statistics output """ import unittest import sys import os sys.path.append(os.path.dirname(os.path.abspath(__file__))+"/../src") from stats import determineWithinTolerance from stats import gapBetweenRa...
72
72
242
10
61
bbc/dvbcss-synctiming
tests/test_stats.py
Python
Test_determineWithinTolerance
Test_determineWithinTolerance
33
64
33
34
8a98d98e8dc172d8efcc4161327ae8e14fbde70a
bigcode/the-stack
train
b2bd794eb84de0f851445046
train
class
class XdsTestClient(framework.rpc.grpc.GrpcApp): """ Represents RPC services implemented in Client component of the xds test app. https://github.com/grpc/grpc/blob/master/doc/xds-test-descriptions.md#client """ def __init__(self, *, ip: str, rpc_po...
class XdsTestClient(framework.rpc.grpc.GrpcApp):
""" Represents RPC services implemented in Client component of the xds test app. https://github.com/grpc/grpc/blob/master/doc/xds-test-descriptions.md#client """ def __init__(self, *, ip: str, rpc_port: int, server_target: str, ...
, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ xDS Test Client. TODO(sergiitk): separate XdsTestClient and KubernetesClientRunner to individual modules. """ import datetime import functools import logging from typing import Iterab...
256
256
1,526
13
242
hanjingo/grpc
tools/run_tests/xds_k8s_test_driver/framework/test_app/client_app.py
Python
XdsTestClient
XdsTestClient
48
225
48
48
bfa9eb4c7399a70b727b8a9c71c20cd531f75302
bigcode/the-stack
train
9cba64c76534ac31ee6af18d
train
class
class KubernetesClientRunner(base_runner.KubernetesBaseRunner): def __init__(self, k8s_namespace, *, deployment_name, image_name, td_bootstrap_image, gcp_api_manager: gcp.api.GcpApiManager, gcp_pr...
class KubernetesClientRunner(base_runner.KubernetesBaseRunner):
def __init__(self, k8s_namespace, *, deployment_name, image_name, td_bootstrap_image, gcp_api_manager: gcp.api.GcpApiManager, gcp_project: str, gcp_service_account: str, ...
' 'the server') def get_server_channels(self, **kwargs) -> Iterable[_ChannelzChannel]: return self.channelz.find_channels_for_target(self.server_target, **kwargs) def find_subchannel_with_state(self, channel: _ChannelzChannel, ...
256
256
1,398
11
244
hanjingo/grpc
tools/run_tests/xds_k8s_test_driver/framework/test_app/client_app.py
Python
KubernetesClientRunner
KubernetesClientRunner
228
391
228
229
f7a59ec5f0ab849297a5cde290f72e9bbb4f9908
bigcode/the-stack
train
509f88705d334805c3967245
train
function
def run_func_as_main(func, parser=None, passed_args=None): """ Run function as the main. Put the function arguments into argument parser """ if passed_args is None: passed_args = {} parser = get_argparser_from_func(func, parser=parser, exclude=list(passed_args.keys())) args = vars(parser.parse_a...
def run_func_as_main(func, parser=None, passed_args=None):
""" Run function as the main. Put the function arguments into argument parser """ if passed_args is None: passed_args = {} parser = get_argparser_from_func(func, parser=parser, exclude=list(passed_args.keys())) args = vars(parser.parse_args()) args.update(passed_args) func(**args)
Argument with default value None must be annotated with type in {func}, {k}, {v.annotation}') parser.add_argument('--' + k, type=arg_type, default=v.default, help=params.get(k, ' ')) return parser def run_func_as_main(func, parser=None, passed_args=None):
64
64
83
14
49
vermouth1992/rl-util
rlutils/infra/runner/utils/commandline_utils.py
Python
run_func_as_main
run_func_as_main
47
54
47
47
ce755df1a953825c7e1bf7c61d3753dc8228ba47
bigcode/the-stack
train
076fe3c3767f2de9a987ba9f
train
function
def get_argparser_from_func(func, parser, exclude=None): """ Read the argument of a function and parse it as ArgumentParser. """ if parser is None: parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) signature = inspect.signature(func) docstring = docstring_p...
def get_argparser_from_func(func, parser, exclude=None):
""" Read the argument of a function and parse it as ArgumentParser. """ if parser is None: parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) signature = inspect.signature(func) docstring = docstring_parser.parse(inspect.getdoc(func)) # transform docstr...
import argparse import inspect import docstring_parser def get_argparser_from_func(func, parser, exclude=None):
24
98
329
13
10
vermouth1992/rl-util
rlutils/infra/runner/utils/commandline_utils.py
Python
get_argparser_from_func
get_argparser_from_func
7
44
7
7
e5c3e9c6df3f69118bd9db06ccd4b00a9dc2c6ec
bigcode/the-stack
train
979406027fda1b9f7f96e9f7
train
class
class TestTwistedConnection(unittest.TestCase): def setUp(self): if twistedreactor is None: raise unittest.SkipTest("Twisted libraries not available") twistedreactor.TwistedConnection.initialize_reactor() self.reactor_cft_patcher = patch( 'twisted.internet.reactor.cal...
class TestTwistedConnection(unittest.TestCase):
def setUp(self): if twistedreactor is None: raise unittest.SkipTest("Twisted libraries not available") twistedreactor.TwistedConnection.initialize_reactor() self.reactor_cft_patcher = patch( 'twisted.internet.reactor.callFromThread') self.reactor_running_patch...
callback writes the data to the connection object's buffer and calls handle_read(). """ self.obj_ut.makeConnection(self.tr) self.obj_ut.dataReceived('foobar') self.assertTrue(self.mock_connection.handle_read.called) self.mock_connection._iobuf.write.assert_called_with("f...
256
256
954
9
247
josh-mckenzie/python-driver
tests/unit/io/test_twistedreactor.py
Python
TestTwistedConnection
TestTwistedConnection
91
194
91
91
38d3380b39b7f2d19d8acba9c0ec07a1db36b96f
bigcode/the-stack
train
af5d2e79145b152b463d131c
train
class
class TestTwistedProtocol(unittest.TestCase): def setUp(self): if twistedreactor is None: raise unittest.SkipTest("Twisted libraries not available") twistedreactor.TwistedConnection.initialize_reactor() self.tr = proto_helpers.StringTransportWithDisconnection() self.tr.c...
class TestTwistedProtocol(unittest.TestCase):
def setUp(self): if twistedreactor is None: raise unittest.SkipTest("Twisted libraries not available") twistedreactor.TwistedConnection.initialize_reactor() self.tr = proto_helpers.StringTransportWithDisconnection() self.tr.connector = Mock() self.mock_connection ...
. try: import unittest2 as unittest except ImportError: import unittest from mock import Mock, patch try: from twisted.test import proto_helpers from twisted.python.failure import Failure from cassandra.io import twistedreactor except ImportError: twistedreactor = None # NOQA class TestTwiste...
77
77
257
9
67
josh-mckenzie/python-driver
tests/unit/io/test_twistedreactor.py
Python
TestTwistedProtocol
TestTwistedProtocol
29
62
29
30
fd5889f0f67ea97c3eb5a62197a4a3ab6332e065
bigcode/the-stack
train
ffddc295dda83e2617089609
train
class
class TestTwistedClientFactory(unittest.TestCase): def setUp(self): if twistedreactor is None: raise unittest.SkipTest("Twisted libraries not available") twistedreactor.TwistedConnection.initialize_reactor() self.mock_connection = Mock() self.obj_ut = twistedreactor.Twist...
class TestTwistedClientFactory(unittest.TestCase):
def setUp(self): if twistedreactor is None: raise unittest.SkipTest("Twisted libraries not available") twistedreactor.TwistedConnection.initialize_reactor() self.mock_connection = Mock() self.obj_ut = twistedreactor.TwistedConnectionClientFactory( self.mock_co...
the connection object's buffer and calls handle_read(). """ self.obj_ut.makeConnection(self.tr) self.obj_ut.dataReceived('foobar') self.assertTrue(self.mock_connection.handle_read.called) self.mock_connection._iobuf.write.assert_called_with("foobar") class TestTwistedClientFacto...
64
64
186
10
54
josh-mckenzie/python-driver
tests/unit/io/test_twistedreactor.py
Python
TestTwistedClientFactory
TestTwistedClientFactory
65
88
65
65
0d14fe3cb3e191d2e78f6e6f403263fe83e65a93
bigcode/the-stack
train
dc57a0da950a65e8a82985ba
train
function
def series(warmup=100000, repeat=20, steps=10000, limit_hours=None): R""" Perform a series of benchmark runs. Args: warmup (int): Number of time steps to :py:meth:`hoomd.run()` to warm up the benchmark repeat (int): Number of times to repeat the benchmark *steps*. steps (int): Number of...
def series(warmup=100000, repeat=20, steps=10000, limit_hours=None):
R""" Perform a series of benchmark runs. Args: warmup (int): Number of time steps to :py:meth:`hoomd.run()` to warm up the benchmark repeat (int): Number of times to repeat the benchmark *steps*. steps (int): Number of time steps to :py:meth:`hoomd.run()` at each benchmark point. ...
file is part of the HOOMD-blue project, released under the BSD 3-Clause License. # Maintainer: joaander / All Developers are free to add commands for new features R""" Benchmark utilities Commands that help in benchmarking HOOMD-blue performance. """ import hoomd def series(warmup=100000, repeat=20, steps=10000, l...
83
83
279
22
60
kmoskovtsev/HOOMD-Blue-fork
hoomd/benchmark.py
Python
series
series
13
38
13
13
c3824aa7144eec8a4ccb5706fe050f12b0be9c7c
bigcode/the-stack
train
63a0946de1f2432e0909c2b1
train
function
def main(): """Prints info about qlist""" print("qlist enterprise available at - https://www.qsonlabs.com")
def main():
"""Prints info about qlist""" print("qlist enterprise available at - https://www.qsonlabs.com")
import os def main():
6
64
29
3
2
QsonLabs/open-qlist-py
qlist/qlist.py
Python
main
main
4
6
4
4
a01136e0bc8dee4ee59cf7113effcf698bac916f
bigcode/the-stack
train
50c9eb238fb29152f9765b6c
train
function
@convert_kwargs_to_snake_case def resolve_todo(obj, info, todo_id): try: todo = Todo.query.get(todo_id) payload = { "success": True, "todo": todo.to_dict() } except AttributeError: # todo not found payload = { "success": False, "e...
@convert_kwargs_to_snake_case def resolve_todo(obj, info, todo_id):
try: todo = Todo.query.get(todo_id) payload = { "success": True, "todo": todo.to_dict() } except AttributeError: # todo not found payload = { "success": False, "errors": [f"Todo item matching id {todo_id} not found"] } ...
{ "success": True, "todos": todos } except Exception as error: payload = { "success": False, "errors": [str(error)] } return payload @convert_kwargs_to_snake_case def resolve_todo(obj, info, todo_id):
64
64
96
19
44
carmelo0x99/GraphQL-Flask-Ariadne
api/queries.py
Python
resolve_todo
resolve_todo
18
33
18
19
195f55eb5e9d1a715b8632935584d30a919b2f9e
bigcode/the-stack
train
3288dfc124e207f7568bfbf5
train
function
def resolve_todos(obj, info): try: todos = [todo.to_dict() for todo in Todo.query.all()] payload = { "success": True, "todos": todos } except Exception as error: payload = { "success": False, "errors": [str(error)] } ret...
def resolve_todos(obj, info):
try: todos = [todo.to_dict() for todo in Todo.query.all()] payload = { "success": True, "todos": todos } except Exception as error: payload = { "success": False, "errors": [str(error)] } return payload
from .models import Todo from ariadne import convert_kwargs_to_snake_case def resolve_todos(obj, info):
26
64
74
8
17
carmelo0x99/GraphQL-Flask-Ariadne
api/queries.py
Python
resolve_todos
resolve_todos
4
16
4
4
b4bc6ad55ea91cf98e7625184d590ec6c24bf8c3
bigcode/the-stack
train
01be4e4bb1d1f07e1989de15
train
class
class PrintLabel(Document): pass
class PrintLabel(Document):
pass
# -*- coding: utf-8 -*- # Copyright (c) 2019, jonathan and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document class PrintLabel(Document):
55
64
7
5
49
jof2jc/custom1
custom1/custom1/doctype/print_label/print_label.py
Python
PrintLabel
PrintLabel
9
10
9
9
8fa0c5509fefa3a1507debc57692236c3e13ae3c
bigcode/the-stack
train
3290a1fb837e37f06b1cc723
train
class
class SampleWebRequestOpened(apper.Fusion360WebRequestEvent): def __init__(self, event_id: str, event_type): super().__init__(event_id, event_type) from multiprocessing.connection import Client address = ('localhost', 6000) self.conn = Client(address) def web_request_event_rece...
class SampleWebRequestOpened(apper.Fusion360WebRequestEvent):
def __init__(self, event_id: str, event_type): super().__init__(event_id, event_type) from multiprocessing.connection import Client address = ('localhost', 6000) self.conn = Client(address) def web_request_event_received(self, event_args, file, fusion_id, occurrence_or_document,...
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # SampleWebRequestEvent.py ~ # This file is a component of ApperSample. ~ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~...
64
64
157
14
49
tapnair/FusionApperSample
commands/SampleWebRequestEvent.py
Python
SampleWebRequestOpened
SampleWebRequestOpened
13
32
13
14
d08082b7a86f83190add321218d8aa45e9c9820e
bigcode/the-stack
train
891a094b77e88cfe255b6041
train
class
class TestQsturng(object): def test_scalar(self): # scalar input -> scalar output assert_almost_equal(4.43645545899562, qsturng(.9,5,6), 5) def test_vector(self): # vector input -> vector output assert_array_almost_equal(np.array([3.98832389, ...
class TestQsturng(object):
def test_scalar(self): # scalar input -> scalar output assert_almost_equal(4.43645545899562, qsturng(.9,5,6), 5) def test_vector(self): # vector input -> vector output assert_array_almost_equal(np.array([3.98832389, 4.56835318, ...
# Copyright (c) 2011 BSD, Roger Lew [see LICENSE.txt] # This software is funded in part by NIH Grant P20 RR016454. """The 'handful' tests are intended to aid refactoring. The tests with the @dec.slow are empirical (test within error limits) and intended to more extensively ensure the stability and accuracy of the func...
251
256
1,731
8
243
cdown/statsmodels
statsmodels/stats/libqsturng/tests/test_qsturng.py
Python
TestQsturng
TestQsturng
27
132
27
27
61a40affeafbaa81c0f0452bcba2bccffe82cee4
bigcode/the-stack
train
5cd89c7946b1171eaca6f19d
train
function
def read_ch(fname): with open(fname) as f: lines = f.readlines() ps,rs,vs,qs = lzip(*[L.split(',') for L in lines]) return lmap(float, ps), lmap(float, rs),lmap(float, vs), lmap(float, qs)
def read_ch(fname):
with open(fname) as f: lines = f.readlines() ps,rs,vs,qs = lzip(*[L.split(',') for L in lines]) return lmap(float, ps), lmap(float, rs),lmap(float, vs), lmap(float, qs)
_almost_equal, assert_array_almost_equal, assert_array_equal, \ assert_approx_equal, assert_raises, run_module_suite, dec import numpy as np from statsmodels.stats.libqsturng import qsturng, psturng,p_keys,v_keys def read_ch(fname):
64
64
67
5
58
cdown/statsmodels
statsmodels/stats/libqsturng/tests/test_qsturng.py
Python
read_ch
read_ch
20
24
20
20
a74612501150b1850d8c961ac808da960da35fa3
bigcode/the-stack
train
d67591b2f7a0f82d72eea90d
train
class
class TestPsturng(object): def test_scalar(self): "scalar input -> scalar output" assert_almost_equal(.1, psturng(4.43645545899562,5,6), 5) def test_vector(self): "vector input -> vector output" assert_array_almost_equal(np.array([0.10679889, ...
class TestPsturng(object):
def test_scalar(self): "scalar input -> scalar output" assert_almost_equal(.1, psturng(4.43645545899562,5,6), 5) def test_vector(self): "vector input -> vector output" assert_array_almost_equal(np.array([0.10679889, 0.06550009, ...
.3283725986180395), (0.9503, 2.0, 4.434, 3.7871158594867262), (0.7276132, 95.0, 91.43983, 5.4100384868499889)] for p,r,v,q in cases: assert_almost_equal(q, qsturng(p,r,v), 5) @dec.slow def test_10000_to_ch(self): import os curdir = os.path....
256
256
1,068
8
248
cdown/statsmodels
statsmodels/stats/libqsturng/tests/test_qsturng.py
Python
TestPsturng
TestPsturng
134
196
134
134
d471bfb55abd2cf1d8bd8bd65051022021a9b7fb
bigcode/the-stack
train
236abf5376bed6bcb4929413
train
function
def lenet5(inputs): inputs = tf.reshape(inputs, [-1, 28, 28, 1]) net = slim.conv2d(inputs, 32, [5, 5], padding='SAME', scope='layer1-conv') net = slim.max_pool2d(net, 2, stride=2, scope='layer2-max-pool') net = slim.conv2d(net, 64, [5, 5], padding='SAME', scope='layer3-conv') net = slim.max_pool2d(...
def lenet5(inputs):
inputs = tf.reshape(inputs, [-1, 28, 28, 1]) net = slim.conv2d(inputs, 32, [5, 5], padding='SAME', scope='layer1-conv') net = slim.max_pool2d(net, 2, stride=2, scope='layer2-max-pool') net = slim.conv2d(net, 64, [5, 5], padding='SAME', scope='layer3-conv') net = slim.max_pool2d(net, 2, scope='layer...
# -*- coding:utf-8 -*- import tensorflow as tf import tensorflow.contrib.slim as slim import numpy as np from tensorflow.examples.tutorials.mnist import input_data def lenet5(inputs):
42
64
181
6
35
carbo-T/TF
Encapsulation/slim_usage.py
Python
lenet5
lenet5
8
18
8
8
91b7aacbdd4c2e831f2dfafd2c713a72b5e127eb
bigcode/the-stack
train
869f02c4f3178091314372e4
train
function
def main(): cfg.parse_args()
def main():
cfg.parse_args()
#!/usr/bin/env python from faster_particles.config import cfg def main():
16
64
8
3
12
Temigo/faster-particles
faster_particles/bin/ppn.py
Python
main
main
5
6
5
5
13bbc1956175e2b7fdd9f473353c3a3dd4c4ee83
bigcode/the-stack
train
538131c63dbba27a99ca0840
train
class
class Solution(object): def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ ls = len(s) lp = len(p) dp = [[False] * (lp+1) for _ in range(ls+1)] dp[0][0] = True for i in range(1,lp): if p[i] == '*': ...
class Solution(object):
def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ ls = len(s) lp = len(p) dp = [[False] * (lp+1) for _ in range(ls+1)] dp[0][0] = True for i in range(1,lp): if p[i] == '*': dp[0][i+1] = ...
class Solution(object):
4
83
279
4
0
tedye/leetcode
Python/leetcode.010.regular-expression-matching.py
Python
Solution
Solution
1
25
1
1
61b90c1836b47382d8c4cf94017076a2ab64a48e
bigcode/the-stack
train
c07a08c8dce7fc8531be362b
train
function
def test_something(): assert True
def test_something():
assert True
from tabularasa import SomeClass import numpy as np from numpy.testing import assert_equal, assert_allclose def test_something():
29
64
9
5
23
edmundsj/template
tabularasa/test/test_something.py
Python
test_something
test_something
5
6
5
5
d457bc920643cd72077c6e22fe39c8c46c87a976
bigcode/the-stack
train
5582bb9e5b3bb095df3f7fb6
train
class
class GeometryNode(Node) : def __init__(self, parent) : super().__init__('geometry', parent) def validate(self) : if self._attributes : return False if self._text : return False if self._is_cdata : return False if not self._childre...
class GeometryNode(Node) :
def __init__(self, parent) : super().__init__('geometry', parent) def validate(self) : if self._attributes : return False if self._text : return False if self._is_cdata : return False if not self._children : return Fals...
from .Node import Node class GeometryNode(Node) :
12
64
78
6
5
jamiefeiss/MLFX
mlfx/nodes/GeometryNode.py
Python
GeometryNode
GeometryNode
3
16
3
3
680eac229224b30adbe845ffd28240e3a25aa877
bigcode/the-stack
train
fda1984f9d43e69cf4a3c8fc
train
class
class SecurityRulesOperations(object): """SecurityRulesOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. ...
class SecurityRulesOperations(object):
"""SecurityRulesOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.network.v20...
) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # ----------------------------------...
256
256
4,427
6
250
beltr0n/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2017_08_01/operations/_security_rules_operations.py
Python
SecurityRulesOperations
SecurityRulesOperations
28
439
28
28
cb52920c1947e5bc4c58a2b12b6ef8afc2d8e538
bigcode/the-stack
train
1d80488def2873a4263d2389
train
class
class TestTemporaryDirectory(unittest.TestCase): def test_keep_true(self) -> None: with TemporaryDirectory(keep=True) as work_dir: self.assertTrue(os.path.exists(work_dir.name)) self.assertTrue(os.path.exists(work_dir.name)) def test_keep_false(self) -> None: with TemporaryD...
class TestTemporaryDirectory(unittest.TestCase):
def test_keep_true(self) -> None: with TemporaryDirectory(keep=True) as work_dir: self.assertTrue(os.path.exists(work_dir.name)) self.assertTrue(os.path.exists(work_dir.name)) def test_keep_false(self) -> None: with TemporaryDirectory() as work_dir: self.assertTr...
# SPDX-License-Identifier: Apache-2.0 # # The OpenSearch Contributors require contributions made to # this file be licensed under the Apache-2.0 license or a # compatible open source license. import os import stat import unittest from system.temporary_directory import TemporaryDirectory class TestTemporaryDirectory(u...
70
92
308
8
61
naveenpajjuri/opensearch-build
tests/tests_system/test_temporary_directory.py
Python
TestTemporaryDirectory
TestTemporaryDirectory
14
46
14
14
4b87c488562d94bc08e193f12afc06db3533c1e4
bigcode/the-stack
train
9e667832263f4690b9b45d50
train
function
def do_preprocess(args): log.debug("reading config file ({})".format(args.config_file)) config = azconfig.ConfigFile() config.open(args.config_file) print(json.dumps(config.preprocess(), indent=4))
def do_preprocess(args):
log.debug("reading config file ({})".format(args.config_file)) config = azconfig.ConfigFile() config.open(args.config_file) print(json.dumps(config.preprocess(), indent=4))
log import azutil from cryptography.hazmat.primitives import serialization as crypto_serialization from cryptography.hazmat.primitives.asymmetric import rsa from cryptography.hazmat.backends import default_backend as crypto_default_backend log = azlog.getLogger(__name__) def do_preprocess(args):
64
64
48
6
58
jithinjosepkl/azurehpc
pyazhpc/azhpc.py
Python
do_preprocess
do_preprocess
23
27
23
23
8a5ef3976271831e77538d46612e41b6f5657fc5
bigcode/the-stack
train
138f4a0a1f47c76d0925235a
train
function
def _exec_command(fqdn, sshuser, sshkey, cmdline): ssh_exe = "ssh" ssh_args = [ ssh_exe, "-q", "-o", "StrictHostKeyChecking=no", "-o", "UserKnownHostsFile=/dev/null", "-i", sshkey, f"{sshuser}@{fqdn}" ] log.debug(" ".join(ssh_args + [ cmdline ])) os.execvp(ss...
def _exec_command(fqdn, sshuser, sshkey, cmdline):
ssh_exe = "ssh" ssh_args = [ ssh_exe, "-q", "-o", "StrictHostKeyChecking=no", "-o", "UserKnownHostsFile=/dev/null", "-i", sshkey, f"{sshuser}@{fqdn}" ] log.debug(" ".join(ssh_args + [ cmdline ])) os.execvp(ssh_exe, ssh_args + [ cmdline ])
{sshuser}@{fqdn}", f"{sshuser}@{target}" ] log.debug(" ".join(ssh_args + cmdline)) os.execvp(ssh_exe, ssh_args + cmdline) def _exec_command(fqdn, sshuser, sshkey, cmdline):
64
64
113
17
47
jithinjosepkl/azurehpc
pyazhpc/azhpc.py
Python
_exec_command
_exec_command
296
306
296
296
2039d45129d7c479243f0a0d08841d2b2e792fb8
bigcode/the-stack
train
c63ef2b92d26b158ea4328b1
train
function
def do_scp(args): log.debug("reading config file ({})".format(args.config_file)) c = azconfig.ConfigFile() c.open(args.config_file) adminuser = c.read_value("admin_user") sshkey="{}_id_rsa".format(adminuser) # TODO: check ssh key exists fqdn = c.get_install_from_destination() if no...
def do_scp(args):
log.debug("reading config file ({})".format(args.config_file)) c = azconfig.ConfigFile() c.open(args.config_file) adminuser = c.read_value("admin_user") sshkey="{}_id_rsa".format(adminuser) # TODO: check ssh key exists fqdn = c.get_install_from_destination() if not fqdn: lo...
elif vv == "false": vv = False vset[vk] = vv for root, dirs, files in os.walk(args.dir): for name in files: if os.path.splitext(name)[1] == ".json": fname = os.path.join(root, name) ...
84
84
282
6
78
jithinjosepkl/azurehpc
pyazhpc/azhpc.py
Python
do_scp
do_scp
159
187
159
159
2239a355f689d14265dc4415aa6ac81302469d07
bigcode/the-stack
train
2655d17b65e26391f147b388
train
function
def do_build(args): log.debug(f"reading config file ({args.config_file})") tmpdir = "azhpc_install_" + os.path.basename(args.config_file)[:-5] log.debug(f"tmpdir = {tmpdir}") if os.path.isdir(tmpdir): log.debug("removing existing tmp directory") shutil.rmtree(tmpdir) c = azconfig.Co...
def do_build(args):
log.debug(f"reading config file ({args.config_file})") tmpdir = "azhpc_install_" + os.path.basename(args.config_file)[:-5] log.debug(f"tmpdir = {tmpdir}") if os.path.isdir(tmpdir): log.debug("removing existing tmp directory") shutil.rmtree(tmpdir) c = azconfig.ConfigFile() c.ope...
arm template") deployname = azutil.deploy( config["resource_group"], output_template ) log.debug(f"deployment name: {deployname}") _wait_for_deployment(config["resource_group"], deployname) # remove local scripts config["install"] = [ step for step in config["install"] if step...
189
189
630
5
184
jithinjosepkl/azurehpc
pyazhpc/azhpc.py
Python
do_build
do_build
597
675
597
597
706dd59c340db88f467e8631b05fbd91d8ecacd4
bigcode/the-stack
train
ae341cf446c7e97e922df8f7
train
function
def do_run(args): log.debug("reading config file ({})".format(args.config_file)) c = azconfig.ConfigFile() c.open(args.config_file) adminuser = c.read_value("admin_user") ssh_private_key="{}_id_rsa".format(adminuser) # TODO: check ssh key exists if args.user == None: sshuse...
def do_run(args):
log.debug("reading config file ({})".format(args.config_file)) c = azconfig.ConfigFile() c.open(args.config_file) adminuser = c.read_value("admin_user") ssh_private_key="{}_id_rsa".format(adminuser) # TODO: check ssh key exists if args.user == None: sshuser = adminuser ...
_destination() if not fqdn: log.error(f"Missing 'install_from' property") sys.exit(1) tmpdir = "azhpc_install_" + os.path.basename(args.config_file).strip(".json") _exec_command(fqdn, adminuser, ssh_private_key, f"pssh -h {tmpdir}/hostlists/linux -i -t 0 'printf \"%-20s%s\n\" \"$(hostname)\...
113
113
377
5
108
jithinjosepkl/azurehpc
pyazhpc/azhpc.py
Python
do_run
do_run
325
369
325
325
e1efb5cd78b095bfe46bb15e6b4755c841153ba2
bigcode/the-stack
train
82bdd08fdbe9a225c4790c40
train
function
def do_get(args): config = azconfig.ConfigFile() config.open(args.config_file) log.debug(f"azhpc get for {args.path}") processed_val = config.process_value(args.path) log.debug(f"processed value is {processed_val}") read_val = config.read_value(processed_val) log.debug(f"read value is {read_...
def do_get(args):
config = azconfig.ConfigFile() config.open(args.config_file) log.debug(f"azhpc get for {args.path}") processed_val = config.process_value(args.path) log.debug(f"processed value is {processed_val}") read_val = config.read_value(processed_val) log.debug(f"read value is {read_val}") if read...
_backend log = azlog.getLogger(__name__) def do_preprocess(args): log.debug("reading config file ({})".format(args.config_file)) config = azconfig.ConfigFile() config.open(args.config_file) print(json.dumps(config.preprocess(), indent=4)) def do_get(args):
64
64
135
5
59
jithinjosepkl/azurehpc
pyazhpc/azhpc.py
Python
do_get
do_get
29
42
29
29
1089d4fad08c69f15b969e99b3860c113bc29381
bigcode/the-stack
train
db656b0cf152e39ad33705eb
train
function
def __add_unset_vars(vset, config_file): log.debug(f"looking for vars in {config_file}") file_loc = os.path.dirname(config_file) with open(config_file) as f: data = json.load(f) vars = data.get("variables", {}) if type(vars) is str and vars.startswith("@"): fname = vars[1:] i...
def __add_unset_vars(vset, config_file):
log.debug(f"looking for vars in {config_file}") file_loc = os.path.dirname(config_file) with open(config_file) as f: data = json.load(f) vars = data.get("variables", {}) if type(vars) is str and vars.startswith("@"): fname = vars[1:] if file_loc == "": file_loc = ...
args.path == processed_val: # use the read value result if valid or if processed value is the same as the original val = read_val else: val = processed_val print(f"{args.path} = {val}") def __add_unset_vars(vset, config_file):
64
64
161
12
52
jithinjosepkl/azurehpc
pyazhpc/azhpc.py
Python
__add_unset_vars
__add_unset_vars
44
62
44
44
db6c3841d114ad1aeb0da03ecfe9f90c648a7c85
bigcode/the-stack
train
aac7fa305621973272a9d6f7
train
function
def __replace_vars(vset, config_file): log.debug(f"replacing vars in {config_file}") floc = os.path.dirname(config_file) fname = config_file with open(fname) as f: alldata = json.load(f) varsobj = alldata.get("variables", {}) if type(varsobj) is str and varsobj.startswith("@"): ...
def __replace_vars(vset, config_file):
log.debug(f"replacing vars in {config_file}") floc = os.path.dirname(config_file) fname = config_file with open(fname) as f: alldata = json.load(f) varsobj = alldata.get("variables", {}) if type(varsobj) is str and varsobj.startswith("@"): if floc != "": floc = floc...
with open(f"{file_loc}/{fname}") as f: vars = json.load(f) log.debug(vars) vset.update([ x for x in vars.keys() if vars[x] == "<NOT-SET>" ]) def __replace_vars(vset, config_file):
64
64
212
10
54
jithinjosepkl/azurehpc
pyazhpc/azhpc.py
Python
__replace_vars
__replace_vars
64
88
64
64
7f5f0b599387dacc52bcc224ef3b5b102fafb078
bigcode/the-stack
train
f728ca027eff622996cb262c
train
function
def do_slurm_suspend(args): log.debug(f"reading config file ({args.config_file})") c = azconfig.ConfigFile() c.open(args.config_file) config = c.preprocess() log.info(f"slurm suspend for {args.nodes}") # first get the resource name resource_name, brackets = re.search(r'([^[]*)\[?([\d\-...
def do_slurm_suspend(args):
log.debug(f"reading config file ({args.config_file})") c = azconfig.ConfigFile() c.open(args.config_file) config = c.preprocess() log.info(f"slurm suspend for {args.nodes}") # first get the resource name resource_name, brackets = re.search(r'([^[]*)\[?([\d\-\,]*)\]?', args.nodes).group...
): for value in d: pretty_print(value, indent) elif isinstance(d, dict): for key, value in d.items(): if isinstance(value, dict): ...
136
136
454
7
129
jithinjosepkl/azurehpc
pyazhpc/azhpc.py
Python
do_slurm_suspend
do_slurm_suspend
467
510
467
467
610be2427397422b49f5da1553d36f8a5ecd830a
bigcode/the-stack
train
9eb6f6414b4c6160c0bee32d
train
function
def do_connect(args): log.debug("reading config file ({})".format(args.config_file)) c = azconfig.ConfigFile() c.open(args.config_file) adminuser = c.read_value("admin_user") ssh_private_key="{}_id_rsa".format(adminuser) # TODO: check ssh key exists if not args.user: sshuse...
def do_connect(args):
log.debug("reading config file ({})".format(args.config_file)) c = azconfig.ConfigFile() c.open(args.config_file) adminuser = c.read_value("admin_user") ssh_private_key="{}_id_rsa".format(adminuser) # TODO: check ssh key exists if not args.user: sshuser = adminuser else...
.open(args.config_file) adminuser = c.read_value("admin_user") sshkey="{}_id_rsa".format(adminuser) # TODO: check ssh key exists fqdn = c.get_install_from_destination() if not fqdn: log.error(f"Missing 'install_from' property") sys.exit(1) if args.args and args.args[0] == ...
256
256
970
5
251
jithinjosepkl/azurehpc
pyazhpc/azhpc.py
Python
do_connect
do_connect
189
294
189
189
6fa7c312dddbc2c82c03829e1145a03cf215d859
bigcode/the-stack
train
c673a8fc34663429f0a1b3d2
train
function
def _wait_for_deployment(resource_group, deploy_name): building = True success = True del_lines = 1 while building: time.sleep(5) res = azutil.get_deployment_status(resource_group, deploy_name) log.debug(res) print("\033[F"*del_lines) del_lines = 1 ...
def _wait_for_deployment(resource_group, deploy_name):
building = True success = True del_lines = 1 while building: time.sleep(5) res = azutil.get_deployment_status(resource_group, deploy_name) log.debug(res) print("\033[F"*del_lines) del_lines = 1 for i in res: props = i["properties"] ...
.exists(public_key_file)): # create ssh keys key = rsa.generate_private_key( backend=crypto_default_backend(), public_exponent=65537, key_size=2048 ) private_key = key.private_bytes( crypto_serialization.Encoding.PEM, crypto_ser...
186
186
621
12
174
jithinjosepkl/azurehpc
pyazhpc/azhpc.py
Python
_wait_for_deployment
_wait_for_deployment
394
465
394
394
2f57e30a214aa24e698f2d40d1c425f73ec393b3
bigcode/the-stack
train
5d8229dcb7ef984148ebbd69
train
function
def do_init(args): if not os.path.exists(args.config_file): log.error("config file/dir does not exist") sys.exit(1) if args.show: vlist = set() if os.path.isfile(args.config_file): __add_unset_vars(vlist, args.config_file) else: for root, dirs, f...
def do_init(args):
if not os.path.exists(args.config_file): log.error("config file/dir does not exist") sys.exit(1) if args.show: vlist = set() if os.path.isfile(args.config_file): __add_unset_vars(vlist, args.config_file) else: for root, dirs, files in os.walk(arg...
obj = alldata.get("variables", {}) if type(varsobj) is str and varsobj.startswith("@"): if floc != "": floc = floc + "/" fname = floc + varsobj[1:] log.debug(f"variables are redirected to {fname}") with open(f"{fname}") as f: alldata = json.load(f) ...
160
160
535
5
155
jithinjosepkl/azurehpc
pyazhpc/azhpc.py
Python
do_init
do_init
90
157
90
90
569b41b47fc33bb9ab94fc8015f4c533358d696e
bigcode/the-stack
train
4fa73a298225b79ec2623cb2
train
function
def do_slurm_resume(args): log.debug(f"reading config file ({args.config_file})") while True: timestamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S") tmpdir = "azhpc_install_" + os.path.basename(args.config_file)[:-5] + "_" + timestamp if not os.path.isdir(tmpdir): brea...
def do_slurm_resume(args):
log.debug(f"reading config file ({args.config_file})") while True: timestamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S") tmpdir = "azhpc_install_" + os.path.basename(args.config_file)[:-5] + "_" + timestamp if not os.path.isdir(tmpdir): break log.warning(f"{tm...
: resource_list.append(resource_name) resource_name = resource_name[:-4] subscription_id = azutil.get_subscription_id() resource_group = config["resource_group"] vm_ids = [] nic_ids = [] disk_ids = [] for resource in resource_list: vm_ids.append(f"/subscriptions/{su...
231
231
771
7
224
jithinjosepkl/azurehpc
pyazhpc/azhpc.py
Python
do_slurm_resume
do_slurm_resume
512
595
512
512
dede7bd5afd38dbf1205a0b3d0f6cdf1c2422b01
bigcode/the-stack
train
ea96b9f71f0c2ac977c57288
train
function
def _create_private_key(private_key_file, public_key_file): if not (os.path.exists(private_key_file) and os.path.exists(public_key_file)): # create ssh keys key = rsa.generate_private_key( backend=crypto_default_backend(), public_exponent=65537, key_size=2048 ...
def _create_private_key(private_key_file, public_key_file):
if not (os.path.exists(private_key_file) and os.path.exists(public_key_file)): # create ssh keys key = rsa.generate_private_key( backend=crypto_default_backend(), public_exponent=65537, key_size=2048 ) private_key = key.private_bytes( c...
= " ".join(hosts) cmd = " ".join(args.args) _exec_command(fqdn, sshuser, ssh_private_key, f"pssh -H '{hostlist}' -i -t 0 '{cmd}'") def _create_private_key(private_key_file, public_key_file):
64
64
201
13
51
jithinjosepkl/azurehpc
pyazhpc/azhpc.py
Python
_create_private_key
_create_private_key
371
392
371
371
8cd9ea273d58cc44ae7fbc58acecd8f650f0eafb
bigcode/the-stack
train
2ef072af6e5080baf8dc5a4e
train
function
def do_status(args): log.debug("reading config file ({})".format(args.config_file)) c = azconfig.ConfigFile() c.open(args.config_file) adminuser = c.read_value("admin_user") ssh_private_key="{}_id_rsa".format(adminuser) fqdn = c.get_install_from_destination() if not fqdn: log.e...
def do_status(args):
log.debug("reading config file ({})".format(args.config_file)) c = azconfig.ConfigFile() c.open(args.config_file) adminuser = c.read_value("admin_user") ssh_private_key="{}_id_rsa".format(adminuser) fqdn = c.get_install_from_destination() if not fqdn: log.error(f"Missing 'insta...
"UserKnownHostsFile=/dev/null", "-i", sshkey, f"{sshuser}@{fqdn}" ] log.debug(" ".join(ssh_args + [ cmdline ])) os.execvp(ssh_exe, ssh_args + [ cmdline ]) def do_status(args):
64
64
177
5
59
jithinjosepkl/azurehpc
pyazhpc/azhpc.py
Python
do_status
do_status
308
322
308
308
43dc647d7c63711bd3d6cda56c45f2135f9c844c
bigcode/the-stack
train
657d904829939cb3fe3e31bd
train
function
def do_destroy(args): log.info("reading config file ({})".format(args.config_file)) config = azconfig.ConfigFile() config.open(args.config_file) log.warning("deleting entire resource group ({})".format(config.read_value("resource_group"))) if not args.force: log.info("you have 10s to chan...
def do_destroy(args):
log.info("reading config file ({})".format(args.config_file)) config = azconfig.ConfigFile() config.open(args.config_file) log.warning("deleting entire resource group ({})".format(config.read_value("resource_group"))) if not args.force: log.info("you have 10s to change your mind and ctrl-...
log.info("creating cyclecloud projects") azinstall.generate_cc_projects(config, f"{tmpdir}/projects") if "clusters" in config["cyclecloud"]: log.info("creating cyclecloud clusters") azinstall.generate_cc_clusters(config, f"{tmpdir}/clusters") def do_destroy(args)...
64
64
113
5
59
jithinjosepkl/azurehpc
pyazhpc/azhpc.py
Python
do_destroy
do_destroy
677
690
677
677
f16fd6f107dfe2a8f8c20382a8647e31f63428d0
bigcode/the-stack
train
48b51dbbab4393219655a3b8
train
function
def get_full_version() -> str: """Get full version, with build hash appended""" version = __version__ if (build_hash := get_build_hash()) != "": version += "." + build_hash return version
def get_full_version() -> str:
"""Get full version, with build hash appended""" version = __version__ if (build_hash := get_build_hash()) != "": version += "." + build_hash return version
_build_hash(fallback: Optional[str] = None) -> str: """Get build hash""" build_hash = environ.get(ENV_GIT_HASH_KEY, fallback if fallback else "") if build_hash == "" and fallback: return fallback return build_hash def get_full_version() -> str:
64
64
49
8
55
BeryJu/passbook
authentik/__init__.py
Python
get_full_version
get_full_version
17
22
17
17
c18e5dda7f7107806b32a835cc910766608b7be1
bigcode/the-stack
train
941502097f942909816c1035
train
function
def get_build_hash(fallback: Optional[str] = None) -> str: """Get build hash""" build_hash = environ.get(ENV_GIT_HASH_KEY, fallback if fallback else "") if build_hash == "" and fallback: return fallback return build_hash
def get_build_hash(fallback: Optional[str] = None) -> str:
"""Get build hash""" build_hash = environ.get(ENV_GIT_HASH_KEY, fallback if fallback else "") if build_hash == "" and fallback: return fallback return build_hash
"""authentik""" from os import environ from typing import Optional __version__ = "2022.6.2" ENV_GIT_HASH_KEY = "GIT_BUILD_HASH" def get_build_hash(fallback: Optional[str] = None) -> str:
55
64
58
16
39
BeryJu/passbook
authentik/__init__.py
Python
get_build_hash
get_build_hash
9
14
9
9
03ebb3bc75aaf8b9f4e1dff38909b545de5c8da5
bigcode/the-stack
train
0a37206617b4e51821767fce
train
class
class Data(): def __init__(self): super(Data, self).__init__() self.train_data = [] self.valid_data=[] self.test_data=[] self.in_hid=0
class Data():
def __init__(self): super(Data, self).__init__() self.train_data = [] self.valid_data=[] self.test_data=[] self.in_hid=0
torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, 1500, eta_min=1e-6) stats = [] res = [] best_val = 0 best_loss=100 train_step = 2250 st = time.time() feature,idl=feature_cal(graph) class Data():
64
64
43
3
61
superweisp/DHAN2022
PF2.py
Python
Data
Data
145
151
145
145
22ac2e4de74eaca0c7f84ba50e6d25b8e9deb62a
bigcode/the-stack
train
8146477c4a07d34c2462528c
train
function
def renamed_load(file_obj): return RenameUnpickler(file_obj).load()
def renamed_load(file_obj):
return RenameUnpickler(file_obj).load()
(self, module, name): renamed_module = module if module == "GPT_GNN.data" or module == 'data': renamed_module = "HRGAT.data" return super(RenameUnpickler, self).find_class(renamed_module, name) def renamed_load(file_obj):
64
64
17
6
58
superweisp/DHAN2022
PF2.py
Python
renamed_load
renamed_load
97
98
97
97
2f617900c54a3784afbfb9b9f1b0cc35588fbed4
bigcode/the-stack
train
65d6bbef12868873229f17c9
train
class
class RenameUnpickler(dill.Unpickler): def find_class(self, module, name): renamed_module = module if module == "GPT_GNN.data" or module == 'data': renamed_module = "HRGAT.data" return super(RenameUnpickler, self).find_class(renamed_module, name)
class RenameUnpickler(dill.Unpickler):
def find_class(self, module, name): renamed_module = module if module == "GPT_GNN.data" or module == 'data': renamed_module = "HRGAT.data" return super(RenameUnpickler, self).find_class(renamed_module, name)
() set_random_seed(2021) # if args.cuda != -1: # device = torch.device("cuda:" + str(args.cuda)) # else: # device = torch.device("cpu") device = torch.device("cpu") log={} class RenameUnpickler(dill.Unpickler):
63
64
73
11
52
superweisp/DHAN2022
PF2.py
Python
RenameUnpickler
RenameUnpickler
89
94
89
89
f3724ce112d2c5d5f8af11da9dc45a85b34d4ec0
bigcode/the-stack
train
15e38e90c27be50746795b2a
train
class
class PosixTester(unittest.TestCase): def setUp(self): # create empty file fp = open(test_support.TESTFN, 'w+') fp.close() self.teardown_files = [ test_support.TESTFN ] def tearDown(self): for teardown_file in self.teardown_files: os.unlink(teardown_file) ...
class PosixTester(unittest.TestCase):
def setUp(self): # create empty file fp = open(test_support.TESTFN, 'w+') fp.close() self.teardown_files = [ test_support.TESTFN ] def tearDown(self): for teardown_file in self.teardown_files: os.unlink(teardown_file) def testNoArgFunctions(self): ...
"Test posix functions" from test import test_support # Skip these tests if there is no posix module. posix = test_support.import_module('posix') import errno import time import os import platform import pwd import shutil import stat import sys import tempfile import unittest import warnings _DUMMY_SYMLINK = os.path...
120
256
5,791
8
112
FloMom/pypy
lib-python/2.7/test/test_posix.py
Python
PosixTester
PosixTester
26
618
26
27
6b91c0438ed649f3a605580bf44e777a8cc28edf
bigcode/the-stack
train
9196827613626f22afc2ce10
train
class
class PosixGroupsTester(unittest.TestCase): def setUp(self): if posix.getuid() != 0: raise unittest.SkipTest("not enough privileges") if not hasattr(posix, 'getgroups'): raise unittest.SkipTest("need posix.getgroups") if sys.platform == 'darwin': raise un...
class PosixGroupsTester(unittest.TestCase):
def setUp(self): if posix.getuid() != 0: raise unittest.SkipTest("not enough privileges") if not hasattr(posix, 'getgroups'): raise unittest.SkipTest("need posix.getgroups") if sys.platform == 'darwin': raise unittest.SkipTest("getgroups(2) is broken on OS...
.O_WRONLY | os.O_CREAT) # raises finally: if fd is not None: os.close(fd) self.assertFalse(os.path.exists(fn)) self.assertRaises(TypeError, os.mkdir, fn_with_NUL) self.assertFalse(os.path.exists(fn)) open(fn, 'wb').close() self.assertRaises(Typ...
92
92
308
9
83
FloMom/pypy
lib-python/2.7/test/test_posix.py
Python
PosixGroupsTester
PosixGroupsTester
621
654
621
622
c625e8bca7c09dea8d9fb4d467fcbd0e577a8976
bigcode/the-stack
train
2bc24a944b874f10449acd70
train
function
def test_main(): test_support.run_unittest(PosixTester, PosixGroupsTester)
def test_main():
test_support.run_unittest(PosixTester, PosixGroupsTester)
ittest.skipUnless(hasattr(posix, 'setgroups'), 'test needs posix.setgroups()') def test_setgroups(self): for groups in [[0], range(16)]: posix.setgroups(groups) self.assertListEqual(groups, posix.getgroups()) def test_main():
64
64
19
4
60
FloMom/pypy
lib-python/2.7/test/test_posix.py
Python
test_main
test_main
657
658
657
657
a195dd2f1542df2b58781134dde207de4d5d1404
bigcode/the-stack
train
be96fcbffd6358d481ee0bab
train
class
class LocatorTests(unittest.TestCase): @classmethod def setUpClass(cls): desired_cap = { "deviceName": "emulator-5554", "platformName": "Android", "app": "/Users/govind794/Downloads/com.aefyr.sai_2020-06-19.apk", # "appPackage": "com.google.android.apps.n...
class LocatorTests(unittest.TestCase): @classmethod
def setUpClass(cls): desired_cap = { "deviceName": "emulator-5554", "platformName": "Android", "app": "/Users/govind794/Downloads/com.aefyr.sai_2020-06-19.apk", # "appPackage": "com.google.android.apps.nexuslauncher", # "appWaitActivity": "com.goog...
from appium import webdriver import time import unittest class LocatorTests(unittest.TestCase): @classmethod
23
140
467
11
11
govind794/Python-Appium-Automation
Learn/Locators.py
Python
LocatorTests
LocatorTests
6
52
6
8
e195233dedc07248d728ab79e01dd5ddc0d5cac7
bigcode/the-stack
train
3461f3d00010c98929b44d9a
train
function
def test_root_redirect(client): r_root = client.get("/") assert r_root.status_code == 302 assert r_root.headers["Location"].endswith("/overview/")
def test_root_redirect(client):
r_root = client.get("/") assert r_root.status_code == 302 assert r_root.headers["Location"].endswith("/overview/")
def test_root_redirect(client):
6
64
36
6
0
datalad/datalad-registry
datalad_registry/tests/test_root.py
Python
test_root_redirect
test_root_redirect
1
4
1
1
68505a9a8dda3daddf8ef673d6aa3f9f94a44bd8
bigcode/the-stack
train
62284dadbf2b6a358c98a53f
train
function
def demo(N=23): from nltk.grammar import CFG print("Generating the first %d sentences for demo grammar:" % (N,)) print(demo_grammar) grammar = CFG.fromstring(demo_grammar) for n, sent in enumerate(generate(grammar, n=N), 1): print("%3d. %s" % (n, " ".join(sent)))
def demo(N=23):
from nltk.grammar import CFG print("Generating the first %d sentences for demo grammar:" % (N,)) print(demo_grammar) grammar = CFG.fromstring(demo_grammar) for n, sent in enumerate(generate(grammar, n=N), 1): print("%3d. %s" % (n, " ".join(sent)))
P NP VP -> 'slept' | 'saw' NP | 'walked' PP Det -> 'the' | 'a' N -> 'man' | 'park' | 'dog' P -> 'in' | 'with' """ def demo(N=23):
64
64
83
6
58
agannon/nltk
nltk/parse/generate.py
Python
demo
demo
78
85
78
78
97d6acffa9cb6a8b0a3104f31b249720796d0bee
bigcode/the-stack
train
64ff66390c549c74a724acdf
train
function
def generate(grammar, start=None, depth=None, n=None): """ Generates an iterator of all sentences from a CFG. :param grammar: The Grammar used to generate sentences. :param start: The Nonterminal from which to start generate sentences. :param depth: The maximal depth of the generated tree. :par...
def generate(grammar, start=None, depth=None, n=None):
""" Generates an iterator of all sentences from a CFG. :param grammar: The Grammar used to generate sentences. :param start: The Nonterminal from which to start generate sentences. :param depth: The maximal depth of the generated tree. :param n: The maximum number of sentences to return. :r...
Ljunglöf <peter.ljunglof@heatherleaf.se> # URL: <http://nltk.org/> # For license information, see LICENSE.TXT # import itertools import sys from nltk.grammar import Nonterminal def generate(grammar, start=None, depth=None, n=None):
64
64
148
13
50
agannon/nltk
nltk/parse/generate.py
Python
generate
generate
16
36
16
16
5b1b9d2c704659e4995f3dc272a21d79539ef347
bigcode/the-stack
train
a9a49d276c4abacb06b42f44
train
function
def _generate_one(grammar, item, depth): if depth > 0: if isinstance(item, Nonterminal): for prod in grammar.productions(lhs=item): for frag in _generate_all(grammar, prod.rhs(), depth - 1): yield frag else: yield [item]
def _generate_one(grammar, item, depth):
if depth > 0: if isinstance(item, Nonterminal): for prod in grammar.productions(lhs=item): for frag in _generate_all(grammar, prod.rhs(), depth - 1): yield frag else: yield [item]
.message == "maximum recursion depth exceeded": # Helpful error message while still showing the recursion stack. raise RuntimeError( "The grammar has rule(s) that yield infinite recursion!!" ) else: raise else: y...
63
64
66
10
53
agannon/nltk
nltk/parse/generate.py
Python
_generate_one
_generate_one
57
64
57
57
ee9e7d02b4bb663afcac086cffcb8f4c86b19aa8
bigcode/the-stack
train
d9460b1de2f2e7f7915926bb
train
function
def _generate_all(grammar, items, depth): if items: try: for frag1 in _generate_one(grammar, items[0], depth): for frag2 in _generate_all(grammar, items[1:], depth): yield frag1 + frag2 except RuntimeError as _error: if _error.message == "m...
def _generate_all(grammar, items, depth):
if items: try: for frag1 in _generate_one(grammar, items[0], depth): for frag2 in _generate_all(grammar, items[1:], depth): yield frag1 + frag2 except RuntimeError as _error: if _error.message == "maximum recursion depth exceeded": ...
if not start: start = grammar.start() if depth is None: depth = sys.maxsize iter = _generate_all(grammar, [start], depth) if n: iter = itertools.islice(iter, n) return iter def _generate_all(grammar, items, depth):
64
64
122
10
53
agannon/nltk
nltk/parse/generate.py
Python
_generate_all
_generate_all
39
54
39
39
70c8178e7403f5c7bb47d21c046d6ff0e67629a1
bigcode/the-stack
train
50151c2db5962e5064919502
train
function
def FaceReverseParse(pollContent): return ''.join( (' /%s ' % faceMap.get(m[1], '未知表情')) if isinstance(m, list) else str(m) for m in pollContent[1:] )
def FaceReverseParse(pollContent):
return ''.join( (' /%s ' % faceMap.get(m[1], '未知表情')) if isinstance(m, list) else str(m) for m in pollContent[1:] )
= line.strip().split() code = int(code) faceMap[code] = face faceMap[face] = code p = p + '/' + face + '|' p = p[:-1] + ')' pat = re.compile(p) def FaceReverseParse(pollContent):
64
64
53
8
56
lc4t/qqbot
qqbot/facemap.py
Python
FaceReverseParse
FaceReverseParse
130
134
130
130
8242267024e8d3eb99687f1c011d9f1a589d9cc2
bigcode/the-stack
train
31c829da7458efa62c2dd2b7
train
function
def FaceParse(sendContent): result = pat.split(sendContent) for i in range(1, len(result), 2): result[i] = ['face', faceMap.get(result[i][1:], 134)] s = 0 if result[0] else 1 result[-1] or result.pop() return result[s:]
def FaceParse(sendContent):
result = pat.split(sendContent) for i in range(1, len(result), 2): result[i] = ['face', faceMap.get(result[i][1:], 134)] s = 0 if result[0] else 1 result[-1] or result.pop() return result[s:]
= re.compile(p) def FaceReverseParse(pollContent): return ''.join( (' /%s ' % faceMap.get(m[1], '未知表情')) if isinstance(m, list) else str(m) for m in pollContent[1:] ) def FaceParse(sendContent):
64
64
75
6
58
lc4t/qqbot
qqbot/facemap.py
Python
FaceParse
FaceParse
136
142
136
136
d91e55028538a9443f1077ccbfc5b65dc0e72f60
bigcode/the-stack
train
fa6c555b045544b1a91081ab
train
class
class CaptionPlugin(CMSPluginBase): name = _('Carousel Caption') module = _("Carousel") allow_children = True render_template = 'cmsplugin_carousel/caption.html'
class CaptionPlugin(CMSPluginBase):
name = _('Carousel Caption') module = _("Carousel") allow_children = True render_template = 'cmsplugin_carousel/caption.html'
, self).render(context, instance, placeholder) context.update({ 'auto_id': 'carousel_%s' % instance.pk, 'rotate_interval': instance.interval * 1000, 'objects_list': instance.child_plugin_instances, }) return context class CaptionPlugin(CMSPluginBase):
64
64
40
8
55
tygermarshall/djangocms-carousel
src/cmsplugin_carousel/cms_plugins.py
Python
CaptionPlugin
CaptionPlugin
26
30
26
26
20ddb4c7af50be5909331c42ed92e9a92b22f3e5
bigcode/the-stack
train
9fa9e8577636a9b2a53fde59
train
class
class CMSCarouselPlugin(CMSPluginBase): name = _("Carousel") module = _("Carousel") model = CarouselPlugin allow_children = True render_template = "cmsplugin_carousel/carousel.html" cache = False def render(self, context, instance, placeholder): context = super(CMSCarouselPlugin, se...
class CMSCarouselPlugin(CMSPluginBase):
name = _("Carousel") module = _("Carousel") model = CarouselPlugin allow_children = True render_template = "cmsplugin_carousel/carousel.html" cache = False def render(self, context, instance, placeholder): context = super(CMSCarouselPlugin, self).render(context, instance, placeholde...
from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from django.utils.translation import ugettext_lazy as _ from .models import CarouselPlugin class CMSCarouselPlugin(CMSPluginBase):
44
64
126
9
34
tygermarshall/djangocms-carousel
src/cmsplugin_carousel/cms_plugins.py
Python
CMSCarouselPlugin
CMSCarouselPlugin
8
23
8
8
a2175a30f78d4914e632a19c27c40c994e33a97d
bigcode/the-stack
train
b92e8a207e32bcebfebed060
train
class
class CourseListView(generic.ListView): template_name = 'onlinecourse/course_list_bootstrap.html' context_object_name = 'course_list' def get_queryset(self): user = self.request.user courses = Course.objects.order_by('-total_enrollment')[:10] for course in courses: if us...
class CourseListView(generic.ListView):
template_name = 'onlinecourse/course_list_bootstrap.html' context_object_name = 'course_list' def get_queryset(self): user = self.request.user courses = Course.objects.order_by('-total_enrollment')[:10] for course in courses: if user.is_authenticated: cou...
user.id is not None: # Check if user enrolled num_results = Enrollment.objects.filter(user=user, course=course).count() if num_results > 0: is_enrolled = True return is_enrolled # CourseListView class CourseListView(generic.ListView):
64
64
89
9
54
thomaskrug96/final-cloud-app-with-database
onlinecourse/views.py
Python
CourseListView
CourseListView
74
84
74
74
243adb5981dd5380b33727f68bc7a6163285a422
bigcode/the-stack
train
feb15ed1ef6aa7f054835390
train
function
def login_request(request): context = {} if request.method == "POST": username = request.POST['username'] password = request.POST['psw'] user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect('on...
def login_request(request):
context = {} if request.method == "POST": username = request.POST['username'] password = request.POST['psw'] user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect('onlinecourse:index') e...
_name=first_name, last_name=last_name, password=password) login(request, user) return redirect("onlinecourse:index") else: context['message'] = "User already exists." return render(request, 'onlinecourse/user_registratio...
64
64
115
5
59
thomaskrug96/final-cloud-app-with-database
onlinecourse/views.py
Python
login_request
login_request
42
55
42
42
4ae6c6f290a528d85c5d0a4982f4df0a4a1afbac
bigcode/the-stack
train
a2200feaad7224815da60869
train
function
def enroll(request, course_id): course = get_object_or_404(Course, pk=course_id) user = request.user is_enrolled = check_if_enrolled(user, course) if not is_enrolled and user.is_authenticated: # Create an enrollment Enrollment.objects.create(user=user, course=course, mode='honor') ...
def enroll(request, course_id):
course = get_object_or_404(Course, pk=course_id) user = request.user is_enrolled = check_if_enrolled(user, course) if not is_enrolled and user.is_authenticated: # Create an enrollment Enrollment.objects.create(user=user, course=course, mode='honor') course.total_enrollment += 1 ...
for course in courses: if user.is_authenticated: course.is_enrolled = check_if_enrolled(user, course) return courses class CourseDetailView(generic.DetailView): model = Course template_name = 'onlinecourse/course_detail_bootstrap.html' def enroll(request, course_id)...
64
64
109
7
57
thomaskrug96/final-cloud-app-with-database
onlinecourse/views.py
Python
enroll
enroll
92
103
92
92
fc5eda3e40abe960153d5b4973e0f6a9b2a3ad3e
bigcode/the-stack
train
6fe753abc75b5ac57fa1bfb6
train
class
class CourseDetailView(generic.DetailView): model = Course template_name = 'onlinecourse/course_detail_bootstrap.html'
class CourseDetailView(generic.DetailView):
model = Course template_name = 'onlinecourse/course_detail_bootstrap.html'
_queryset(self): user = self.request.user courses = Course.objects.order_by('-total_enrollment')[:10] for course in courses: if user.is_authenticated: course.is_enrolled = check_if_enrolled(user, course) return courses class CourseDetailView(generic.DetailView...
64
64
27
9
54
thomaskrug96/final-cloud-app-with-database
onlinecourse/views.py
Python
CourseDetailView
CourseDetailView
87
89
87
87
22ebbd21fe15035a12da6ca2a6d21a89c2ac5fdd
bigcode/the-stack
train
ecd0be04d1bfc445c41236d3
train
function
def registration_request(request): context = {} if request.method == 'GET': return render(request, 'onlinecourse/user_registration_bootstrap.html', context) elif request.method == 'POST': # Check if user exists username = request.POST['username'] password = request.POST['psw'...
def registration_request(request):
context = {} if request.method == 'GET': return render(request, 'onlinecourse/user_registration_bootstrap.html', context) elif request.method == 'POST': # Check if user exists username = request.POST['username'] password = request.POST['psw'] first_name = request.POST...
import get_object_or_404, render, redirect from django.urls import reverse from django.views import generic from django.contrib.auth import login, logout, authenticate import logging # Get an instance of a logger logger = logging.getLogger(__name__) # Create your views here. def registration_request(request):
64
64
191
5
59
thomaskrug96/final-cloud-app-with-database
onlinecourse/views.py
Python
registration_request
registration_request
16
39
16
16
79c9b9ffd10582579511758d0b6a86969a835966
bigcode/the-stack
train
f8abdb1ae3bd261e2b67d0d6
train
function
def submit(request, course_id): user = request.user course = get_object_or_404(Course, pk=course_id) enrollment = Enrollment.objects.filter(user=user, course=course).get() submission = Submission.objects.create(enrollment_id=enrollment.id) selected_choices = extract_answers(request) for choice i...
def submit(request, course_id):
user = request.user course = get_object_or_404(Course, pk=course_id) enrollment = Enrollment.objects.filter(user=user, course=course).get() submission = Submission.objects.create(enrollment_id=enrollment.id) selected_choices = extract_answers(request) for choice in selected_choices: c = ...
the associated enrollment object created when the user enrolled the course # Create a submission object referring to the enrollment # Collect the selected choices from exam form # Add each selected choice object to the submission object # Redirect to show_exam_result with the submis...
64
64
120
7
56
thomaskrug96/final-cloud-app-with-database
onlinecourse/views.py
Python
submit
submit
112
122
112
112
2dad71886d585790922f112e48be794ac76e869e
bigcode/the-stack
train
14eb252bce42e82a32e86f5c
train
function
def logout_request(request): logout(request) return redirect('onlinecourse:index')
def logout_request(request):
logout(request) return redirect('onlinecourse:index')
) return redirect('onlinecourse:index') else: context['message'] = "Invalid username or password." return render(request, 'onlinecourse/user_login_bootstrap.html', context) else: return render(request, 'onlinecourse/user_login_bootstrap.html', context) def logout_...
64
64
17
5
59
thomaskrug96/final-cloud-app-with-database
onlinecourse/views.py
Python
logout_request
logout_request
58
60
58
58
976fee440467cce40bb9915023ed90fd8096cd94
bigcode/the-stack
train
32cb78420184717120badb28
train
function
def show_exam_result(request, course_id, submission_id): context = {} course = get_object_or_404(Course, pk=course_id) submission = get_object_or_404(Submission, pk=submission_id) selected_choices = Submission.objects.filter(id = submission_id).values_list('choices', flat=True) grade = 0 for i i...
def show_exam_result(request, course_id, submission_id):
context = {} course = get_object_or_404(Course, pk=course_id) submission = get_object_or_404(Submission, pk=submission_id) selected_choices = Submission.objects.filter(id = submission_id).values_list('choices', flat=True) grade = 0 for i in submission.choices.all().filter(is_correct=True).values...
on the following logic: # Get course and submission based on their ids # Get the selected choice ids from the submission record # For each selected choice, check if it is a correct answer or not # Calculate the total score def show_exam_result(request, course_id, submission_id):
64
64
152
12
51
thomaskrug96/final-cloud-app-with-database
onlinecourse/views.py
Python
show_exam_result
show_exam_result
141
152
141
141
a6e258b82b0b75dffbe1574fcf043686d28b66a0
bigcode/the-stack
train
d218f3d7505bc69e6bf27cab
train
function
def check_if_enrolled(user, course): is_enrolled = False if user.id is not None: # Check if user enrolled num_results = Enrollment.objects.filter(user=user, course=course).count() if num_results > 0: is_enrolled = True return is_enrolled
def check_if_enrolled(user, course):
is_enrolled = False if user.id is not None: # Check if user enrolled num_results = Enrollment.objects.filter(user=user, course=course).count() if num_results > 0: is_enrolled = True return is_enrolled
or password." return render(request, 'onlinecourse/user_login_bootstrap.html', context) else: return render(request, 'onlinecourse/user_login_bootstrap.html', context) def logout_request(request): logout(request) return redirect('onlinecourse:index') def check_if_enrolled(user, course...
64
64
68
9
55
thomaskrug96/final-cloud-app-with-database
onlinecourse/views.py
Python
check_if_enrolled
check_if_enrolled
63
70
63
63
b9272c723d05ee1a907b693feb426d3459a949ef
bigcode/the-stack
train
ae8ec2e898472aca94ad4c8b
train
function
def extract_answers(request): submitted_anwsers = [] for key in request.POST: if key.startswith('choice'): value = request.POST[key] choice_id = int(value) submitted_anwsers.append(choice_id) return submitted_anwsers
def extract_answers(request):
submitted_anwsers = [] for key in request.POST: if key.startswith('choice'): value = request.POST[key] choice_id = int(value) submitted_anwsers.append(choice_id) return submitted_anwsers
get() submission.choices.add(c) submission.save() return HttpResponseRedirect(reverse(viewname='onlinecourse:show_exam_result', args=(course_id, submission.id))) # <HINT> A example method to collect the selected choices from the exam form from the request object def extract_answers(request):
64
64
56
5
58
thomaskrug96/final-cloud-app-with-database
onlinecourse/views.py
Python
extract_answers
extract_answers
125
132
125
125
10f16a7a0cfa0c09c7df6af4129ba8f48df41cc6
bigcode/the-stack
train
bde7d90c40a227466cf33e11
train
function
@click.command('analyse') @click.option( '--method', '-m', type=click.Choice([str(m) for m in show()], case_sensitive=False), multiple=True, help='Analytical method to run on certificate(s) [all methods run by default].') @click.option('--description', '-d', is_flag=True, help='Shows additional info...
@click.command('analyse') @click.option( '--method', '-m', type=click.Choice([str(m) for m in show()], case_sensitive=False), multiple=True, help='Analytical method to run on certificate(s) [all methods run by default].') @click.option('--description', '-d', is_flag=True, help='Shows additional info...
"""Runs analytical methods on certificate chain c1 c2 cN (endpoint cert --> CA cert).""" if description: for info in show(True): click.echo(info) if certificate: if not method: method = show() validation_method_arguments = {"reference_time": int(reference_da...
@click.command('analyse') @click.option( '--method', '-m', type=click.Choice([str(m) for m in show()], case_sensitive=False), multiple=True, help='Analytical method to run on certificate(s) [all methods run by default].') @click.option('--description', '-d', is_flag=True, help='Shows additional info...
151
75
251
151
0
crocs-muni/cert-validataion-stats
cevast/analysis/cli.py
Python
analysis_group
analysis_group
14
43
14
30
5b8c9dd00cf691c864438abec004a36ff64a938e
bigcode/the-stack
train
4633fce9232b1bb644111564
train
class
@override_settings( UAA_CLIENT_ID='clientid', UAA_CLIENT_SECRET='clientsecret', UAA_AUTH_URL='https://example.org/auth', UAA_TOKEN_URL='https://example.org/token' ) class AuthenticationTests(TestCase): def test_get_auth_url_works(self): self.assertEqual(auth.get_auth_url(None), 'https://exa...
@override_settings( UAA_CLIENT_ID='clientid', UAA_CLIENT_SECRET='clientsecret', UAA_AUTH_URL='https://example.org/auth', UAA_TOKEN_URL='https://example.org/token' ) class AuthenticationTests(TestCase):
def test_get_auth_url_works(self): self.assertEqual(auth.get_auth_url(None), 'https://example.org/auth') def test_get_token_url_works(self): self.assertEqual(auth.get_token_url(None), 'https://example.org/token') @mock.patch('uaa_client.authentication.logger.warn') def test_exchange_co...
from unittest import mock import urllib.parse import jwt from django.test import TestCase from django.test.utils import override_settings from django.contrib.auth.models import User import httmock from .. import authentication as auth @override_settings( UAA_CLIENT_ID='clientid', UAA_CLIENT_SECRET='clientsecre...
99
247
826
53
45
18F/acquisitions.18f.gov
uaa_client/tests/test_authentication.py
Python
AuthenticationTests
AuthenticationTests
12
106
12
19
9b4b1f15fab49d5d3c5837c2a14ad6ab819590bb
bigcode/the-stack
train