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
e62f8b2adeffe3bfa615ee64
train
function
def main(): configs = collect_configurations() train(configs) statistics_file = eval(configs) make_plots(statistics_file)
def main():
configs = collect_configurations() train(configs) statistics_file = eval(configs) make_plots(statistics_file)
/plumeEnsemble-v1-dvr.json", "config-files/plumeEnsemble-v2-dvr.json", ] VOLUME_FILES = "volumes/ScalarFlow/sim_{ensemble:06d}/volume_{time:06d}.cvol" VOLUME_TIMESTEP = 100 def main():
64
64
31
3
60
khoehlein/fV-SRN
applications/volnet/eval_world_DensityVsColorGrid_NoImportance.py
Python
main
main
30
34
30
30
c524349cec9c616849f7b1d963b1e46e88a3ef75
bigcode/the-stack
train
8656d76283b5c32efe3d5404
train
function
def collect_configurations(): return [ ("density", 0), ("rgbo", 0), ("rgbo", 1), ("rgbo", 2), ]
def collect_configurations():
return [ ("density", 0), ("rgbo", 0), ("rgbo", 1), ("rgbo", 2), ]
Flow/sim_{ensemble:06d}/volume_{time:06d}.cvol" VOLUME_TIMESTEP = 100 def main(): configs = collect_configurations() train(configs) statistics_file = eval(configs) make_plots(statistics_file) def collect_configurations():
64
64
41
5
59
khoehlein/fV-SRN
applications/volnet/eval_world_DensityVsColorGrid_NoImportance.py
Python
collect_configurations
collect_configurations
36
42
36
36
6491113c99eb31f6b1587d3fbe7e3601b44fd031
bigcode/the-stack
train
d0ba36a1485a9a07ce850f27
train
function
def eval(configs): print("Evaluate") statistics_file = 'volnet/results/eval_world_DensityVsColorGrid_NoImportance/stats.json' if os.path.exists(statistics_file): print("Statistics file already exists!") return statistics_file import common.utils as utils import pyrenderer ...
def eval(configs):
print("Evaluate") statistics_file = 'volnet/results/eval_world_DensityVsColorGrid_NoImportance/stats.json' if os.path.exists(statistics_file): print("Statistics file already exists!") return statistics_file import common.utils as utils import pyrenderer from volnet.infer...
1]-1)), "--volumetric_features_resolution", str(GRID_RESOLUTION), "--volumetric_features_channels", str(GRID_CHANNELS), "--logdir", 'volnet/results/eval_world_DensityVsColorGrid_NoImportance/log', "--modeldir", 'volnet/results/eval_world_DensityVsColorGrid_NoImportance/model', ...
255
256
974
5
250
khoehlein/fV-SRN
applications/volnet/eval_world_DensityVsColorGrid_NoImportance.py
Python
eval
eval
95
197
95
95
9b2b2661de82898d245b815895f7c7caa02b23aa
bigcode/the-stack
train
c0b6c45b7b7b92b85a7f6b9b
train
function
def get_args_and_hdf5_file(output_mode, config_file_index:int): """ Assembles the command line arguments for training and the filename for the hdf5-file with the results :param activation: the activation function name :param network: the network combination (channels, layers) :return: args...
def get_args_and_hdf5_file(output_mode, config_file_index:int):
""" Assembles the command line arguments for training and the filename for the hdf5-file with the results :param activation: the activation function name :param network: the network combination (channels, layers) :return: args, filename """ output_name = "run_%s_%d"%(output_mode, ...
/plumeEnsemble-v1-dvr.json", "config-files/plumeEnsemble-v2-dvr.json", ] VOLUME_FILES = "volumes/ScalarFlow/sim_{ensemble:06d}/volume_{time:06d}.cvol" VOLUME_TIMESTEP = 100 def main(): configs = collect_configurations() train(configs) statistics_file = eval(configs) make_plots(statistics_file...
149
150
502
16
133
khoehlein/fV-SRN
applications/volnet/eval_world_DensityVsColorGrid_NoImportance.py
Python
get_args_and_hdf5_file
get_args_and_hdf5_file
44
82
44
44
a33cb11136c6fea2b8e14430791d7e42a78bea14
bigcode/the-stack
train
034e419e601d2347bbd3e5d6
train
function
def train(configs): print("Configurations:", len(configs)) for output_mode, config_file_index in configs: args, filename = get_args_and_hdf5_file(output_mode, config_file_index) if os.path.exists(filename): print("Skipping test", filename) else: print("\n==...
def train(configs):
print("Configurations:", len(configs)) for output_mode, config_file_index in configs: args, filename = get_args_and_hdf5_file(output_mode, config_file_index) if os.path.exists(filename): print("Skipping test", filename) else: print("\n=======================...
'--name', output_name, '--save_frequency', '50' ] hdf5_file = 'volnet/results/eval_world_DensityVsColorGrid_NoImportance/hdf5/' + output_name + ".hdf5" return parameters, hdf5_file def train(configs):
64
64
93
5
58
khoehlein/fV-SRN
applications/volnet/eval_world_DensityVsColorGrid_NoImportance.py
Python
train
train
84
93
84
84
353d2f12414b84d548ab2f18ec7dac9db94a6cc3
bigcode/the-stack
train
449cb7dafd33a080a6147018
train
function
def make_plots(statistics_file): print("\n===================================== Make Plots") with open(statistics_file, "r") as f: stats = json.load(f) output_folder = os.path.split(statistics_file)[0] FILETYPE = "eps" numCols = len(stats) numClasses = 2 fig, axs = plt.subp...
def make_plots(statistics_file):
print("\n===================================== Make Plots") with open(statistics_file, "r") as f: stats = json.load(f) output_folder = os.path.split(statistics_file)[0] FILETYPE = "eps" numCols = len(stats) numClasses = 2 fig, axs = plt.subplots(1, 2, sharex=True, figsize=(6...
Model.EvaluationMode.TENSORCORES_MIXED, reference_images, os.path.join(image_folder, 'density%03d.png'), True, True) local_stats['density-time'] = time local_stats['density-ssim'] = ssim local_stats['density-lpips'] = lpips output_stats.append(local_stats)...
127
127
425
8
118
khoehlein/fV-SRN
applications/volnet/eval_world_DensityVsColorGrid_NoImportance.py
Python
make_plots
make_plots
199
237
199
199
a3fc5975e3df82853ce73d5243f85841eff25b66
bigcode/the-stack
train
9cb64b68ba9512ddb2c2384f
train
class
class Arcd(nlp.GeneratorBasedBuilder): """ARCD: Arabic Reading Comprehension Dataset.""" _URL = "https://raw.githubusercontent.com/husseinmozannar/SOQAL/master/data/" _DEV_FILE = "arcd-test.json" _TRAINING_FILE = "arcd-train.json" BUILDER_CONFIGS = [ ArcdConfig( name="plain_tex...
class Arcd(nlp.GeneratorBasedBuilder):
"""ARCD: Arabic Reading Comprehension Dataset.""" _URL = "https://raw.githubusercontent.com/husseinmozannar/SOQAL/master/data/" _DEV_FILE = "arcd-test.json" _TRAINING_FILE = "arcd-train.json" BUILDER_CONFIGS = [ ArcdConfig( name="plain_text", version=nlp.Version("1....
: (1) a document retriever using a hierarchical TF-IDF approach and (2) a neural reading comprehension model using the pre-trained bi-directional transformer BERT. Our experiments on ARCD indicate the effectiveness of our approach with our BERT-based reader achieving a 61.3 F1 score, and our open domain system SOQAL ac...
189
189
633
10
179
tongni1975/nlp
datasets/arcd/arcd.py
Python
Arcd
Arcd
46
118
46
46
d99dec4e19a8bce76cee1093409549c24e730676
bigcode/the-stack
train
adbf8d77d2fd9b5a9ed06355
train
class
class ArcdConfig(nlp.BuilderConfig): """BuilderConfig for ARCD.""" def __init__(self, **kwargs): """BuilderConfig for ARCD. Args: **kwargs: keyword arguments forwarded to super. """ super(ArcdConfig, self).__init__(**kwargs)
class ArcdConfig(nlp.BuilderConfig):
"""BuilderConfig for ARCD.""" def __init__(self, **kwargs): """BuilderConfig for ARCD. Args: **kwargs: keyword arguments forwarded to super. """ super(ArcdConfig, self).__init__(**kwargs)
score, and our open domain system SOQAL achieving a 27.6 F1 score.} } """ _DESCRIPTION = """\ Arabic Reading Comprehension Dataset (ARCD) composed of 1,395 questions\ posed by crowdworkers on Wikipedia articles. """ class ArcdConfig(nlp.BuilderConfig):
64
64
64
9
55
tongni1975/nlp
datasets/arcd/arcd.py
Python
ArcdConfig
ArcdConfig
34
43
34
34
6f7857c918da1564299cfc9205aa6fb2bb4bf715
bigcode/the-stack
train
3997c00accfb86e39e498567
train
class
class BenchmarkCommand(setuptools.Command): description = 'Benchmark exfoliate against pure aiohttp.' user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): os.system(f'{sys.executable} benchmark.py') sys.exit()
class BenchmarkCommand(setuptools.Command):
description = 'Benchmark exfoliate against pure aiohttp.' user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): os.system(f'{sys.executable} benchmark.py') sys.exit()
wheel (universal) distribution...') os.system(f'{sys.executable} setup.py sdist bdist_wheel --universal') print('uploading the package to PyPi via Twine...') os.system('twine upload dist/*') sys.exit() class BenchmarkCommand(setuptools.Command):
64
64
63
8
56
brianjpetersen/exfoliate
setup.py
Python
BenchmarkCommand
BenchmarkCommand
55
66
55
56
c4420e5d44634a2242e26b3383d4ac087d9d91a4
bigcode/the-stack
train
d9be31d83044126db098d708
train
class
class PublishCommand(setuptools.Command): description = 'Build and publish the package.' user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): try: print('removing previous builds...') shutil.rmtree(os.path.jo...
class PublishCommand(setuptools.Command):
description = 'Build and publish the package.' user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): try: print('removing previous builds...') shutil.rmtree(os.path.join(__where__, 'dist')) except FileNotFo...
Test the exfoliate package with pytest.' user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): import pytest exit_code = pytest.main(['tests.py', ]) sys.exit(exit_code) class PublishCommand(setuptools.Command):
64
64
141
8
56
brianjpetersen/exfoliate
setup.py
Python
PublishCommand
PublishCommand
33
52
33
34
a46d6226df42789c832c6b3194d22d76928868b6
bigcode/the-stack
train
6a5d75274607ab50d0e49833
train
class
class TestCommand(setuptools.Command): description = 'Test the exfoliate package with pytest.' user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): import pytest exit_code = pytest.main(['tests.py', ]) sys.exit(e...
class TestCommand(setuptools.Command):
description = 'Test the exfoliate package with pytest.' user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): import pytest exit_code = pytest.main(['tests.py', ]) sys.exit(exit_code)
# issue for more information: https://github.com/pypa/packaging-problems/issues/46 with open(os.path.join(__where__, 'DESCRIPTION.rst'), 'rb') as f: long_description = f.read().decode('utf-8').strip() class TestCommand(setuptools.Command):
64
64
68
8
56
brianjpetersen/exfoliate
setup.py
Python
TestCommand
TestCommand
18
30
18
19
8ed62cfad60cd6e2a025c2643a3621f29c631b10
bigcode/the-stack
train
6f340bffc2794df691e99568
train
class
class HomePageView(TemplateView): template_name = "home.html" def get_context_data(self, **kwargs): context = super(HomePageView, self).get_context_data(**kwargs) return context
class HomePageView(TemplateView):
template_name = "home.html" def get_context_data(self, **kwargs): context = super(HomePageView, self).get_context_data(**kwargs) return context
from django.views.generic.base import TemplateView class HomePageView(TemplateView):
17
64
46
8
8
moshthepitt/django-template3
template3/apps/core/views.py
Python
HomePageView
HomePageView
4
10
4
5
b1f0f6e2c371d0b8e80e639b78f652ddc1eb84c3
bigcode/the-stack
train
393a7d84e606a5491089db66
train
class
class Dashboard(TemplateView): template_name = "dashboard.html" def get_context_data(self, **kwargs): context = super(Dashboard, self).get_context_data(**kwargs) return context
class Dashboard(TemplateView):
template_name = "dashboard.html" def get_context_data(self, **kwargs): context = super(Dashboard, self).get_context_data(**kwargs) return context
from django.views.generic.base import TemplateView class HomePageView(TemplateView): template_name = "home.html" def get_context_data(self, **kwargs): context = super(HomePageView, self).get_context_data(**kwargs) return context class Dashboard(TemplateView):
61
64
43
6
54
moshthepitt/django-template3
template3/apps/core/views.py
Python
Dashboard
Dashboard
13
19
13
14
49288be0a6eb3f963e7362a474c485663573f7ea
bigcode/the-stack
train
f6711d4042afd1280fde7ed6
train
class
class ParseError(Exception): """An error occurred during parsing.""" pass
class ParseError(Exception):
"""An error occurred during parsing.""" pass
types of supported options, visit [the documentation of argparse](https://docs.python.org/2/library/argparse.html). """ import argparse import shlex from textwrap import dedent from evennia import Command, InterruptCommand from evennia.utils.ansi import raw class ParseError(Exception):
64
64
16
5
58
davidrideout/evennia
evennia/contrib/base_systems/unixcommand/unixcommand.py
Python
ParseError
ParseError
74
78
74
75
4fca98c6980b11f97842892ca33d4324f6368c00
bigcode/the-stack
train
c8d719bf2bcfde4f38b10c46
train
class
class UnixCommand(Command): """ Unix-type commands, supporting short and long options. This command syntax uses the Unix-style commands with short options (-X) and long options (--something). The `argparse` module is used to parse the command. In order to use it, you should override two metho...
class UnixCommand(Command):
""" Unix-type commands, supporting short and long options. This command syntax uses the Unix-style commands with short options (-X) and long options (--something). The `argparse` module is used to parse the command. In order to use it, you should override two methods: - `init_parser`: thi...
""" if self.command: self.command.msg(self.format_usage().strip()) def print_help(self, file=None): """Print the help to the caller. Args: file (file-object): not used here, the caller is used. Note: This method will override `argparse.Argument...
224
225
751
5
219
davidrideout/evennia
evennia/contrib/base_systems/unixcommand/unixcommand.py
Python
UnixCommand
UnixCommand
202
298
202
202
f439d8edb8615b6a217b511bd6b39deb19474db2
bigcode/the-stack
train
141d2e54073ea583924810f9
train
class
class HelpAction(argparse.Action): """Override the -h/--help action in the default parser. Using the default -h/--help will call the exit function in different ways, preventing the entire help message to be provided. Hence this override. """ def __call__(self, parser, namespace, values, opt...
class HelpAction(argparse.Action):
"""Override the -h/--help action in the default parser. Using the default -h/--help will call the exit function in different ways, preventing the entire help message to be provided. Hence this override. """ def __call__(self, parser, namespace, values, option_string=None): """If aske...
. Note: This method will override `argparse.ArgumentParser`'s in order to not display the help on stdout or stderr, but to the command's caller. """ if self.command: self.command.msg(self.format_help().strip()) class HelpAction(argparse.Action): ...
64
64
111
7
57
davidrideout/evennia
evennia/contrib/base_systems/unixcommand/unixcommand.py
Python
HelpAction
HelpAction
185
199
185
186
6aee4e0948bb8fab986e65aefc0247933e178784
bigcode/the-stack
train
b8ea74effe1ef48178a8be6b
train
class
class UnixCommandParser(argparse.ArgumentParser): """A modifier command parser for unix commands. This parser is used to replace `argparse.ArgumentParser`. It is aware of the command calling it, and can more easily report to the caller. Some features (like the "brutal exit" of the original parse...
class UnixCommandParser(argparse.ArgumentParser):
"""A modifier command parser for unix commands. This parser is used to replace `argparse.ArgumentParser`. It is aware of the command calling it, and can more easily report to the caller. Some features (like the "brutal exit" of the original parser) are disabled or replaced. This parser is used b...
.parser.add_argument("-a", "--age", type=int, default=1, help="the age of the plant to be planted") self.parser.add_argument("--hidden", action="store_true", help="should the newly-planted plant be hidden to players?") def func(self): "func is called only if the pars...
222
222
740
9
212
davidrideout/evennia
evennia/contrib/base_systems/unixcommand/unixcommand.py
Python
UnixCommandParser
UnixCommandParser
81
182
81
82
562dcd7f4b830029bd559be14636513dd2f70899
bigcode/the-stack
train
c9d4ed268a9a229d1e61433f
train
function
def gen_ticket_code(): from random import choice return "".join(choice(ticket_alphabet) for i in range(8))
def gen_ticket_code():
from random import choice return "".join(choice(ticket_alphabet) for i in range(8))
# {{{ mypy from typing import Optional, Text, Tuple, FrozenSet, TYPE_CHECKING # noqa if TYPE_CHECKING: import datetime # noqa # }}} ticket_alphabet = "ABCDEFGHJKLPQRSTUVWXYZabcdefghjkpqrstuvwxyz23456789" def gen_ticket_code():
64
64
27
5
59
khanhduy8/relate
course/exam.py
Python
gen_ticket_code
gen_ticket_code
70
72
70
70
720f618f647006c84d8951b46df004ff88d581a4
bigcode/the-stack
train
683f50d231a5f9f080065e77
train
function
@sensitive_post_parameters() @csrf_protect @never_cache def check_in_for_exam(request): # must import locally for mock to work from course.views import get_now_or_fake_time now_datetime = get_now_or_fake_time(request) if request.method == "POST": form = ExamCheckInForm(request.POST) if ...
@sensitive_post_parameters() @csrf_protect @never_cache def check_in_for_exam(request): # must import locally for mock to work
from course.views import get_now_or_fake_time now_datetime = get_now_or_fake_time(request) if request.method == "POST": form = ExamCheckInForm(request.POST) if form.is_valid(): username = form.cleaned_data["username"] code = form.cleaned_data["code"] pre...
=forms.PasswordInput(), help_text=_("This is not your password, but a code that was " "given to you by a staff member. If you do not have one, " "please follow the link above to log in.")) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) ...
120
121
404
31
89
khanhduy8/relate
course/exam.py
Python
check_in_for_exam
check_in_for_exam
533
597
533
537
914f401edb1ec63888525dda47399d0769373abf
bigcode/the-stack
train
c17d266abaaa5570ef2d8a6a
train
function
def list_available_exams(request): # must import locally for mock to work from course.views import get_now_or_fake_time now_datetime = get_now_or_fake_time(request) if request.user.is_authenticated: participations = ( Participation.objects.filter( user=reques...
def list_available_exams(request): # must import locally for mock to work
from course.views import get_now_or_fake_time now_datetime = get_now_or_fake_time(request) if request.user.is_authenticated: participations = ( Participation.objects.filter( user=request.user, status=participation_status.active)) else: ...
this exam, log out.")) return redirect("relate-view_start_flow", exam_flow_session.course.identifier, exam_flow_session.flow_id) return self.get_response(request) # }}} # {{{ list available exams def list_available_exams(request): # must i...
64
64
194
17
46
khanhduy8/relate
course/exam.py
Python
list_available_exams
list_available_exams
789
817
789
790
0d5be79046d275d00b876973c8081ca951d51701
bigcode/the-stack
train
f4d6f154a2b17ca85d7032f3
train
class
class ExamCheckInForm(StyledForm): username = forms.CharField(required=True, label=_("User name"), # For now, until we upgrade to a custom user model. max_length=30, help_text=_("This is typically your full email address.")) code = forms.CharField(required=True, label=_("Code...
class ExamCheckInForm(StyledForm):
username = forms.CharField(required=True, label=_("User name"), # For now, until we upgrade to a custom user model. max_length=30, help_text=_("This is typically your full email address.")) code = forms.CharField(required=True, label=_("Code"), widget=forms.Passwo...
().objects.get( username=username, is_active=True) return user def get_user(self, user_id): try: return get_user_model().objects.get(pk=user_id) except get_user_model().DoesNotExist: return None class ExamCheckInForm(StyledForm):
64
64
163
9
54
khanhduy8/relate
course/exam.py
Python
ExamCheckInForm
ExamCheckInForm
515
530
515
515
d5ab7b234028da74841d1668c9a11ba8777005f1
bigcode/the-stack
train
0ec9e290bbbcee8114cc2952
train
class
class BatchIssueTicketsForm(StyledForm): # prevents form submission with codemirror's empty textarea use_required_attribute = False def __init__(self, course, editor_mode, *args, **kwargs): super().__init__(*args, **kwargs) from course.utils import get_codemirror_widget cm_widget, ...
class BatchIssueTicketsForm(StyledForm): # prevents form submission with codemirror's empty textarea
use_required_attribute = False def __init__(self, course, editor_mode, *args, **kwargs): super().__init__(*args, **kwargs) from course.utils import get_codemirror_widget cm_widget, cm_help_text = get_codemirror_widget( language_mode={"name": "markdown", "xml": True}, ...
" "browser at this location:"), """ """, _("Exam URL"), """: **`{{ checkin_uri }}`** """, _("You should see boxes prompting for your user " "name and a one-time check-in code."), """ """, _("Enter the following information"), ":", """ """, _("User name"), """: **`{{ ticket.participation.user.username }}`** """, p...
171
171
570
22
149
khanhduy8/relate
course/exam.py
Python
BatchIssueTicketsForm
BatchIssueTicketsForm
268
335
268
269
92487599301da2813ffc842975c760ff5830e333
bigcode/the-stack
train
bdf93b8e05bb49659036d722
train
function
def exam_lockdown_context_processor(request): return { "relate_exam_lockdown": getattr( request, "relate_exam_lockdown", None) }
def exam_lockdown_context_processor(request):
return { "relate_exam_lockdown": getattr( request, "relate_exam_lockdown", None) }
(no_exams_after__gt=now_datetime)) .order_by("no_exams_before", "course__number")) return render(request, "course/list-exams.html", { "exams": exams }) # }}} # {{{ lockdown context processor def exam_lockdown_context_processor(request):
64
64
35
8
55
khanhduy8/relate
course/exam.py
Python
exam_lockdown_context_processor
exam_lockdown_context_processor
824
828
824
824
5cfa5c2b469572241e45c44120e5de7815b1a333
bigcode/the-stack
train
4889643b95de527fe2db2f96
train
class
class ExamTicketBackend: def authenticate(self, request, username=None, code=None, now_datetime=None, facilities=None): is_valid, msg = check_exam_ticket(username, code, now_datetime, facilities) if not is_valid: return None user = get_user_model().objects.get( ...
class ExamTicketBackend:
def authenticate(self, request, username=None, code=None, now_datetime=None, facilities=None): is_valid, msg = check_exam_ticket(username, code, now_datetime, facilities) if not is_valid: return None user = get_user_model().objects.get( username=user...
): return (False, _("Exam ticket is not yet valid.")) if ( ticket.valid_end_time is not None and ticket.valid_end_time < now_datetime): return (False, _("Exam ticket has expired.")) return True, _("Ticket is valid.") class ExamTicketBackend:
63
64
115
5
58
khanhduy8/relate
course/exam.py
Python
ExamTicketBackend
ExamTicketBackend
495
512
495
495
3fe1ae5c9cd99be19f58ca95036daf66f5756d27
bigcode/the-stack
train
dc27d114417bebee94071a9e
train
class
class IssueTicketForm(StyledForm): def __init__(self, now_datetime, *args, **kwargs): initial_exam = kwargs.pop("initial_exam", None) super().__init__(*args, **kwargs) from course.auth import UserSearchWidget self.fields["user"] = forms.ModelChoiceField( queryset=(...
class IssueTicketForm(StyledForm):
def __init__(self, now_datetime, *args, **kwargs): initial_exam = kwargs.pop("initial_exam", None) super().__init__(*args, **kwargs) from course.auth import UserSearchWidget self.fields["user"] = forms.ModelChoiceField( queryset=(get_user_model().objects ...
( exam_ticket_states, participation_status, participation_permission as pperm) from relate.utils import StyledForm, string_concat # {{{ mypy from typing import Optional, Text, Tuple, FrozenSet, TYPE_CHECKING # noqa if TYPE_CHECKING: import datetime # noqa # }}} ticket_alphabet = "A...
125
125
417
8
116
khanhduy8/relate
course/exam.py
Python
IssueTicketForm
IssueTicketForm
77
133
77
77
2f45db9d5459e04e5e1b654aa54d3024bb261985
bigcode/the-stack
train
d515e1f83bc5141e0000de58
train
function
def check_exam_ticket( username: Optional[str], code: Optional[str], now_datetime: datetime.datetime, facilities: Optional[FrozenSet[str]] ) -> Tuple[bool, str]: """ :returns: (is_valid, msg) """ try: user = get_user_model().objects.get( u...
def check_exam_ticket( username: Optional[str], code: Optional[str], now_datetime: datetime.datetime, facilities: Optional[FrozenSet[str]] ) -> Tuple[bool, str]:
""" :returns: (is_valid, msg) """ try: user = get_user_model().objects.get( username=username, is_active=True) ticket = ExamTicket.objects.get( participation__user=user, code=code, ) except ObjectDoesNot...
(request, messages.SUCCESS, _("%d tickets issued.") % len(tickets)) else: form = BatchIssueTicketsForm(pctx.course, request.user.editor_mode) return render_course_page(pctx, "course/batch-exam-tickets-form.html", { "form": form, "form_text": form_text, "...
135
135
450
42
92
khanhduy8/relate
course/exam.py
Python
check_exam_ticket
check_exam_ticket
429
492
429
434
f785338b9194aa3e82e9f4e6ffa31bc34acf272c
bigcode/the-stack
train
782c4009bb0f2d17faab9cc8
train
function
@permission_required("course.can_issue_exam_tickets", raise_exception=True) def issue_exam_ticket(request): # must import locally for mock to work from course.views import get_now_or_fake_time now_datetime = get_now_or_fake_time(request) if request.method == "POST": form = IssueTicketForm(now_d...
@permission_required("course.can_issue_exam_tickets", raise_exception=True) def issue_exam_ticket(request): # must import locally for mock to work
from course.views import get_now_or_fake_time now_datetime = get_now_or_fake_time(request) if request.method == "POST": form = IssueTicketForm(now_datetime, request.POST) if form.is_valid(): exam = form.cleaned_data["exam"] try: participation = Parti...
_facility"] = forms.CharField( label=_("Restrict to facility"), help_text=_("If not blank, the exam ticket may only be used in the " "given facility"), required=False) self.fields["revoke_prior"] = forms.BooleanField( label=_("...
128
129
431
31
97
khanhduy8/relate
course/exam.py
Python
issue_exam_ticket
issue_exam_ticket
136
198
136
138
06a5c3578e89931336e3d355797a47691b27dc63
bigcode/the-stack
train
39c73e0fca79983b41d54362
train
function
def is_from_exams_only_facility(request): from course.utils import get_facilities_config for name, props in get_facilities_config(request).items(): if not props.get("exams_only", False): continue # By now we know that this facility is exams-only if name in request.relate_fac...
def is_from_exams_only_facility(request):
from course.utils import get_facilities_config for name, props in get_facilities_config(request).items(): if not props.get("exams_only", False): continue # By now we know that this facility is exams-only if name in request.relate_facilities: return True retu...
ticket.exam.flow_id) else: form = ExamCheckInForm() return render(request, "course/exam-check-in.html", { "form_description": _("Check in for Exam"), "form": form }) # }}} def is_from_exams_only_facility(request):
64
64
80
10
54
khanhduy8/relate
course/exam.py
Python
is_from_exams_only_facility
is_from_exams_only_facility
602
612
602
602
cf384c4e4fdc683c67cff170a2ccf88fd534007a
bigcode/the-stack
train
f3054c38316e404d82acd8db
train
class
class ExamLockdownMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): request.relate_exam_lockdown = False if "relate_session_locked_to_exam_flow_session_pk" in request.session: exam_flow_session_pk = request.session[ ...
class ExamLockdownMiddleware:
def __init__(self, get_response): self.get_response = get_response def __call__(self, request): request.relate_exam_lockdown = False if "relate_session_locked_to_exam_flow_session_pk" in request.session: exam_flow_session_pk = request.session[ "relate_se...
elif ( (request.user.is_staff or request.user.has_perm("course.can_issue_exam_tickets")) and resolver_match.func == issue_exam_ticket): ok = True if not ok: if (request.user.is_authenticated and resolver_m...
165
165
550
6
159
khanhduy8/relate
course/exam.py
Python
ExamLockdownMiddleware
ExamLockdownMiddleware
699
782
699
699
57f3bd1c985cca23d6751d1d8bf31f5561689f85
bigcode/the-stack
train
54f4239c4c789570dc2e9604
train
class
class ExamFacilityMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): exams_only = is_from_exams_only_facility(request) if not exams_only: return self.get_response(request) if (exams_only and (...
class ExamFacilityMiddleware:
def __init__(self, get_response): self.get_response = get_response def __call__(self, request): exams_only = is_from_exams_only_facility(request) if not exams_only: return self.get_response(request) if (exams_only and ( "relate_s...
_only_facility(request): from course.utils import get_facilities_config for name, props in get_facilities_config(request).items(): if not props.get("exams_only", False): continue # By now we know that this facility is exams-only if name in request.relate_facilities: ...
144
144
482
5
138
khanhduy8/relate
course/exam.py
Python
ExamFacilityMiddleware
ExamFacilityMiddleware
626
696
626
626
b74a9508ed0ea8c483165a537a8ff86772a220ec
bigcode/the-stack
train
da92ae2be951a71645e500c8
train
function
@course_view def batch_issue_exam_tickets(pctx): if not pctx.has_permission(pperm.batch_issue_exam_ticket): raise PermissionDenied(_("may not batch-issue tickets")) form_text = "" request = pctx.request if request.method == "POST": form = BatchIssueTicketsForm(pctx.course, request.user...
@course_view def batch_issue_exam_tickets(pctx):
if not pctx.has_permission(pperm.batch_issue_exam_ticket): raise PermissionDenied(_("may not batch-issue tickets")) form_text = "" request = pctx.request if request.method == "POST": form = BatchIssueTicketsForm(pctx.course, request.user.editor_mode, request.POST) ...
:mm", "sideBySide": True}), required=False) self.fields["restrict_to_facility"] = forms.CharField( label=_("Restrict to facility"), help_text=_("If not blank, the exam ticket may only be used in the " "given facility"), required...
179
180
603
13
166
khanhduy8/relate
course/exam.py
Python
batch_issue_exam_tickets
batch_issue_exam_tickets
338
422
338
339
e55171594a77e5ed1a935ac9f8177380ac5d0216
bigcode/the-stack
train
9295c6be53cc4569f24660e1
train
function
def get_login_exam_ticket(request: http.HttpRequest) -> Optional[ExamTicket]: exam_ticket_pk = request.session.get("relate_exam_ticket_pk_used_for_login") if exam_ticket_pk is None: return None return ExamTicket.objects.get(pk=exam_ticket_pk)
def get_login_exam_ticket(request: http.HttpRequest) -> Optional[ExamTicket]:
exam_ticket_pk = request.session.get("relate_exam_ticket_pk_used_for_login") if exam_ticket_pk is None: return None return ExamTicket.objects.get(pk=exam_ticket_pk)
(): if not props.get("exams_only", False): continue # By now we know that this facility is exams-only if name in request.relate_facilities: return True return False def get_login_exam_ticket(request: http.HttpRequest) -> Optional[ExamTicket]:
64
64
59
17
46
khanhduy8/relate
course/exam.py
Python
get_login_exam_ticket
get_login_exam_ticket
615
621
615
615
51e8fc33e138e28bc7f91e034173d45e2e98e13c
bigcode/the-stack
train
829024f0748b6ae0483be97d
train
class
class LibCClock(Clock): """ Clock implementation that works only on platforms that provide libc. This clock is guaranteed nanosecond precision. """ __libc = "libc.dylib" if uname()[0] == "Darwin" else "libc.so.6" class _TimeSpec(Structure): _fields_ = [ ("seconds", c_longlong),...
class LibCClock(Clock):
""" Clock implementation that works only on platforms that provide libc. This clock is guaranteed nanosecond precision. """ __libc = "libc.dylib" if uname()[0] == "Darwin" else "libc.so.6" class _TimeSpec(Structure): _fields_ = [ ("seconds", c_longlong), ("nanosecon...
except ImportError: return False else: return True def utc_time(self): from time import time_ns t = time_ns() seconds, nanoseconds = divmod(t, 1000000000) return ClockTime(seconds, nanoseconds) class LibCClock(Clock):
66
66
223
7
59
matilda-me/neo4j-python-driver
neo4j/time/clock_implementations.py
Python
LibCClock
LibCClock
79
112
79
79
ddd0bf20ba55b434c8bad79edcbac4979681b2fc
bigcode/the-stack
train
0674152882d4b784559aa656
train
class
class PEP564Clock(Clock): """ Clock implementation based on the PEP564 additions to Python 3.7. This clock is guaranteed nanosecond precision. """ @classmethod def precision(cls): return 9 @classmethod def available(cls): try: from time import time_ns ex...
class PEP564Clock(Clock):
""" Clock implementation based on the PEP564 additions to Python 3.7. This clock is guaranteed nanosecond precision. """ @classmethod def precision(cls): return 9 @classmethod def available(cls): try: from time import time_ns except ImportError: ...
def available(cls): return True def utc_time(self): from time import time seconds, nanoseconds = nano_divmod(int(time() * 1000000), 1000000) return ClockTime(seconds, nanoseconds * 1000) class PEP564Clock(Clock):
64
64
131
8
56
matilda-me/neo4j-python-driver
neo4j/time/clock_implementations.py
Python
PEP564Clock
PEP564Clock
54
76
54
54
3536fd3ab202b0e329dde3000fac08bddbc6c20f
bigcode/the-stack
train
960d8b0747c97ef25d8ab5e5
train
class
class SafeClock(Clock): """ Clock implementation that should work for any variant of Python. This clock is guaranteed microsecond precision. """ @classmethod def precision(cls): return 6 @classmethod def available(cls): return True def utc_time(self): from time...
class SafeClock(Clock):
""" Clock implementation that should work for any variant of Python. This clock is guaranteed microsecond precision. """ @classmethod def precision(cls): return 6 @classmethod def available(cls): return True def utc_time(self): from time import time sec...
. from ctypes import ( byref, c_long, c_longlong, CDLL, Structure, ) from platform import uname from neo4j.time import ( Clock, ClockTime, ) from neo4j.time.arithmetic import nano_divmod class SafeClock(Clock):
64
64
105
6
57
matilda-me/neo4j-python-driver
neo4j/time/clock_implementations.py
Python
SafeClock
SafeClock
35
51
35
35
8d6d361bb57b42085a45f1b4d9d02dc9a8e3fe86
bigcode/the-stack
train
00d07d4d81f5add52620f643
train
class
class LyricSpider(scrapy.Spider): name = 'lyric-spider' allowed_domains = ['lyrics.com'] start_urls = ['https://www.lyrics.com/artist/Tame+Impala/1111074', 'https://www.lyrics.com/artist/Frank+Ocean/2295304', 'https://www.lyrics.com/artist/Kendrick+Lamar/2412704', 'https://www.lyrics.com/artist/...
class LyricSpider(scrapy.Spider):
name = 'lyric-spider' allowed_domains = ['lyrics.com'] start_urls = ['https://www.lyrics.com/artist/Tame+Impala/1111074', 'https://www.lyrics.com/artist/Frank+Ocean/2295304', 'https://www.lyrics.com/artist/Kendrick+Lamar/2412704', 'https://www.lyrics.com/artist/Arctic+Monkeys/744567'] custo...
import scrapy from scrapy.http import Request # an object that we need to convert any URL string into something # we can go into class LyricSpider(scrapy.Spider):
38
105
350
9
28
maximcondon/Project_LyricsClassifier
lyric_scraper_peppermint.py
Python
LyricSpider
LyricSpider
6
38
6
6
dbfd076a32a1bbf952705ca9116aaee5a2357fd6
bigcode/the-stack
train
38d4717455e8f830ea089ddf
train
function
def main(): args = parser.parse_args() print_arguments(args) check_cuda(args.use_gpu) eval(args)
def main():
args = parser.parse_args() print_arguments(args) check_cuda(args.use_gpu) eval(args)
f = np.vstack(f) l = np.hstack(l) recall = recall_topk(f, l, k=1) print("[%s] End test %d, test_recall %.5f" % (fmt_time(), len(f), recall)) sys.stdout.flush() def main():
64
64
26
3
61
chengduoZH/models
PaddleCV/metric_learning/eval.py
Python
main
main
93
97
93
93
294ffc678906f668676712620833a5ecda0a47f2
bigcode/the-stack
train
a7595deacab6b7881dc76754
train
function
def eval(args): # parameters from arguments model_name = args.model pretrained_model = args.pretrained_model with_memory_optimization = args.with_mem_opt image_shape = [int(m) for m in args.image_shape.split(",")] assert model_name in model_list, "{} is not in lists: {}".format(args.model, ...
def eval(args): # parameters from arguments
model_name = args.model pretrained_model = args.pretrained_model with_memory_optimization = args.with_mem_opt image_shape = [int(m) for m in args.image_shape.split(",")] assert model_name in model_list, "{} is not in lists: {}".format(args.model, ...
Set the network to use.") add_arg('embedding_size', int, 0, "Embedding size.") add_arg('batch_size', int, 10, "Minibatch size.") add_arg('image_shape', str, "3,224,224", "Input image size.") add_arg('use_gpu', bool, True, "Whether to use GPU or not.") add_arg('with_mem_opt', bool, False, "Whether to use memory optimiza...
148
148
495
10
138
chengduoZH/models
PaddleCV/metric_learning/eval.py
Python
eval
eval
34
90
34
35
83e195b4df7afc9aaf4db1473d6cf7cc0a9f6776
bigcode/the-stack
train
5dc17067e82a05010af6aa53
train
class
class MetricEntity(utils.metaclass_insert(abc.ABCMeta, PluginReadyEntity)): """ This is the handler for RAVEN general interface metrics """ interfaceFactory = MetricFactory ####################### # # Construction # def __init__(self): """ This is the basic method initialize the metric ob...
class MetricEntity(utils.metaclass_insert(abc.ABCMeta, PluginReadyEntity)):
""" This is the handler for RAVEN general interface metrics """ interfaceFactory = MetricFactory ####################### # # Construction # def __init__(self): """ This is the basic method initialize the metric object @ In, none @ Out, none """ super().__init__() s...
# Copyright 2017 Battelle Energy Alliance, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed t...
206
256
964
17
188
dgarrett622/raven
ravenframework/Metrics/MetricEntity.py
Python
MetricEntity
MetricEntity
27
145
27
27
d9dc50b676d3ba2bab3fdbf46c2cd4db7a046656
bigcode/the-stack
train
d56c9c5720a25471031cdbfe
train
function
def parse_speed_unit(max_speed): """Converts a maxspeed string to m/s based on the unit present in the input. OpenStreetMap defaults to kph if no unit is present. """ if not max_speed: return None conversion = CV.KPH_TO_MS if 'mph' in max_speed: max_speed = max_speed.replace(' mph', '') conversi...
def parse_speed_unit(max_speed):
"""Converts a maxspeed string to m/s based on the unit present in the input. OpenStreetMap defaults to kph if no unit is present. """ if not max_speed: return None conversion = CV.KPH_TO_MS if 'mph' in max_speed: max_speed = max_speed.replace(' mph', '') conversion = CV.MPH_TO_MS try: retu...
(x2 * y1 - x1 * y2) return (-B / (2 * A), - C / (2 * A), np.sqrt((B**2 + C**2 - 4 * A * D) / (4 * A**2))) def parse_speed_unit(max_speed):
64
64
111
7
57
1Thamer/openpilot1
selfdrive/mapd/mapd_helpers.py
Python
parse_speed_unit
parse_speed_unit
36
50
36
36
53d034a163cbba3f5e7d9326d931e312b0840467
bigcode/the-stack
train
1d82ded4da311c4070459799
train
function
def geocode_maxspeed(tags, location_info): max_speed = None try: geocode_country = location_info.get('country', '') geocode_region = location_info.get('region', '') country_rules = DEFAULT_SPEEDS_BY_REGION.get(geocode_country, {}) country_defaults = country_rules.get('Default', []) for rule in ...
def geocode_maxspeed(tags, location_info):
max_speed = None try: geocode_country = location_info.get('country', '') geocode_region = location_info.get('region', '') country_rules = DEFAULT_SPEEDS_BY_REGION.get(geocode_country, {}) country_defaults = country_rules.get('Default', []) for rule in country_defaults: rule_valid = all( ...
_speed = DEFAULT_SPEEDS.get(tags['source:maxspeed'], None) if not max_speed and 'maxspeed:type' in tags: max_speed = DEFAULT_SPEEDS.get(tags['maxspeed:type'], None) max_speed = parse_speed_unit(max_speed) return max_speed def geocode_maxspeed(tags, location_info):
69
69
233
10
58
1Thamer/openpilot1
selfdrive/mapd/mapd_helpers.py
Python
geocode_maxspeed
geocode_maxspeed
82
113
82
82
33df2649b984276babf570c73a97bc311f9c5c39
bigcode/the-stack
train
ef3236a7479c744842b3d732
train
class
class Way: def __init__(self, way, query_results): self.id = way.id self.way = way self.query_results = query_results points = list() for node in self.way.get_nodes(resolve_missing=False): points.append((float(node.lat), float(node.lon), 0.)) self.points = np.asarray(points) @class...
class Way:
def __init__(self, way, query_results): self.id = way.id self.way = way self.query_results = query_results points = list() for node in self.way.get_nodes(resolve_missing=False): points.append((float(node.lat), float(node.lon), 0.)) self.points = np.asarray(points) @classmethod de...
speed:type'], None) max_speed = parse_speed_unit(max_speed) return max_speed def geocode_maxspeed(tags, location_info): max_speed = None try: geocode_country = location_info.get('country', '') geocode_region = location_info.get('region', '') country_rules = DEFAULT_SPEEDS_BY_REGION.get(geocode_co...
256
256
2,732
3
252
1Thamer/openpilot1
selfdrive/mapd/mapd_helpers.py
Python
Way
Way
115
435
115
115
f5fafb4a84dbf7dd8b5f0e3331506b2f90ba935e
bigcode/the-stack
train
e700f38ff37f2c0301c5a967
train
function
def parse_speed_tags(tags): """Parses tags on a way to find the maxspeed string""" max_speed = None if 'maxspeed' in tags: max_speed = tags['maxspeed'] if 'maxspeed:conditional' in tags: try: max_speed_cond, cond = tags['maxspeed:conditional'].split(' @ ') cond = cond[1:-1] start, e...
def parse_speed_tags(tags):
"""Parses tags on a way to find the maxspeed string""" max_speed = None if 'maxspeed' in tags: max_speed = tags['maxspeed'] if 'maxspeed:conditional' in tags: try: max_speed_cond, cond = tags['maxspeed:conditional'].split(' @ ') cond = cond[1:-1] start, end = cond.split('-') n...
if no unit is present. """ if not max_speed: return None conversion = CV.KPH_TO_MS if 'mph' in max_speed: max_speed = max_speed.replace(' mph', '') conversion = CV.MPH_TO_MS try: return float(max_speed) * conversion except ValueError: return None def parse_speed_tags(tags):
82
82
276
6
75
1Thamer/openpilot1
selfdrive/mapd/mapd_helpers.py
Python
parse_speed_tags
parse_speed_tags
52
80
52
52
7f367e6179c76571a19491ea8aec689c6abb9ea3
bigcode/the-stack
train
eda102df04647435754e810c
train
function
def circle_through_points(p1, p2, p3): """Fits a circle through three points Formulas from: http://www.ambrsoft.com/trigocalc/circle3d.htm""" x1, y1, _ = p1 x2, y2, _ = p2 x3, y3, _ = p3 A = x1 * (y2 - y3) - y1 * (x2 - x3) + x2 * y3 - x3 * y2 B = (x1**2 + y1**2) * (y3 - y2) + (x2**2 + y2**2) * (y1 - y3) ...
def circle_through_points(p1, p2, p3):
"""Fits a circle through three points Formulas from: http://www.ambrsoft.com/trigocalc/circle3d.htm""" x1, y1, _ = p1 x2, y2, _ = p2 x3, y3, _ = p3 A = x1 * (y2 - y3) - y1 * (x2 - x3) + x2 * y3 - x3 * y2 B = (x1**2 + y1**2) * (y3 - y2) + (x2**2 + y2**2) * (y1 - y3) + (x3**2 + y3**2) * (y2 - y1) C = (x1...
d/default_speeds.json" DEFAULT_SPEEDS = {} with open(DEFAULT_SPEEDS_JSON_FILE, "rb") as f: DEFAULT_SPEEDS = json.loads(f.read()) DEFAULT_SPEEDS_BY_REGION_JSON_FILE = BASEDIR + "/selfdrive/mapd/default_speeds_by_region.json" DEFAULT_SPEEDS_BY_REGION = {} with open(DEFAULT_SPEEDS_BY_REGION_JSON_FILE, "rb") as f: DEF...
109
109
366
14
95
1Thamer/openpilot1
selfdrive/mapd/mapd_helpers.py
Python
circle_through_points
circle_through_points
22
34
22
22
de1daf591a426f7e79c0e7975994e58bc4a710cf
bigcode/the-stack
train
141423ea39142cb68c65510d
train
class
@Seq2SeqEncoder.register("concat_rnn") class ConcatRNN(Seq2SeqEncoder): def __init__(self, input_size, hidden_size, num_layers, bidirectional, rnn_type="GRU", dropout=0., stateful=False, batch_first=True): super().__init__(stateful=stateful) rnn_cls = Seq2SeqEncoder.by_name(rnn_type.lower()) ...
@Seq2SeqEncoder.register("concat_rnn") class ConcatRNN(Seq2SeqEncoder):
def __init__(self, input_size, hidden_size, num_layers, bidirectional, rnn_type="GRU", dropout=0., stateful=False, batch_first=True): super().__init__(stateful=stateful) rnn_cls = Seq2SeqEncoder.by_name(rnn_type.lower()) self.rnn_list = torch.nn.ModuleList( [rnn_cls(input_size=in...
import torch from allennlp.modules import Seq2SeqEncoder from modules.dropout import RNNDropout @Seq2SeqEncoder.register("concat_rnn") class ConcatRNN(Seq2SeqEncoder):
45
74
249
22
22
matthew-z/pytorch_rnet
modules/rnn/stacked_rnn.py
Python
ConcatRNN
ConcatRNN
7
30
7
8
f3319f7b7939271b4de5b6b326db18d25a680caa
bigcode/the-stack
train
ff02c1931e58b9aca3403112
train
function
def toposort(edges): """Topological sort algorithm by Kahn [1]_. Complexity is O(nodes + vertices). Parameters ---------- edges : dict Dict of the form {a: {b, c}} where b and c depend on a Returns ------- An ordered list of nodes that satisfy the dependencies of ``edges`` ...
def toposort(edges):
"""Topological sort algorithm by Kahn [1]_. Complexity is O(nodes + vertices). Parameters ---------- edges : dict Dict of the form {a: {b, c}} where b and c depend on a Returns ------- An ordered list of nodes that satisfy the dependencies of ``edges`` Example -------...
[v] self.forward[merged_vertex] = forward_edges backward_edges = set() for v in vertices: backward_edges.update(self.backward[v]) del self.backward[v] self.backward[merged_vertex] = backward_edges for e in forward_edges: self.backward[e].diff...
108
108
362
6
102
pedrombmachado/nengo
nengo/utils/graphs.py
Python
toposort
toposort
103
151
103
103
8d3b06700d13d06e1b494f26c17d7b5b147399a7
bigcode/the-stack
train
9202fb20e9240c1523f1b054
train
function
def graph(edges=None): g = defaultdict(set) if edges is not None: g.update(edges) return g
def graph(edges=None):
g = defaultdict(set) if edges is not None: g.update(edges) return g
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ from collections import defaultdict from ..exceptions import BuildError def graph(edges=None):
64
64
27
5
58
pedrombmachado/nengo
nengo/utils/graphs.py
Python
graph
graph
43
47
43
43
316e900d08b24e99873e969049ebff932995a88e
bigcode/the-stack
train
03d4b5eda11fe29800a6e26f
train
function
def transitive_closure(edges, topo_sorted=None): """Constructs the transitive closure of a directed acyclic graph (DAG). The complexity is O(nodes + vertices). Parameters ---------- edges : dict Dict of the form ``{a: {b, c}}`` where ``b`` and ``c`` depend on ``a``. Must not contai...
def transitive_closure(edges, topo_sorted=None):
"""Constructs the transitive closure of a directed acyclic graph (DAG). The complexity is O(nodes + vertices). Parameters ---------- edges : dict Dict of the form ``{a: {b, c}}`` where ``b`` and ``c`` depend on ``a``. Must not contain cycles. topo_sorted : sequence, optional ...
] incoming_edges[m].remove(n) if not incoming_edges[m]: vertices.add(m) if any(incoming_edges.get(v, None) for v in edges): raise BuildError( "Input graph has cycles. This usually occurs because " "too many connections have no synapses. Try set...
99
99
333
11
87
pedrombmachado/nengo
nengo/utils/graphs.py
Python
transitive_closure
transitive_closure
154
190
154
154
b50e7444d4b9928c8728c39dce2e6d429ad24678
bigcode/the-stack
train
f148c7e0197c1c3e99b9e214
train
function
def reverse_edges(edges): """Reverses direction of dependence dict. Parameters ---------- edges : dict Dict of the form {a: {b, c}, b: set(), c: set()} where b and c depend on a. Returns ------- Dict of the form {a: set(), b: {a}, c: {a}} where b and c depend on a. Exa...
def reverse_edges(edges):
"""Reverses direction of dependence dict. Parameters ---------- edges : dict Dict of the form {a: {b, c}, b: set(), c: set()} where b and c depend on a. Returns ------- Dict of the form {a: set(), b: {a}, c: {a}} where b and c depend on a. Example ------- >>> ...
to reuse existing sets as this can significantly reduce # memory in some cases (which is important in the OpMergeOptimizer). if reachables[vertex] in sets: reachables[vertex] = sets[reachables[vertex]] sets[reachables[vertex]] = reachables[vertex] return reachables def reverse_e...
74
74
249
5
68
pedrombmachado/nengo
nengo/utils/graphs.py
Python
reverse_edges
reverse_edges
193
223
193
193
1302443893a9afc4056de28f59e26a2b27a640a6
bigcode/the-stack
train
ca26a1ef11041e539c461225
train
class
class BidirectionalDAG: """Directed acyclic graph supporting bidirectional traversal. Parameters ---------- forward : dict Forward edges for each vertex in the form {1: {2, 3}, 2: {3}, 3: set()}. Attributes ---------- forward : dict Maps vertices to edges in forward...
class BidirectionalDAG:
"""Directed acyclic graph supporting bidirectional traversal. Parameters ---------- forward : dict Forward edges for each vertex in the form {1: {2, 3}, 2: {3}, 3: set()}. Attributes ---------- forward : dict Maps vertices to edges in forward direction. backward...
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ from collections import defaultdict from ..exceptions import BuildError def graph(edges=None): g = defaultdict...
88
88
296
6
81
pedrombmachado/nengo
nengo/utils/graphs.py
Python
BidirectionalDAG
BidirectionalDAG
50
100
50
50
2b0042211cef20cad509a81b3d209e1dad99a81b
bigcode/the-stack
train
b7187fcec8e6b8896737f76e
train
function
def add_edges(edges, new_edge_iter): for src, dst in new_edge_iter: edges[src].add(dst)
def add_edges(edges, new_edge_iter):
for src, dst in new_edge_iter: edges[src].add(dst)
. So this function output order should be considered as undeterministic. """ result = {k: set() for k in edges} for key in edges: for val in edges[key]: result[val].add(key) return result def add_edges(edges, new_edge_iter):
64
64
26
9
54
pedrombmachado/nengo
nengo/utils/graphs.py
Python
add_edges
add_edges
226
228
226
226
646a0172242a92989de7930d7a551525ece38250
bigcode/the-stack
train
289601de5825b6706cb5bf90
train
function
def _f(w, z, s2): return -0.5 * (np.square(np.log(w)) / s2 + z * w)
def _f(w, z, s2):
return -0.5 * (np.square(np.log(w)) / s2 + z * w)
model log-powers # needs to be corrected: return var_logP * LN10SQ # S^2_j = def _integrand(w, z, s2): return np.exp(_f(w, z, s2)) def _f(w, z, s2):
64
64
32
10
54
astromancer/tsa
src/tsa/rednoise.py
Python
_f
_f
97
98
97
97
94c5629fbca14ce8ea9160a6e26506d951b10ffb
bigcode/the-stack
train
d29c698c99740a65bc2d5be6
train
function
def powerlaw_variance(frq): """ Uncertainties on the slope and normalisation estimates from LS fit """ a = np.ma.log10(np.atleast_1d(frq)) n = len(a) # - 1 # n is the number of frequencies used in the fitting. # Normally n = n − 1 since only the Nyquist frequency is ignored # (because ...
def powerlaw_variance(frq):
""" Uncertainties on the slope and normalisation estimates from LS fit """ a = np.ma.log10(np.atleast_1d(frq)) n = len(a) # - 1 # n is the number of frequencies used in the fitting. # Normally n = n − 1 since only the Nyquist frequency is ignored # (because the periodogram at the Nyqui...
.pi / LN10) ** 2 / 6 # variance of the log-periodogram about true spectrum (Geweke & Porter-Hudak # 1983) (\sigma^2 in Vaughan 2005) def powerlaw(N, alpha, x): return N * np.power(x, -alpha) def powerlaw_variance(frq):
74
74
247
8
66
astromancer/tsa
src/tsa/rednoise.py
Python
powerlaw_variance
powerlaw_variance
45
72
45
45
0c2fa4133a0c8559254c221a8f2478e41c8745e0
bigcode/the-stack
train
2888359cda03d6eb8566937f
train
function
def cdf_gamma(z, s2j): A, Ae = dblquad(_integrand, 0, z, lambda _: zero, lambda _: np.inf, (s2j,)) return A
def cdf_gamma(z, s2j):
A, Ae = dblquad(_integrand, 0, z, lambda _: zero, lambda _: np.inf, (s2j,)) return A
the power in the # fitted model at frequency f j is therefore: A, Ae = quad(_integrand, zero, np.inf, (z, s2j)) return A / (SQRT8PI * np.sqrt(s2j)) def cdf_gamma(z, s2j):
64
64
44
10
54
astromancer/tsa
src/tsa/rednoise.py
Python
cdf_gamma
cdf_gamma
114
116
114
114
c2db32c91c927c1a5d2c45607fc22eee2f5e0733
bigcode/the-stack
train
ac7a3204c356b84ec89eaeb8
train
class
class PowerLawSpec(Spectral): def __init__(self, *args, **kws): Spectral.__init__(self, *args, **kws) # suppress warnings for zeros with warnings.catch_warnings(): warnings.simplefilter('ignore', RuntimeWarning) # log-log for fitting powerlaw self.logfrq...
class PowerLawSpec(Spectral):
def __init__(self, *args, **kws): Spectral.__init__(self, *args, **kws) # suppress warnings for zeros with warnings.catch_warnings(): warnings.simplefilter('ignore', RuntimeWarning) # log-log for fitting powerlaw self.logfrq = np.log10(self.frq) ...
(gamma, sj)) return val - c def solver2(sj, c): return brentq(eq2, 0, 1e3, (sj, c)) # import inspect # from pathlib import Path # from decor.misc import memoize # # get coordinate cache file # here = inspect.getfile(inspect.currentframe()) # moduleDir = Path(here).parent # cacheName = '.cache.confidence_so...
256
256
1,000
7
249
astromancer/tsa
src/tsa/rednoise.py
Python
PowerLawSpec
PowerLawSpec
296
405
296
296
af7a7362e5660ef26ce127617997626e8242fc91
bigcode/the-stack
train
9e1e799a877cd95b39dbdc89
train
function
def _confidence_solver(sj2, c): # The calculation of γ depends only on p_γ_j (z), from Eq. (21), which in # turn depends only on Sj, from Eq. (13), and this is calculated using # the the abscissae (frequencies f_j) with no dependence on the ordinates # (periodogram powers I_j ). The critical value γ can...
def _confidence_solver(sj2, c): # The calculation of γ depends only on p_γ_j (z), from Eq. (21), which in # turn depends only on Sj, from Eq. (13), and this is calculated using # the the abscissae (frequencies f_j) with no dependence on the ordinates # (periodogram powers I_j ). The critical value γ can...
def _solve(z): return cdf_gamma(z, sj2) - c return brentq(_solve, 0, 1e3)
def _confidence_solver(sj2, c): # The calculation of γ depends only on p_γ_j (z), from Eq. (21), which in # turn depends only on Sj, from Eq. (13), and this is calculated using # the the abscissae (frequencies f_j) with no dependence on the ordinates # (periodogram powers I_j ). The critical value γ can...
106
64
141
106
0
astromancer/tsa
src/tsa/rednoise.py
Python
_confidence_solver
_confidence_solver
171
181
171
177
45d10bb1a3b19d4cd3996c196c7b86a377c223dd
bigcode/the-stack
train
b0af93b44fe617b7abf6994d
train
function
def global_confidence2(frq, percent=99.9, local=False): # this one should be much faster since it involves only a single # numerical integration due to some clever calculus (my own work - not in # Vaughan (2005)) assert (0 < percent < 100), 'Significance should be a percentage value ' \ ...
def global_confidence2(frq, percent=99.9, local=False): # this one should be much faster since it involves only a single # numerical integration due to some clever calculus (my own work - not in # Vaughan (2005))
assert (0 < percent < 100), 'Significance should be a percentage value ' \ 'between 0 and 100 (exclusive).' c = percent / 100. # 1 - epsilon if not local: c = pow(c, 1 / len(frq)) func = ftl.partial(solver2, c=SQRT1PI * (1 - c)) s = periodogram_variance(frq)...
() return np.array(gamma_e) def global_confidence2(frq, percent=99.9, local=False): # this one should be much faster since it involves only a single # numerical integration due to some clever calculus (my own work - not in # Vaughan (2005))
65
65
218
56
9
astromancer/tsa
src/tsa/rednoise.py
Python
global_confidence2
global_confidence2
223
244
223
227
1f27ccd26a789be976918f99f02ad7b538afbd15
bigcode/the-stack
train
65cd85793515270016442e2d
train
function
def integrand2(x, gamma, sj): return np.exp((-x * x - 0.5 * gamma * np.exp(SQRT2 * sj * x)))
def integrand2(x, gamma, sj):
return np.exp((-x * x - 0.5 * gamma * np.exp(SQRT2 * sj * x)))
some minutes for with mp.Pool() as pool: result = pool.map(func, s.compressed()) pool.join() gamma_e = np.zeros_like(s) gamma_e[~gamma_e.mask] = result return gamma_e def integrand2(x, gamma, sj):
64
64
37
10
53
astromancer/tsa
src/tsa/rednoise.py
Python
integrand2
integrand2
247
248
247
247
2575eb99c8bb03865f9b2632dc9e915d154aa810
bigcode/the-stack
train
20cd1460996aaadadcd4f55d
train
function
def powerlaw(N, alpha, x): return N * np.power(x, -alpha)
def powerlaw(N, alpha, x):
return N * np.power(x, -alpha)
.pi) VAR_LN_P = (np.pi / LN10) ** 2 / 6 # variance of the log-periodogram about true spectrum (Geweke & Porter-Hudak # 1983) (\sigma^2 in Vaughan 2005) def powerlaw(N, alpha, x):
64
64
20
9
55
astromancer/tsa
src/tsa/rednoise.py
Python
powerlaw
powerlaw
41
42
41
41
fa5404d7c76eeae06deaced239d6205a57cb9b23
bigcode/the-stack
train
a8efc5fe4f99c113dfea7697
train
function
def _init_shared_memory(Z, Sj2, grid): global _shared shape = (len(Z),) if grid: shape += (len(Sj2),) id_, tmp = tempfile.mkstemp() _shared = np.lib.format.open_memmap(tmp, 'w+', np.float, shape)
def _init_shared_memory(Z, Sj2, grid):
global _shared shape = (len(Z),) if grid: shape += (len(Sj2),) id_, tmp = tempfile.mkstemp() _shared = np.lib.format.open_memmap(tmp, 'w+', np.float, shape)
(z, sj2)) for inner product _init_shared_memory(Z, Sj2, grid) with mp.Pool() as pool: pool.map(worker, args) pool.join() return np.array(_shared) import tempfile def _init_shared_memory(Z, Sj2, grid):
64
64
69
12
51
astromancer/tsa
src/tsa/rednoise.py
Python
_init_shared_memory
_init_shared_memory
159
167
159
159
ff9d5fe078056a7bd10741bb30d47a95252dd86e
bigcode/the-stack
train
493062ce3fc334db7e0271e9
train
class
class Linear(Model): """A straight line""" def __call__(self, p, x): 'P_j = N f_j^-\alpha ln(f_j)' return p[0] * x + p[1]
class Linear(Model):
"""A straight line""" def __call__(self, p, x): 'P_j = N f_j^-\alpha ln(f_j)' return p[0] * x + p[1]
1 - epsilon if local: c = frac else: n = len(frq) c = pow(frac, 1 / n) from scipy.optimize import leastsq from .spectral import Spectral from obstools.modelling.core import Model class Linear(Model):
64
64
49
4
59
astromancer/tsa
src/tsa/rednoise.py
Python
Linear
Linear
288
293
288
288
d28078e29d6f12f2a52b5678ade50a2dc0210962
bigcode/the-stack
train
9fd7d6ffeb68b3f45061003c
train
function
def periodogram_variance(frq): """ The expected uncertainties and covariance of the two model parameters can be combined to give an estimate of the uncertainty of the logarithm of the model, log[P̂ j ], at a frequency f j , using the standard error propagation formula. """ a = np.ma.log10(f...
def periodogram_variance(frq):
""" The expected uncertainties and covariance of the two model parameters can be combined to give an estimate of the uncertainty of the logarithm of the model, log[P̂ j ], at a frequency f j , using the standard error propagation formula. """ a = np.ma.log10(frq) var_logN, var_alpha, co...
VAR_LN_P / delta # var normalization factor var_logN = VAR_LN_P * a2s / delta # covariance cov = VAR_LN_P * asum / delta return var_logN, var_alpha, cov def periodogram_variance(frq):
64
64
191
8
55
astromancer/tsa
src/tsa/rednoise.py
Python
periodogram_variance
periodogram_variance
75
90
75
75
adf9b38445b20bef7d739eeae2a08cc1594bea15
bigcode/the-stack
train
78aeea401f31b14c0dcec80c
train
function
def global_confidence(frq, percent=99.9, local=False): # The probability of obtaining a value of γ̂ j higher than γ_e can be # computed by integrating this PDF: This can be evaluated numerically to # find γ_e for a given e1 . Equivalently, we can find the value of γ_j at # the corresponding 1 − e signif...
def global_confidence(frq, percent=99.9, local=False): # The probability of obtaining a value of γ̂ j higher than γ_e can be # computed by integrating this PDF: This can be evaluated numerically to # find γ_e for a given e1 . Equivalently, we can find the value of γ_j at # the corresponding 1 − e signif...
assert (0 < percent < 100) frac = percent / 100. # 1 - epsilon if local: c = frac else: c = pow(frac, 1 / len(frq)) func = ftl.partial(_confidence_solver, c=c) with mp.Pool() as pool: gamma_e = pool.map(func, periodogram_variance(frq)) pool.join() return np.ar...
def global_confidence(frq, percent=99.9, local=False): # The probability of obtaining a value of γ̂ j higher than γ_e can be # computed by integrating this PDF: This can be evaluated numerically to # find γ_e for a given e1 . Equivalently, we can find the value of γ_j at # the corresponding 1 − e signif...
340
132
440
340
0
astromancer/tsa
src/tsa/rednoise.py
Python
global_confidence
global_confidence
184
220
184
206
d11be1f5c6fe03891b862e3ee997f8e52ae4c9cb
bigcode/the-stack
train
04897da85432aa951d691675
train
function
def solver2(sj, c): return brentq(eq2, 0, 1e3, (sj, c))
def solver2(sj, c):
return brentq(eq2, 0, 1e3, (sj, c))
.exp(SQRT2 * sj * x))) def eq2(gamma, sj, c): inf = 1e2 val, err = quad(integrand2, -inf, inf, (gamma, sj)) return val - c def solver2(sj, c):
64
64
29
8
55
astromancer/tsa
src/tsa/rednoise.py
Python
solver2
solver2
257
258
257
257
15b629b32c135976bf0ae9d363b7691dc659598e
bigcode/the-stack
train
9e76d678d4d5dd9e59a37169
train
function
def eq2(gamma, sj, c): inf = 1e2 val, err = quad(integrand2, -inf, inf, (gamma, sj)) return val - c
def eq2(gamma, sj, c):
inf = 1e2 val, err = quad(integrand2, -inf, inf, (gamma, sj)) return val - c
gamma_e[~gamma_e.mask] = result return gamma_e def integrand2(x, gamma, sj): return np.exp((-x * x - 0.5 * gamma * np.exp(SQRT2 * sj * x))) def eq2(gamma, sj, c):
63
64
45
10
53
astromancer/tsa
src/tsa/rednoise.py
Python
eq2
eq2
251
254
251
251
d2f538d8d737d37626c4714fdf9a344983fd3ab7
bigcode/the-stack
train
0858fa9ef210d4df1c59be5e
train
function
def _bulk_compute(frq, Z, grid=True, **kws): """Calculate probability surface for pdf / cdf""" pdf = kws.get('pdf', not kws.get('cdf', False)) func = pdf_gamma if pdf else cdf_gamma worker = ftl.partial(_gamma_worker, func) frq = np.atleast_1d(frq) Z = np.atleast_1d(Z) # make sure we have...
def _bulk_compute(frq, Z, grid=True, **kws):
"""Calculate probability surface for pdf / cdf""" pdf = kws.get('pdf', not kws.get('cdf', False)) func = pdf_gamma if pdf else cdf_gamma worker = ftl.partial(_gamma_worker, func) frq = np.atleast_1d(frq) Z = np.atleast_1d(Z) # make sure we have 1D arrays if (np.ndim(frq) > 1) or (np.n...
): A, Ae = dblquad(_integrand, 0, z, lambda _: zero, lambda _: np.inf, (s2j,)) return A def _gamma_worker(f, args): i, (z, sj2) = args _shared[i] = f(z, sj2) def _bulk_compute(frq, Z, grid=True, **kws):
83
83
279
16
67
astromancer/tsa
src/tsa/rednoise.py
Python
_bulk_compute
_bulk_compute
124
153
124
124
acd5654e0fc610446a86822896675106d12738f4
bigcode/the-stack
train
b65a0fd79b07cd6fe26b0c1f
train
function
def _gamma_worker(f, args): i, (z, sj2) = args _shared[i] = f(z, sj2)
def _gamma_worker(f, args):
i, (z, sj2) = args _shared[i] = f(z, sj2)
(SQRT8PI * np.sqrt(s2j)) def cdf_gamma(z, s2j): A, Ae = dblquad(_integrand, 0, z, lambda _: zero, lambda _: np.inf, (s2j,)) return A def _gamma_worker(f, args):
64
64
32
8
55
astromancer/tsa
src/tsa/rednoise.py
Python
_gamma_worker
_gamma_worker
119
121
119
119
a42f3764be1f832d09986364fd4104cc526384cd
bigcode/the-stack
train
ca9bd1878fb4a4715125e657
train
function
def _integrand(w, z, s2): return np.exp(_f(w, z, s2))
def _integrand(w, z, s2):
return np.exp(_f(w, z, s2))
whereas previously the results were given in # terms of base 10 logarithm. The uncertainty on the model log-powers # needs to be corrected: return var_logP * LN10SQ # S^2_j = def _integrand(w, z, s2):
63
64
24
11
52
astromancer/tsa
src/tsa/rednoise.py
Python
_integrand
_integrand
93
94
93
93
a978c5e171e05ec27b61c0d889bd2ca4fa8075ea
bigcode/the-stack
train
19ac06f8484357a4e70d5247
train
function
def fancy_3D(Frq, Z, P, log=False, gamma_e=None): def shade3D(ax, k, ge=None, color='g', alpha=0.4): """3D shaded area""" if ge is None: ge = Z[:, k].max() seg = Z[:, k] <= ge fk, zk, pgk = Frq[seg, k], Z[seg, k], P[seg, k] fk = np.r_[fk, fk[-1]] zk = np...
def fancy_3D(Frq, Z, P, log=False, gamma_e=None):
def shade3D(ax, k, ge=None, color='g', alpha=0.4): """3D shaded area""" if ge is None: ge = Z[:, k].max() seg = Z[:, k] <= ge fk, zk, pgk = Frq[seg, k], Z[seg, k], P[seg, k] fk = np.r_[fk, fk[-1]] zk = np.r_[zk, ge] pgk = np.r_[pgk, pgk[-1]] ...
-limits for spectrum # kws.get('clabels', ) for i, (gg, lbl) in enumerate(itt.zip_longest(g, clabels)): ax.plot(x[::10], op(m[::10], gg), 'k--', dashes=(2 * (i + 1),) * 2, label=lbl) # ax.plot(x, m + np.log10(g / 2), 'k:' ) # caption ...
256
256
1,185
20
235
astromancer/tsa
src/tsa/rednoise.py
Python
fancy_3D
fancy_3D
427
535
427
427
db3055fe856d1151e1b34a775f243f90ac81b5cb
bigcode/the-stack
train
2188cd4be53be0413afcbc04
train
function
def pdf_gamma(z, s2j): # The ratio γ̂ j = 2I j /P̂ j is really the ratio of two random variables; # the PDF of this would allow us to calculate the probability of observing # a given value of γ̂ j taking full account of the uncertainty in the # model fitting. of the uncertainty in the model fitting. ...
def pdf_gamma(z, s2j): # The ratio γ̂ j = 2I j /P̂ j is really the ratio of two random variables; # the PDF of this would allow us to calculate the probability of observing # a given value of γ̂ j taking full account of the uncertainty in the # model fitting. of the uncertainty in the model fitting. ...
A, Ae = quad(_integrand, zero, np.inf, (z, s2j)) return A / (SQRT8PI * np.sqrt(s2j))
def pdf_gamma(z, s2j): # The ratio γ̂ j = 2I j /P̂ j is really the ratio of two random variables; # the PDF of this would allow us to calculate the probability of observing # a given value of γ̂ j taking full account of the uncertainty in the # model fitting. of the uncertainty in the model fitting. ...
149
64
187
149
0
astromancer/tsa
src/tsa/rednoise.py
Python
pdf_gamma
pdf_gamma
101
111
101
109
54389b0a8aeda4a84ca74cf8ad4af543c766b4bd
bigcode/the-stack
train
a74f48797eb47848e5761318
train
function
def test_memoize(frq, percent=99.9): assert (0 < percent < 100) frac = percent / 100. # 1 - epsilon if local: c = frac else: n = len(frq) c = pow(frac, 1 / n)
def test_memoize(frq, percent=99.9):
assert (0 < percent < 100) frac = percent / 100. # 1 - epsilon if local: c = frac else: n = len(frq) c = pow(frac, 1 / n)
ize # # get coordinate cache file # here = inspect.getfile(inspect.currentframe()) # moduleDir = Path(here).parent # cacheName = '.cache.confidence_solver' # cachePath = moduleDir / cacheName def test_memoize(frq, percent=99.9):
64
64
70
14
49
astromancer/tsa
src/tsa/rednoise.py
Python
test_memoize
test_memoize
271
279
271
271
a5151f50e2a4182a371d161eb084bc1a21344641
bigcode/the-stack
train
f03bbf45e237c76f896e934c
train
class
@object.__new__ class bootstrap: def __getattr__(self, name): setattr( self, name, safe_rendering( getattr( bootstrap3.forms, 'render_' + name ) ) ) return getattr(self, n...
@object.__new__ class bootstrap:
def __getattr__(self, name): setattr( self, name, safe_rendering( getattr( bootstrap3.forms, 'render_' + name ) ) ) return getattr(self, name) def button( self...
import bootstrap3.forms from jinja2 import Markup from jinjadp.utils import safe_rendering @object.__new__ class bootstrap:
32
64
180
8
23
afg984/happpycoding
jinjadp/bootstrap.py
Python
bootstrap
bootstrap
7
44
7
9
0d6659f1c0dfae08e049974c7f56e97f885205bc
bigcode/the-stack
train
b7621c22952aab3d8067e824
train
class
class SearchDutch(SearchLanguage): lang = 'nl' language_name = 'Dutch' js_stemmer_rawcode = 'dutch-stemmer.js' js_stemmer_code = js_stemmer stopwords = dutch_stopwords def init(self, options): # type: (Any) -> None self.stemmer = snowballstemmer.stemmer('dutch') def stem(se...
class SearchDutch(SearchLanguage):
lang = 'nl' language_name = 'Dutch' js_stemmer_rawcode = 'dutch-stemmer.js' js_stemmer_code = js_stemmer stopwords = dutch_stopwords def init(self, options): # type: (Any) -> None self.stemmer = snowballstemmer.stemmer('dutch') def stem(self, word): # type: (unicode...
0,128]});var t={'src/stemmer.jsx':{Stemmer:s},'src/dutch-stemmer.jsx':{DutchStemmer:a}}}(JSX)) var Stemmer = JSX.require("src/dutch-stemmer.jsx").DutchStemmer; """ class SearchDutch(SearchLanguage):
64
64
119
6
58
zhsj/sphinx
sphinx/search/nl.py
Python
SearchDutch
SearchDutch
132
145
132
132
b019be2134341ba2c1e1678987d6f347dea6e22b
bigcode/the-stack
train
45c73298948304bbb4f583da
train
function
def run_until_complete(coro): exc = False while True: try: if exc: exc = False fut = coro.throw(AwaitException) else: fut = coro.send(None) except StopIteration as ex: return ex.args[0] if fut == ('throw...
def run_until_complete(coro):
exc = False while True: try: if exc: exc = False fut = coro.throw(AwaitException) else: fut = coro.send(None) except StopIteration as ex: return ex.args[0] if fut == ('throw',): exc = True
)) finally: sys.stderr = old_stderr g.update(ns) class AwaitException(Exception): pass @types_coroutine def awaitable(*, throw=False): if throw: yield ('throw',) else: yield ('result',) def run_until_complete(coro):
64
64
74
7
57
smok-serwis/cython
tests/run/test_asyncgen.py
Python
run_until_complete
run_until_complete
152
165
152
152
99278989759deeac00383cefb349336a4e8ba177
bigcode/the-stack
train
8bc3f3cefdc3a564d93ae706
train
function
@types_coroutine def awaitable(*, throw=False): if throw: yield ('throw',) else: yield ('result',)
@types_coroutine def awaitable(*, throw=False):
if throw: yield ('throw',) else: yield ('result',)
=l, globals=g, lib_dir=os.path.dirname(__file__)) except CompileError as exc: raise SyntaxError(str(exc)) finally: sys.stderr = old_stderr g.update(ns) class AwaitException(Exception): pass @types_coroutine def awaitable(*, throw=False):
64
64
32
13
50
smok-serwis/cython
tests/run/test_asyncgen.py
Python
awaitable
awaitable
144
149
144
145
66c953c6a2dccc152a7b0c3fa22451af36154cb3
bigcode/the-stack
train
8d1991ba0c8b2cb04389daf9
train
function
def to_list(gen): async def iterate(): res = [] async for i in gen: res.append(i) return res return run_until_complete(iterate())
def to_list(gen):
async def iterate(): res = [] async for i in gen: res.append(i) return res return run_until_complete(iterate())
: try: if exc: exc = False fut = coro.throw(AwaitException) else: fut = coro.send(None) except StopIteration as ex: return ex.args[0] if fut == ('throw',): exc = True def to_list(gen):
64
64
38
5
58
smok-serwis/cython
tests/run/test_asyncgen.py
Python
to_list
to_list
168
175
168
168
1788fa8f2032efdbf6eef2c45a80265c4b6a9cb3
bigcode/the-stack
train
35c7acdb76bfbf8c250f6f51
train
function
def exec(code_string, l, g): from Cython.Compiler.Errors import CompileError from Cython.Shadow import inline try: from StringIO import StringIO except ImportError: from io import StringIO old_stderr = sys.stderr try: sys.stderr = StringIO() ns = inline(code_stri...
def exec(code_string, l, g):
from Cython.Compiler.Errors import CompileError from Cython.Shadow import inline try: from StringIO import StringIO except ImportError: from io import StringIO old_stderr = sys.stderr try: sys.stderr = StringIO() ns = inline(code_string, locals=l, globals=g, lib_...
wrapped(_GeneratorWrapper(func(*args, **kwargs))) return call try: from inspect import isawaitable as inspect_isawaitable except ImportError: def inspect_isawaitable(o): return hasattr(o, '__await__') # compiled exec() def exec(code_string, l, g):
64
64
120
9
55
smok-serwis/cython
tests/run/test_asyncgen.py
Python
exec
exec
121
137
121
121
01cfc30f9c150ba7a8feccc7ea4dbc2d056b5cc8
bigcode/the-stack
train
f59f841a56905e9768e5a20a
train
class
class AsyncGenTest(unittest.TestCase): if sys.version_info < (3, 3): @contextlib.contextmanager def assertRaisesRegex(self, exc_type, regex=None): # the error messages usually don't match, so we just ignore them try: yield except exc_type: ...
class AsyncGenTest(unittest.TestCase):
if sys.version_info < (3, 3): @contextlib.contextmanager def assertRaisesRegex(self, exc_type, regex=None): # the error messages usually don't match, so we just ignore them try: yield except exc_type: self.assertTrue(True) ...
''' with self.assertRaisesRegex(SyntaxError, 'yield from.*inside async'): exec(code, {}, {}) def test_async_gen_syntax_02(self): code = '''async def foo(): yield from 123 ''' with self.assertRaisesRegex(SyntaxError, 'yield from.*inside async'): ...
255
256
1,315
8
247
smok-serwis/cython
tests/run/test_asyncgen.py
Python
AsyncGenTest
AsyncGenTest
237
471
237
238
58acc90a654262a556a7c532093952ebfbd3d906
bigcode/the-stack
train
8414d16effcd501512328556
train
class
class AwaitException(Exception): pass
class AwaitException(Exception):
pass
: sys.stderr = StringIO() ns = inline(code_string, locals=l, globals=g, lib_dir=os.path.dirname(__file__)) except CompileError as exc: raise SyntaxError(str(exc)) finally: sys.stderr = old_stderr g.update(ns) class AwaitException(Exception):
64
64
8
5
59
smok-serwis/cython
tests/run/test_asyncgen.py
Python
AwaitException
AwaitException
140
141
140
140
ef83bac3efb41710ea6641a281eb2c4304d6dc88
bigcode/the-stack
train
799778f69571c98251b349fd
train
class
class AsyncGenSyntaxTest(unittest.TestCase): @contextlib.contextmanager def assertRaisesRegex(self, exc_type, regex): # the error messages usually don't match, so we just ignore them try: yield except exc_type: self.assertTrue(True) else: self...
class AsyncGenSyntaxTest(unittest.TestCase): @contextlib.contextmanager
def assertRaisesRegex(self, exc_type, regex): # the error messages usually don't match, so we just ignore them try: yield except exc_type: self.assertTrue(True) else: self.assertTrue(False) def test_async_gen_syntax_01(self): code = ''...
= False fut = coro.throw(AwaitException) else: fut = coro.send(None) except StopIteration as ex: return ex.args[0] if fut == ('throw',): exc = True def to_list(gen): async def iterate(): res = [] async for i in g...
103
103
345
16
87
smok-serwis/cython
tests/run/test_asyncgen.py
Python
AsyncGenSyntaxTest
AsyncGenSyntaxTest
178
234
178
180
a8837c10f7815a42d3349aeb255ac3a107b94a77
bigcode/the-stack
train
3521b12e6ead04627f587258
train
class
@requires_asyncio class AsyncGenAsyncioTest(unittest.TestCase): def setUp(self): self.loop = asyncio.new_event_loop() asyncio.set_event_loop(None) def tearDown(self): self.loop.close() self.loop = None async def to_list(self, gen): res = [] async for i in g...
@requires_asyncio class AsyncGenAsyncioTest(unittest.TestCase):
def setUp(self): self.loop = asyncio.new_event_loop() asyncio.set_event_loop(None) def tearDown(self): self.loop.close() self.loop = None async def to_list(self, gen): res = [] async for i in gen: res.append(i) return res def test_as...
self.compare_generators(sync_gen(), async_gen()) def test_async_gen_exception_10(self): async def gen(): yield 123 with self.assertRaisesRegex(TypeError, "non-None value .* async generator"): gen().__anext__().send(100) def test_asyn...
255
256
4,368
15
240
smok-serwis/cython
tests/run/test_asyncgen.py
Python
AsyncGenAsyncioTest
AsyncGenAsyncioTest
474
1,195
474
476
543978d99e6002067b993f63d5283ae17d224ccd
bigcode/the-stack
train
6f57613de095c43701c7cc3a
train
function
def needs_py36_asyncio(f): if sys.version_info >= (3, 6) or asyncio is None: # Py<3.4 doesn't have asyncio at all => avoid having to special case 2.6's unittest below return f from unittest import skip return skip("needs Python 3.6 or later")(f)
def needs_py36_asyncio(f):
if sys.version_info >= (3, 6) or asyncio is None: # Py<3.4 doesn't have asyncio at all => avoid having to special case 2.6's unittest below return f from unittest import skip return skip("needs Python 3.6 or later")(f)
try: from unittest import skip except ImportError: def requires_asyncio(c): return None else: requires_asyncio = skip("tests require asyncio") asyncio = None else: def requires_asyncio(c): return c def needs_py36_asyncio(f):
64
64
76
8
55
smok-serwis/cython
tests/run/test_asyncgen.py
Python
needs_py36_asyncio
needs_py36_asyncio
41
47
41
41
bf267568c282a523d551ae4e2b3b7c5cdc29a6cc
bigcode/the-stack
train
97afa0e08ed330fae981fc32
train
function
def listener(): rospy.init_node('listener', anonymous=True) rospy.Subscriber('/vrpn_client/raw_transform', TransformStamped, callback) rospy.spin()
def listener():
rospy.init_node('listener', anonymous=True) rospy.Subscriber('/vrpn_client/raw_transform', TransformStamped, callback) rospy.spin()
},{},{}\n'.format( data.header.stamp + time_offset, data.transform.translation.x, data.transform.translation.y, data.transform.translation.z, data.transform.rotation.w, data.transform.rotation.x, data.transform.rotation.y, data.transform.rotation.z )) ...
63
64
33
3
60
kwang-12/basalt-mirror
scripts/basalt_capture_mocap.py
Python
listener
listener
39
43
39
39
a558944b371ce3ee234f14c04e590b9155fc1a48
bigcode/the-stack
train
dca5de5845c92c4be06e194c
train
function
def callback(data): global out_file, time_offset if not out_file: return if not time_offset: time_offset = rospy.Time().now() - data.header.stamp out_file.write('{},{},{},{},{},{},{},{}\n'.format( data.header.stamp + time_offset, data.transform.translation.x, da...
def callback(data):
global out_file, time_offset if not out_file: return if not time_offset: time_offset = rospy.Time().now() - data.header.stamp out_file.write('{},{},{},{},{},{},{},{}\n'.format( data.header.stamp + time_offset, data.transform.translation.x, data.transform.transla...
lavUsenko/basalt.git # # Copyright (c) 2019-2021, Vladyslav Usenko and Nikolaus Demmel. # All rights reserved. # import sys import os import rospy import argparse from geometry_msgs.msg import TransformStamped def callback(data):
64
64
112
4
59
kwang-12/basalt-mirror
scripts/basalt_capture_mocap.py
Python
callback
callback
19
36
19
19
1b7ad4f5144be1de9996d34865730300f9e8a869
bigcode/the-stack
train
fdc75249e38cf01afe2fcc0c
train
class
class EnglishAnswerProxy(Answer): """A no-op proxy class to allow separate language indexing in Haystack""" class Meta: proxy = True
class EnglishAnswerProxy(Answer):
"""A no-op proxy class to allow separate language indexing in Haystack""" class Meta: proxy = True
if self.update_english_page: self.create_or_update_page(language='en') if self.update_spanish_page: self.create_or_update_page(language='es') def delete(self): self.answer_pages.all().delete() super(Answer, self).delete() class EnglishAnswerP...
64
64
32
7
57
contolini/cfgov-refresh
cfgov/ask_cfpb/models/django.py
Python
EnglishAnswerProxy
EnglishAnswerProxy
637
640
637
637
b505005194312e72305fb56f8840d421431a05e0
bigcode/the-stack
train
8221138c89cd439222b5272b
train
function
def generate_short_slug(slug_string): """Limits a slug to around 100 characters, using full words""" if len(slug_string) < 100: return slugify(slug_string) slug_100 = slugify(slug_string)[:100] if slug_100.endswith('-'): slug_base = slug_100.rstrip('-') else: slug_base = "-"....
def generate_short_slug(slug_string):
"""Limits a slug to around 100 characters, using full words""" if len(slug_string) < 100: return slugify(slug_string) slug_100 = slugify(slug_string)[:100] if slug_100.endswith('-'): slug_base = slug_100.rstrip('-') else: slug_base = "-".join(slug_100.split('-')[:-1]) ret...
'understand your question better.'), 'radio_question_1': 'How soon do you expect to buy a home?', 'radio_question_2': 'Do you currently own a home?', 'contact_advisory': ''}}] return stream_value def generate_short_slug(slug_string):
64
64
99
8
55
contolini/cfgov-refresh
cfgov/ask_cfpb/models/django.py
Python
generate_short_slug
generate_short_slug
59
68
59
59
0a833e4de1f1846a185a6b988b531f8af65aedb8
bigcode/the-stack
train
6418c8d435adcb0f44c22c7d
train
class
class SpanishAnswerProxy(Answer): """A no-op proxy class to allow separate language indexing in Haystack""" class Meta: proxy = True
class SpanishAnswerProxy(Answer):
"""A no-op proxy class to allow separate language indexing in Haystack""" class Meta: proxy = True
='es') def delete(self): self.answer_pages.all().delete() super(Answer, self).delete() class EnglishAnswerProxy(Answer): """A no-op proxy class to allow separate language indexing in Haystack""" class Meta: proxy = True class SpanishAnswerProxy(Answer):
64
64
32
7
56
contolini/cfgov-refresh
cfgov/ask_cfpb/models/django.py
Python
SpanishAnswerProxy
SpanishAnswerProxy
643
646
643
643
b5416b16a55467125ee906b50337b1a35b7eaa46
bigcode/the-stack
train
92e51c7e85b28678d299b53d
train
class
class Category(models.Model): name = models.CharField(max_length=255) name_es = models.CharField(max_length=255) slug = models.SlugField(help_text="Do not edit this field") slug_es = models.SlugField(help_text="Do not edit this field") intro = RichTextField( blank=True, help_text=( ...
class Category(models.Model):
name = models.CharField(max_length=255) name_es = models.CharField(max_length=255) slug = models.SlugField(help_text="Do not edit this field") slug_es = models.SlugField(help_text="Do not edit this field") intro = RichTextField( blank=True, help_text=( "Do not use H2, H3,...
_question_2': 'Do you currently own a home?', 'contact_advisory': ''}}] return stream_value def generate_short_slug(slug_string): """Limits a slug to around 100 characters, using full words""" if len(slug_string) < 100: return slugify(slug_string) slug_100 = slugify(slug_string)[:...
244
244
815
5
238
contolini/cfgov-refresh
cfgov/ask_cfpb/models/django.py
Python
Category
Category
97
200
97
97
5fe2a3190a5e4060e032c5a9b8de585230878d3e
bigcode/the-stack
train
e82b8610cee09415c0092654
train
function
def get_feedback_stream_value(page): """Delivers a basic feedback module with yes/no buttons and comment box""" translation_text = { 'helpful': {'es': '¿Fue útil esta respuesta?', 'en': 'Was this page helpful to you?'}, 'button': {'es': 'Enviar', 'en': 'Sub...
def get_feedback_stream_value(page):
"""Delivers a basic feedback module with yes/no buttons and comment box""" translation_text = { 'helpful': {'es': '¿Fue útil esta respuesta?', 'en': 'Was this page helpful to you?'}, 'button': {'es': 'Enviar', 'en': 'Submit'} } stream_value = [ ...
from v1.util.migrations import get_or_create_page from v1.util.util import validate_social_sharing_image html_parser = HTMLParser.HTMLParser() ENGLISH_PARENT_SLUG = 'ask-cfpb' SPANISH_PARENT_SLUG = 'obtener-respuestas' def get_feedback_stream_value(page):
64
64
208
7
57
contolini/cfgov-refresh
cfgov/ask_cfpb/models/django.py
Python
get_feedback_stream_value
get_feedback_stream_value
35
56
35
35
73412e2484c6dc3f562ace4d24961d32d62f828c
bigcode/the-stack
train
ed8a78ba81b7e41d62e12a5c
train
class
class SubCategory(models.Model): name = models.CharField(max_length=255) name_es = models.CharField(max_length=255, null=True, blank=True) slug = models.SlugField() slug_es = models.SlugField( null=True, blank=True, help_text="This field is not currently used on the front end.") ...
class SubCategory(models.Model):
name = models.CharField(max_length=255) name_es = models.CharField(max_length=255, null=True, blank=True) slug = models.SlugField() slug_es = models.SlugField( null=True, blank=True, help_text="This field is not currently used on the front end.") weight = models.IntegerField(...
udience] if _map['all']: _map[ID] = [] for answer_id in subcat_data[ID]: if answer_id in _map['all']: _map[ID].append(answer_id) container['audiences'].update( {str(audience.id): audience_map[...
107
107
357
6
101
contolini/cfgov-refresh
cfgov/ask_cfpb/models/django.py
Python
SubCategory
SubCategory
203
253
203
203
f78c8374c7c9868c5ba205df748a142d76a6ac59
bigcode/the-stack
train
a78fbfa0dfe835f6167dc5d9
train
class
class Answer(models.Model): last_user = models.ForeignKey(User, blank=True, null=True) category = models.ManyToManyField( 'Category', blank=True, help_text=( "Categorize this answer. " "Avoid putting into more than one category.")) question = models.TextField(...
class Answer(models.Model):
last_user = models.ForeignKey(User, blank=True, null=True) category = models.ManyToManyField( 'Category', blank=True, help_text=( "Categorize this answer. " "Avoid putting into more than one category.")) question = models.TextField(blank=True) statement = ...
on the front end.") description_es = RichTextField( blank=True, help_text="This field is not currently displayed on the front end.") more_info = models.TextField( blank=True, help_text="This field is not currently displayed on the front end.") parent = models.ForeignKey( ...
256
256
2,894
5
251
contolini/cfgov-refresh
cfgov/ask_cfpb/models/django.py
Python
Answer
Answer
256
634
256
256
20b44fb31fc57632ee90a945e33efeb673277bbc
bigcode/the-stack
train
12858f81a49f0fc0fd184db3
train
class
class Audience(models.Model): name = models.CharField(max_length=255) panels = [ FieldPanel('name'), ] def __str__(self): return self.name
class Audience(models.Model):
name = models.CharField(max_length=255) panels = [ FieldPanel('name'), ] def __str__(self): return self.name
_string) slug_100 = slugify(slug_string)[:100] if slug_100.endswith('-'): slug_base = slug_100.rstrip('-') else: slug_base = "-".join(slug_100.split('-')[:-1]) return slug_base class Audience(models.Model):
64
64
40
5
58
contolini/cfgov-refresh
cfgov/ask_cfpb/models/django.py
Python
Audience
Audience
71
79
71
71
8d6be35954421e5dbae4f78f6e71e6408028fd62
bigcode/the-stack
train
17bcd56df240e20a8c483fb5
train
class
class NextStep(models.Model): title = models.CharField(max_length=255) show_title = models.BooleanField(default=False) text = RichTextField(blank=True) panels = [ FieldPanel('title'), FieldPanel('show_title'), FieldPanel('text'), ] def __str__(self): return self...
class NextStep(models.Model):
title = models.CharField(max_length=255) show_title = models.BooleanField(default=False) text = RichTextField(blank=True) panels = [ FieldPanel('title'), FieldPanel('show_title'), FieldPanel('text'), ] def __str__(self): return self.title
"-".join(slug_100.split('-')[:-1]) return slug_base class Audience(models.Model): name = models.CharField(max_length=255) panels = [ FieldPanel('name'), ] def __str__(self): return self.name class NextStep(models.Model):
64
64
73
6
57
contolini/cfgov-refresh
cfgov/ask_cfpb/models/django.py
Python
NextStep
NextStep
82
94
82
82
e173f2c2fe48646497dff5530e76683e824dde40
bigcode/the-stack
train
42edec3db64ece1d2c8fdf35
train
class
class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ n1 = self.processList(l1) n2 = self.processList(l2) answer = str(n1 + n2)[::-1] l3 = ListNode(answer[0], None) temp ...
class Solution(object):
def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ n1 = self.processList(l1) n2 = self.processList(l2) answer = str(n1 + n2)[::-1] l3 = ListNode(answer[0], None) temp = l3 for e in an...
approach: iterative processing # memory: (n) # runtime: (2n) # Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object):
64
64
186
4
59
frankpiva/leetcode
problemset/2.py
Python
Solution
Solution
24
50
24
24
4facc2e3668ade0841a8411fb72bcc2d08300df1
bigcode/the-stack
train
ddeeaa52fba3e3f5cd9e772f
train
class
class Migration(migrations.Migration): dependencies = [ ('polls', '0002_auto_20200609_2225'), ] operations = [ migrations.AlterField( model_name='schedule', name='id_teacher_id', field=models.IntegerField(null=True), ), ]
class Migration(migrations.Migration):
dependencies = [ ('polls', '0002_auto_20200609_2225'), ] operations = [ migrations.AlterField( model_name='schedule', name='id_teacher_id', field=models.IntegerField(null=True), ), ]
# Generated by Django 3.0.7 on 2020-06-09 15:32 from django.db import migrations, models class Migration(migrations.Migration):
38
64
64
7
30
NightSky72/proekt
polls/migrations/0003_auto_20200609_2232.py
Python
Migration
Migration
6
18
6
7
e065238a8109dcdf25c5a33c97b3bc9fbcf2b1f2
bigcode/the-stack
train
c9001e89c570a5b1f3d80f9b
train
class
class ProcessState(PostSortRec): def __init__(self, uow, dependency_processor, delete, state): self.dependency_processor = dependency_processor self.delete = delete self.state = state def execute_aggregate(self, uow, recs): cls_ = self.__class__ dependency_processor = se...
class ProcessState(PostSortRec):
def __init__(self, uow, dependency_processor, delete, state): self.dependency_processor = dependency_processor self.delete = delete self.state = state def execute_aggregate(self, uow, recs): cls_ = self.__class__ dependency_processor = self.dependency_processor d...
state, base_mapper) uow.dependencies.add((save_all, action)) yield action for dep in uow.deps[self.mapper]: states_for_prop = uow.filter_states_for_dep(dep, states) dep.per_state_flush_actions(uow, states_for_prop, True) class ProcessState(PostSortRec):
68
68
229
7
61
lindamar/ecclesi
env/lib/python2.7/site-packages/sqlalchemy/orm/unitofwork.py
Python
ProcessState
ProcessState
597
624
597
597
4316f4a00a3da9fc52874d13ffa06af6c25f1b96
bigcode/the-stack
train
d23d56cbf87924c0dd78f6e5
train
function
def track_cascade_events(descriptor, prop): """Establish event listeners on object attributes which handle cascade-on-set/append. """ key = prop.key def append(state, item, initiator): # process "save_update" cascade rules for when # an instance is appended to the list of another i...
def track_cascade_events(descriptor, prop):
"""Establish event listeners on object attributes which handle cascade-on-set/append. """ key = prop.key def append(state, item, initiator): # process "save_update" cascade rules for when # an instance is appended to the list of another instance if item is None: ...
# orm/unitofwork.py # Copyright (C) 2005-2016 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """The internals for the unit of work system. The session's flush() process passe...
159
180
602
10
148
lindamar/ecclesi
env/lib/python2.7/site-packages/sqlalchemy/orm/unitofwork.py
Python
track_cascade_events
track_cascade_events
23
106
23
23
7a33ce18fc0825b8ea71e8044c0e7ed8acb30a3a
bigcode/the-stack
train
99c21a71a98eead1841ab1c6
train
class
class IterateMappersMixin(object): def _mappers(self, uow): if self.fromparent: return iter( m for m in self.dependency_processor.parent.self_and_descendants if uow._mapper_for_dep[(m, self.dependency_processor)] ) else: ...
class IterateMappersMixin(object):
def _mappers(self, uow): if self.fromparent: return iter( m for m in self.dependency_processor.parent.self_and_descendants if uow._mapper_for_dep[(m, self.dependency_processor)] ) else: return self.dependency_process...
delete, listonly)) in self.states.items() if isdelete ) other = states.difference(isdel) if isdel: self.session._remove_newly_deleted(isdel) if other: self.session._register_newly_persistent(other) class IterateMappersMixin(object):
64
64
77
7
57
lindamar/ecclesi
env/lib/python2.7/site-packages/sqlalchemy/orm/unitofwork.py
Python
IterateMappersMixin
IterateMappersMixin
414
423
414
414
c355f53094b4004d4352d3cbfcfa94830279f0c8
bigcode/the-stack
train
843b4cbc9817d5b578754db4
train
class
class DeleteAll(PostSortRec): def __init__(self, uow, mapper): self.mapper = mapper assert mapper is mapper.base_mapper def execute(self, uow): persistence.delete_obj(self.mapper, uow.states_for_mapper_hierarchy( self.map...
class DeleteAll(PostSortRec):
def __init__(self, uow, mapper): self.mapper = mapper assert mapper is mapper.base_mapper def execute(self, uow): persistence.delete_obj(self.mapper, uow.states_for_mapper_hierarchy( self.mapper, True, False), ...
_mapper) uow.dependencies.add((action, delete_all)) yield action for dep in uow.deps[self.mapper]: states_for_prop = uow.filter_states_for_dep(dep, states) dep.per_state_flush_actions(uow, states_for_prop, False) class DeleteAll(PostSortRec):
65
65
217
7
58
lindamar/ecclesi
env/lib/python2.7/site-packages/sqlalchemy/orm/unitofwork.py
Python
DeleteAll
DeleteAll
568
594
568
568
79220a18e720b399d252217d4bd75c78a59258c3
bigcode/the-stack
train
1f89c55d608cf1bd00c23e54
train
class
class ProcessAll(IterateMappersMixin, PostSortRec): def __init__(self, uow, dependency_processor, delete, fromparent): self.dependency_processor = dependency_processor self.delete = delete self.fromparent = fromparent uow.deps[dependency_processor.parent.base_mapper].\ ad...
class ProcessAll(IterateMappersMixin, PostSortRec):
def __init__(self, uow, dependency_processor, delete, fromparent): self.dependency_processor = dependency_processor self.delete = delete self.fromparent = fromparent uow.deps[dependency_processor.parent.base_mapper].\ add(dependency_processor) def execute(self, uow):...
\ object.__new__(cls) return ret def execute_aggregate(self, uow, recs): self.execute(uow) def __repr__(self): return "%s(%s)" % ( self.__class__.__name__, ",".join(str(x) for x in self.__dict__.values()) ) class ProcessAll(IterateMa...
86
86
288
14
72
lindamar/ecclesi
env/lib/python2.7/site-packages/sqlalchemy/orm/unitofwork.py
Python
ProcessAll
ProcessAll
490
524
490
490
691b3f7cad59ad72f78084f4efe24983481cc7ec
bigcode/the-stack
train