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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
171a363afca53a75ff7d36da | train | function | def cleanup():
# Clean up the file descriptors and processes, just in case.
import os
if header_read_fd >= 0:
try:
os.close(header_read_fd)
except os.error:
pass
if header_write_fd >= 0:
try:
os.close(header_write_fd)
except os.error:
... | def cleanup():
# Clean up the file descriptors and processes, just in case.
| import os
if header_read_fd >= 0:
try:
os.close(header_read_fd)
except os.error:
pass
if header_write_fd >= 0:
try:
os.close(header_write_fd)
except os.error:
pass
if sortopt_read_fd >= 0:
try:
... | _read_fd : int = -1
header_write_fd: int = -1
sortopt_read_fd : int = -1
sortopt_write_fd: int = -1
cat_proc = None
cmd_proc = None
def cleanup():
# Clean up the file descriptors and processes, just in case.
| 64 | 64 | 205 | 17 | 46 | vishalbelsare/kgtk | kgtk/cli/sort.py | Python | cleanup | cleanup | 155 | 196 | 155 | 156 | cfebada9c517312108197a6f8a40ac9cec50c6f9 | bigcode/the-stack | train |
9c0f2a32fc79bd7f243f331e | train | function | def keyboard_interrupt():
cleanup()
| def keyboard_interrupt():
| cleanup()
| :
try:
cat_proc.kill_group()
except os.error:
pass
cat_proc = None
global cmd_proc
if cmd_proc is not None:
try:
cmd_proc.kill_group()
except os.error:
pass
cat_proc = None
def keyboard_interrupt():
| 64 | 64 | 7 | 4 | 59 | vishalbelsare/kgtk | kgtk/cli/sort.py | Python | keyboard_interrupt | keyboard_interrupt | 198 | 199 | 198 | 198 | c9771b80b87f0f348620ebcedc8e8d0ef04970d7 | bigcode/the-stack | train |
0817aace6b3fea684be1f319 | train | function | def parser():
return {
'help': 'Sort file based on one or more columns',
'aliases': ['sort2']
}
| def parser():
| return {
'help': 'Sort file based on one or more columns',
'aliases': ['sort2']
}
| more portable but slower and mor memory
intensive than using the system sort program to sort the input KGTK file.
"""
from argparse import Namespace, SUPPRESS
import typing
from kgtk.cli_argparse import KGTKArgumentParser, KGTKFiles
from kgtk.exceptions import KGTKException
def parser():
| 64 | 64 | 30 | 3 | 60 | vishalbelsare/kgtk | kgtk/cli/sort.py | Python | parser | parser | 53 | 57 | 53 | 53 | 6c709ccdbfd08f460ab825ac3a7d970ca6c9349c | bigcode/the-stack | train |
a2d52c088982def5c5fc0753 | train | function | def add_arguments_extended(parser: KGTKArgumentParser, parsed_shared_args: Namespace):
from kgtk.io.kgtkreader import KgtkReader, KgtkReaderOptions
from kgtk.utils.argparsehelpers import optional_bool
from kgtk.value.kgtkvalueoptions import KgtkValueOptions
_expert: bool = parsed_shared_args._expert
... | def add_arguments_extended(parser: KGTKArgumentParser, parsed_shared_args: Namespace):
| from kgtk.io.kgtkreader import KgtkReader, KgtkReaderOptions
from kgtk.utils.argparsehelpers import optional_bool
from kgtk.value.kgtkvalueoptions import KgtkValueOptions
_expert: bool = parsed_shared_args._expert
# This helper function makes it easy to suppress options from
# The help message... | from the dirst pipe
7) The Python control process feeds the header line to KgtkReader.
8) The Python control process builds the sort key options using
column indexes obtained from KgtkReader.
9) The sort key options are sent from Python to the data processing pipeline
via the second pipe.
10) The data proces... | 256 | 256 | 1,167 | 17 | 239 | vishalbelsare/kgtk | kgtk/cli/sort.py | Python | add_arguments_extended | add_arguments_extended | 59 | 144 | 59 | 59 | 6a2f8d3f0a053becbd82d92922bd9fa367321611 | bigcode/the-stack | train |
ff7733bb45335a4ec94053e4 | train | function | def test_suite():
return unittest.makeSuite(SimpleRecnoTestCase)
| def test_suite():
| return unittest.makeSuite(SimpleRecnoTestCase)
| , dbtype=db.DB_RECNO, flags=db.DB_CREATE)
row_id = d.append(' ')
self.assertEqual(1, d.get_size(key=row_id))
row_id = d.append('')
self.assertEqual(0, d.get_size(key=row_id))
#----------------------------------------------------------------------
def test_suite():
| 64 | 64 | 15 | 4 | 59 | shoemakerdr/bsddb3 | Lib3/bsddb/test/test_recno.py | Python | test_suite | test_suite | 339 | 340 | 339 | 339 | f25e1701e382e1841866eb5ef3259a9cc3c6ea15 | bigcode/the-stack | train |
7430bb82b222f27aef18516c | train | class | class SimpleRecnoTestCase(unittest.TestCase):
if sys.version_info < (2, 7) :
def assertIsInstance(self, obj, datatype, msg=None) :
return self.assertEqual(type(obj), datatype, msg=msg)
def assertGreaterEqual(self, a, b, msg=None) :
return self.assertTrue(a>=b, msg=msg)
... | class SimpleRecnoTestCase(unittest.TestCase):
| if sys.version_info < (2, 7) :
def assertIsInstance(self, obj, datatype, msg=None) :
return self.assertEqual(type(obj), datatype, msg=msg)
def assertGreaterEqual(self, a, b, msg=None) :
return self.assertTrue(a>=b, msg=msg)
def setUp(self):
self.filename = get_n... | of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANT... | 256 | 256 | 1,834 | 10 | 245 | shoemakerdr/bsddb3 | Lib3/bsddb/test/test_recno.py | Python | SimpleRecnoTestCase | SimpleRecnoTestCase | 50 | 330 | 50 | 50 | f4f4aade6e4e1f99154375f39879445aa148bd9a | bigcode/the-stack | train |
5ce3859d863fd4ebefacbdd9 | train | function | def write_unmatched_events_file(file_path):
with open(file_path, 'w') as csv_file:
writer = csv.writer(csv_file)
writer.writerow(UNMATCHED_EVENT_FILE_COLUMN_NAMES)
rows = [get_unmatched_events_file_row(*e) for e in unmatched_events]
rows.sort()
... | def write_unmatched_events_file(file_path):
| with open(file_path, 'w') as csv_file:
writer = csv.writer(csv_file)
writer.writerow(UNMATCHED_EVENT_FILE_COLUMN_NAMES)
rows = [get_unmatched_events_file_row(*e) for e in unmatched_events]
rows.sort()
writer.writerows(rows)
| lat, lon, year, event_name = key
writer.writerow((
lat, lon, year, event_name,
c[-2], c[-1], c[0], c[1], c[2],
sf, usno))
def write_unmatched_events_file(file_path):
| 63 | 64 | 76 | 10 | 53 | Tubbz-alt/Vesper | vesper/ephem/tests/scripts/test_skyfield.py | Python | write_unmatched_events_file | write_unmatched_events_file | 248 | 259 | 248 | 249 | a4a6a1485d2cf403107a41391c576a99885ad0a6 | bigcode/the-stack | train |
99cb654bf706412026000504 | train | function | def write_diff_count_file(file_path):
with open(file_path, 'w') as csv_file:
writer = csv.writer(csv_file)
writer.writerow(DIFF_COUNT_FILE_COLUMN_NAMES)
keys = sorted(event_time_diff_counts.keys())
for key in keys:
c =... | def write_diff_count_file(file_path):
| with open(file_path, 'w') as csv_file:
writer = csv.writer(csv_file)
writer.writerow(DIFF_COUNT_FILE_COLUMN_NAMES)
keys = sorted(event_time_diff_counts.keys())
for key in keys:
c = event_time_diff_counts[key]
sf... | _unmatched_event('USNO', key, usno_time)
usno_index += 1
def record_unmatched_event(source, key, time):
unmatched_event_counts[source][key] += 1
unmatched_events.append((source, key, time))
def write_diff_count_file(file_path):
| 64 | 64 | 150 | 9 | 55 | Tubbz-alt/Vesper | vesper/ephem/tests/scripts/test_skyfield.py | Python | write_diff_count_file | write_diff_count_file | 224 | 245 | 224 | 225 | f4b24928c7940aa976994388015ae4dd56a3d46d | bigcode/the-stack | train |
b513720d95bd3128e97aa6d7 | train | function | def get_skyfield_event_times(lat, lon, year, event_name, utc_offset):
events = skyfield_event_cache.get((lat, lon, year))
if events is None:
# Get all Skyfield events for the specified lat, lon, and year.
c = AstronomicalCalculator(lat, lon)
time_zone = datetime.timezo... | def get_skyfield_event_times(lat, lon, year, event_name, utc_offset):
| events = skyfield_event_cache.get((lat, lon, year))
if events is None:
# Get all Skyfield events for the specified lat, lon, and year.
c = AstronomicalCalculator(lat, lon)
time_zone = datetime.timezone(utc_offset)
start_time = datetime.datetime(year, 1, 1, tzinfo=ti... | _event_times(
t.lat, t.lon, t.year, event_name, t.utc_offset)
match_events(t.lat, t.lon, t.year, event_name, sf_times, usno_times)
def get_skyfield_event_times(lat, lon, year, event_name, utc_offset):
| 63 | 64 | 184 | 20 | 43 | Tubbz-alt/Vesper | vesper/ephem/tests/scripts/test_skyfield.py | Python | get_skyfield_event_times | get_skyfield_event_times | 148 | 166 | 148 | 149 | 1d604ef91aa98ef8867cc43d52ad3532bbfb3637 | bigcode/the-stack | train |
0b94336d0b3626136791878b | train | function | def create_count_dict():
return defaultdict(int)
| def create_count_dict():
| return defaultdict(int)
| ',
'2 Diffs',
'Unmatched Skyfield Events',
'Unmatched USNO Events'
)
UNMATCHED_EVENT_FILE_COLUMN_NAMES = (
'Latitude',
'Longitude',
'Year',
'Time',
'Event Name',
'Source'
)
def create_count_dict():
| 64 | 64 | 10 | 5 | 59 | Tubbz-alt/Vesper | vesper/ephem/tests/scripts/test_skyfield.py | Python | create_count_dict | create_count_dict | 82 | 83 | 82 | 82 | 3729b3c85e5f88a651c15366f63048d294ac1360 | bigcode/the-stack | train |
53e9e0f826e539f0bac39f90 | train | function | def match_events(lat, lon, year, event_name, sf_times, usno_times):
key = (lat, lon, year, event_name)
sf_count = len(sf_times)
usno_count = len(usno_times)
sf_index = 0
usno_index = 0
while sf_index != sf_count and usno_index != usno_count:
sf_time = sf_time... | def match_events(lat, lon, year, event_name, sf_times, usno_times):
| key = (lat, lon, year, event_name)
sf_count = len(sf_times)
usno_count = len(usno_times)
sf_index = 0
usno_index = 0
while sf_index != sf_count and usno_index != usno_count:
sf_time = sf_times[sf_index]
usno_time = usno_times[usno_index]
d... | _zone)
end_time = datetime.datetime(year + 1, 1, 1, tzinfo=time_zone)
events = c.get_solar_events(start_time, end_time)
skyfield_event_cache[(lat, lon, year)] = events
# Get times of events of interest.
times = [time for time, name in events if name == event_name]
... | 105 | 105 | 350 | 20 | 84 | Tubbz-alt/Vesper | vesper/ephem/tests/scripts/test_skyfield.py | Python | match_events | match_events | 169 | 216 | 169 | 170 | f7afe78010641d4ee2fad1fb066ecb853e6bacb2 | bigcode/the-stack | train |
12fb164d2ea5e852fdb700cc | train | function | def record_unmatched_event(source, key, time):
unmatched_event_counts[source][key] += 1
unmatched_events.append((source, key, time))
| def record_unmatched_event(source, key, time):
| unmatched_event_counts[source][key] += 1
unmatched_events.append((source, key, time))
| sf_index += 1
while usno_index != usno_count:
usno_time = usno_times[usno_index]
record_unmatched_event('USNO', key, usno_time)
usno_index += 1
def record_unmatched_event(source, key, time):
| 64 | 64 | 34 | 11 | 52 | Tubbz-alt/Vesper | vesper/ephem/tests/scripts/test_skyfield.py | Python | record_unmatched_event | record_unmatched_event | 219 | 221 | 219 | 219 | 18cde5d7e7a4c525e3d505eda7238ce0d2ea89a6 | bigcode/the-stack | train |
0dd5eb1a8c8d8f91d931dffd | train | function | def get_unmatched_events_file_row(source, key, time):
lat, lon, year, event_name = key
return lat, lon, year, str(time), event_name, source
| def get_unmatched_events_file_row(source, key, time):
| lat, lon, year, event_name = key
return lat, lon, year, str(time), event_name, source
| csv.writer(csv_file)
writer.writerow(UNMATCHED_EVENT_FILE_COLUMN_NAMES)
rows = [get_unmatched_events_file_row(*e) for e in unmatched_events]
rows.sort()
writer.writerows(rows)
def get_unmatched_events_file_row(source, key, time):
| 62 | 64 | 41 | 13 | 49 | Tubbz-alt/Vesper | vesper/ephem/tests/scripts/test_skyfield.py | Python | get_unmatched_events_file_row | get_unmatched_events_file_row | 262 | 264 | 262 | 262 | c5bb633e87c992a73162bdd65f89873c77c72789 | bigcode/the-stack | train |
1b0386128ad367eae6ec1439 | train | function | def main():
table_file_paths = list(USNO_TABLES_DIR_PATH.glob('**/*.txt'))
# table_file_paths = table_file_paths[:2]
table_file_count = len(table_file_paths)
for i, table_file_path in enumerate(table_file_paths):
print(
f'Processing USNO table "{table_file_pa... | def main():
| table_file_paths = list(USNO_TABLES_DIR_PATH.glob('**/*.txt'))
# table_file_paths = table_file_paths[:2]
table_file_count = len(table_file_paths)
for i, table_file_path in enumerate(table_file_paths):
print(
f'Processing USNO table "{table_file_path.name}" '
... | _dict)
"""(lat, lon, year, event name) -> diff -> count"""
unmatched_event_counts = defaultdict(create_count_dict)
"""source name -> (lat, lon, year, event name) -> count"""
unmatched_events = []
"""(source, (lat, lon, year, event name), time) list"""
def main():
| 72 | 72 | 242 | 4 | 68 | Tubbz-alt/Vesper | vesper/ephem/tests/scripts/test_skyfield.py | Python | main | main | 99 | 129 | 99 | 100 | e14e84c064cb000350b7d0f2a7f3800ee111a8b6 | bigcode/the-stack | train |
9c9de53120a822ecefc15f8c | train | function | def get_and_match_skyfield_events(t, usno_times, event_name):
sf_times = get_skyfield_event_times(
t.lat, t.lon, t.year, event_name, t.utc_offset)
match_events(t.lat, t.lon, t.year, event_name, sf_times, usno_times)
| def get_and_match_skyfield_events(t, usno_times, event_name):
| sf_times = get_skyfield_event_times(
t.lat, t.lon, t.year, event_name, t.utc_offset)
match_events(t.lat, t.lon, t.year, event_name, sf_times, usno_times)
| _file(UNMATCHED_EVENTS_FILE_PATH)
def read_usno_table(file_path):
with open(file_path) as table_file:
text = table_file.read()
return UsnoRiseSetTable(text)
def get_and_match_skyfield_events(t, usno_times, event_name):
| 64 | 64 | 69 | 18 | 46 | Tubbz-alt/Vesper | vesper/ephem/tests/scripts/test_skyfield.py | Python | get_and_match_skyfield_events | get_and_match_skyfield_events | 140 | 145 | 140 | 141 | 31188adb2ff988a57b9d7eab303d3b77f9739df4 | bigcode/the-stack | train |
0425ae890ab8e9f7f4b14909 | train | function | def read_usno_table(file_path):
with open(file_path) as table_file:
text = table_file.read()
return UsnoRiseSetTable(text)
| def read_usno_table(file_path):
| with open(file_path) as table_file:
text = table_file.read()
return UsnoRiseSetTable(text)
| event_name = SETTING_EVENT_NAMES[t.type]
get_and_match_skyfield_events(t, usno_times, event_name)
write_diff_count_file(DIFF_COUNT_FILE_PATH)
write_unmatched_events_file(UNMATCHED_EVENTS_FILE_PATH)
def read_usno_table(file_path):
| 63 | 64 | 36 | 9 | 54 | Tubbz-alt/Vesper | vesper/ephem/tests/scripts/test_skyfield.py | Python | read_usno_table | read_usno_table | 132 | 137 | 132 | 133 | 2a34edac7f27daf734b353bd0739c3cd21dad3a6 | bigcode/the-stack | train |
e3a455f04d880c39156623be | train | class | class AuthTokenSerializer(serializers.Serializer):
email = serializers.CharField()
password = serializers.CharField(
style={'input_type': 'password'},
trim_whitespace=False,
)
def validate(self, attrs):
email = attrs.get('email')
password = attrs.get('password')
... | class AuthTokenSerializer(serializers.Serializer):
| email = serializers.CharField()
password = serializers.CharField(
style={'input_type': 'password'},
trim_whitespace=False,
)
def validate(self, attrs):
email = attrs.get('email')
password = attrs.get('password')
user = authenticate(
request=self.cont... | password=validated_data['password']
)
return user
def update(self, instance, validated_data):
if 'password' in validated_data:
password = validated_data.pop('password')
instance.set_password(password)
return super().update(instance, validated_data)
class A... | 64 | 64 | 123 | 7 | 57 | gfy777/recipe-app-api | app/user/serializers.py | Python | AuthTokenSerializer | AuthTokenSerializer | 38 | 60 | 38 | 38 | c9f6707f64362e7987baa3233fcd302630dfee8c | bigcode/the-stack | train |
6119ef67b687b9b4d0f7bee7 | train | class | class UserSerializer(serializers.ModelSerializer):
"""Serializers for the user serializers"""
class Meta:
model = get_user_model()
fields = ('email', 'password', 'name')
extra_kwargs = {
'password': {
'write_only': True,
'style': {'input_type... | class UserSerializer(serializers.ModelSerializer):
| """Serializers for the user serializers"""
class Meta:
model = get_user_model()
fields = ('email', 'password', 'name')
extra_kwargs = {
'password': {
'write_only': True,
'style': {'input_type': 'password'},
'min_length': 7,
... | from django.contrib.auth import get_user_model, authenticate
from rest_framework import serializers
from django.utils.translation import ugettext_lazy as _
class UserSerializer(serializers.ModelSerializer):
| 34 | 64 | 172 | 7 | 27 | gfy777/recipe-app-api | app/user/serializers.py | Python | UserSerializer | UserSerializer | 6 | 35 | 6 | 6 | b5559e11a194865a68a160e2497da3b4e766d52d | bigcode/the-stack | train |
f2f70f24ed1834709a1ac52d | train | class | class AntispamFilter(UpdateFilter):
def filter(self, update: Update):
return get_user_data(update.effective_user.id).get(ReplyButtons.antispam)
| class AntispamFilter(UpdateFilter):
| def filter(self, update: Update):
return get_user_data(update.effective_user.id).get(ReplyButtons.antispam)
| constants import ReplyButtons
def get_user_data(user_id):
from main import dispatcher
return dispatcher.user_data[user_id]
class FontFilter(UpdateFilter):
def filter(self, update: Update):
return get_user_data(update.effective_user.id).get('font')
class AntispamFilter(UpdateFilter):
| 64 | 64 | 36 | 8 | 56 | adrian-kalinin/insta-text-telegram-bot | bot/filters.py | Python | AntispamFilter | AntispamFilter | 18 | 20 | 18 | 18 | e50e87933442e27b7b1318deadcb2bd40b63d1b4 | bigcode/the-stack | train |
67607331059ebe7b20ac9f15 | train | class | class FontFilter(UpdateFilter):
def filter(self, update: Update):
return get_user_data(update.effective_user.id).get('font')
| class FontFilter(UpdateFilter):
| def filter(self, update: Update):
return get_user_data(update.effective_user.id).get('font')
| from telegram import Update
from telegram.ext import UpdateFilter
from .constants import ReplyButtons
def get_user_data(user_id):
from main import dispatcher
return dispatcher.user_data[user_id]
class FontFilter(UpdateFilter):
| 46 | 64 | 30 | 6 | 40 | adrian-kalinin/insta-text-telegram-bot | bot/filters.py | Python | FontFilter | FontFilter | 13 | 15 | 13 | 13 | d8164afd0cac11dff98f7da59555ec7d16856d75 | bigcode/the-stack | train |
27a108bd166ab475c70d9377 | train | class | class InstagramFilter(UpdateFilter):
def filter(self, update: Update):
return get_user_data(update.effective_user.id).get(ReplyButtons.instagram)
| class InstagramFilter(UpdateFilter):
| def filter(self, update: Update):
return get_user_data(update.effective_user.id).get(ReplyButtons.instagram)
| filter(self, update: Update):
return get_user_data(update.effective_user.id).get('font')
class AntispamFilter(UpdateFilter):
def filter(self, update: Update):
return get_user_data(update.effective_user.id).get(ReplyButtons.antispam)
class InstagramFilter(UpdateFilter):
| 64 | 64 | 32 | 6 | 58 | adrian-kalinin/insta-text-telegram-bot | bot/filters.py | Python | InstagramFilter | InstagramFilter | 23 | 25 | 23 | 23 | 6cb3df87bf428d2b071e28ae892d924cf399bb35 | bigcode/the-stack | train |
ad116b6464aa73d6ed9f9bce | train | function | def get_user_data(user_id):
from main import dispatcher
return dispatcher.user_data[user_id]
| def get_user_data(user_id):
| from main import dispatcher
return dispatcher.user_data[user_id]
| from telegram import Update
from telegram.ext import UpdateFilter
from .constants import ReplyButtons
def get_user_data(user_id):
| 26 | 64 | 21 | 7 | 18 | adrian-kalinin/insta-text-telegram-bot | bot/filters.py | Python | get_user_data | get_user_data | 7 | 10 | 7 | 7 | c7aa368bb9253f7e669db8adb38b35eaa96465b7 | bigcode/the-stack | train |
6a80c070641767c278850c29 | train | class | class ExtractedFeaturesDataset(FairseqDataset):
def __init__(
self,
path,
split,
min_length=3,
max_length=None,
labels=None,
label_dict=None,
shuffle=True,
sort_by_length=True,
):
super().__init__()
self.min_l... | class ExtractedFeaturesDataset(FairseqDataset):
| def __init__(
self,
path,
split,
min_length=3,
max_length=None,
labels=None,
label_dict=None,
shuffle=True,
sort_by_length=True,
):
super().__init__()
self.min_length = min_length
self.max_length = max... | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
import os
import contextlib
import numpy as np
import torch
from fairseq.data import FairseqDataset, data_utils... | 89 | 255 | 851 | 10 | 79 | guotao0628/DeepNet | edgelm/examples/wav2vec/unsupervised/data/extracted_features_dataset.py | Python | ExtractedFeaturesDataset | ExtractedFeaturesDataset | 20 | 144 | 20 | 20 | dad9d67cf544ac63d2b2107e8deb6ffb76b899b6 | bigcode/the-stack | train |
e3951cd16efd2a45ad8740c9 | train | function | def deep_walk(root_folder, hash=None, callback=None):
for path, dirs, files in os.walk(root_folder):
for d in dirs:
yield buildresult(path, d)
if callback:
callback(1)
for f in files:
result = buildresult(path, f)
if hash:
... | def deep_walk(root_folder, hash=None, callback=None):
| for path, dirs, files in os.walk(root_folder):
for d in dirs:
yield buildresult(path, d)
if callback:
callback(1)
for f in files:
result = buildresult(path, f)
if hash:
result.stats['md5'] = md5(Path(path).joinpath(f).... | import time
import os
from pathlib import Path
from .hash import md5
from .buildresult import buildresult
def deep_walk(root_folder, hash=None, callback=None):
| 38 | 64 | 99 | 12 | 25 | obviousneil/datasnap | datasnap/deep_walk.py | Python | deep_walk | deep_walk | 7 | 22 | 7 | 7 | 9dab6c1381d5c5a3f142064d639811bd64834c56 | bigcode/the-stack | train |
a1e44162556d6d4d2dc73d33 | train | class | class chamfer_3DDist(nn.Module):
def __init__(self):
super(chamfer_3DDist, self).__init__()
def forward(self, input1, input2):
input1 = input1.contiguous()
input2 = input2.contiguous()
return chamfer_3DFunction.apply(input1, input2)
| class chamfer_3DDist(nn.Module):
| def __init__(self):
super(chamfer_3DDist, self).__init__()
def forward(self, input1, input2):
input1 = input1.contiguous()
input2 = input2.contiguous()
return chamfer_3DFunction.apply(input1, input2)
| .to(device)
chamfer_3D.backward(
xyz1, xyz2, gradxyz1, gradxyz2, graddist1, graddist2, idx1, idx2
)
return gradxyz1, gradxyz2
class chamfer_3DDist(nn.Module):
| 64 | 64 | 75 | 10 | 53 | ttaa9/ChamferDistancePytorch | chamfer3D/dist_chamfer_3D.py | Python | chamfer_3DDist | chamfer_3DDist | 74 | 81 | 74 | 74 | 3ab2bfb8c11dcad6dd92f4d52af9a645053496cf | bigcode/the-stack | train |
e6f07d70b457eaf9eb9ef44c | train | class | class chamfer_3DFunction(Function):
@staticmethod
def forward(ctx, xyz1, xyz2):
batchsize, n, dim = xyz1.size()
assert dim==3, "Wrong last dimension for the chamfer distance 's input! Check with .size()"
_, m, dim = xyz2.size()
assert dim==3, "Wrong last dimension for the chamfer... | class chamfer_3DFunction(Function):
@staticmethod
| def forward(ctx, xyz1, xyz2):
batchsize, n, dim = xyz1.size()
assert dim==3, "Wrong last dimension for the chamfer distance 's input! Check with .size()"
_, m, dim = xyz2.size()
assert dim==3, "Wrong last dimension for the chamfer distance 's input! Check with .size()"
device... | 3D",
sources=[
"/".join(os.path.abspath(__file__).split('/')[:-1] + ["chamfer_cuda.cpp"]),
"/".join(os.path.abspath(__file__).split('/')[:-1] + ["chamfer3D.cu"]),
], build_directory=build_path)
print("Loaded JIT 3D CUDA chamfer distance")
else:
import chamfer... | 132 | 132 | 442 | 13 | 118 | ttaa9/ChamferDistancePytorch | chamfer3D/dist_chamfer_3D.py | Python | chamfer_3DFunction | chamfer_3DFunction | 29 | 71 | 29 | 30 | e09b027b4a85bf36f4de6a86854e0903be0289cc | bigcode/the-stack | train |
59ae4ffe841abccfbdf95b9a | train | function | def _wrap_with_hooks(before, after, responder, resource):
"""Wrap responder on the given resource with "before" and "after" hooks.
Args:
before: An iterable of one or more "before" hooks
after: An iterable of one or more "after" hooks
responder: A method of a resource to wrap
re... | def _wrap_with_hooks(before, after, responder, resource):
| """Wrap responder on the given resource with "before" and "after" hooks.
Args:
before: An iterable of one or more "before" hooks
after: An iterable of one or more "after" hooks
responder: A method of a resource to wrap
resource: A reference to the resource instance providing the... | else:
assert resource is not None
@wraps(responder)
def do_before(req, resp, **kwargs):
shim(req, resp, resource, kwargs)
responder(req, resp, **kwargs)
return do_before
def _wrap_with_hooks(before, after, responder, resource):
| 64 | 64 | 164 | 13 | 50 | cdepman/falcon_api | site-packages/falcon/hooks.py | Python | _wrap_with_hooks | _wrap_with_hooks | 272 | 293 | 272 | 272 | e78064e3dc12383fb4e05166ccd06aeebc550a63 | bigcode/the-stack | train |
4f71ed941192199ceb733814 | train | function | def before(action):
"""Decorator to execute the given action function *before* the responder.
Args:
action (callable): A function of the form
``func(req, resp, resource, params)``, where `resource` is a
reference to the resource class instance associated with the
req... | def before(action):
| """Decorator to execute the given action function *before* the responder.
Args:
action (callable): A function of the form
``func(req, resp, resource, params)``, where `resource` is a
reference to the resource class instance associated with the
request, and `params` i... | 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 to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS... | 121 | 121 | 406 | 4 | 116 | cdepman/falcon_api | site-packages/falcon/hooks.py | Python | before | before | 23 | 84 | 23 | 23 | c349d9e52e3ba15cc003ee564a67b8f6aab4e3f6 | bigcode/the-stack | train |
aff17a4466c1f47b9f9116f5 | train | function | def _wrap_with_before(action, responder, resource=None, is_method=False):
"""Execute the given action function before a responder method.
Args:
action: A function with a similar signature to a resource responder
method, taking the form ``func(req, resp, resource, params)``.
responde... | def _wrap_with_before(action, responder, resource=None, is_method=False):
| """Execute the given action function before a responder method.
Args:
action: A function with a similar signature to a resource responder
method, taking the form ``func(req, resp, resource, params)``.
responder: The responder method to wrap
resource: The resource affected by... | action(req, resp)
# NOTE(swistakm): method must be decorated differently than
# normal function
if is_method:
@wraps(responder)
def do_after(self, req, resp, **kwargs):
responder(self, req, resp, **kwargs)
shim(req, resp, self)
else:
assert resource is n... | 135 | 135 | 451 | 16 | 118 | cdepman/falcon_api | site-packages/falcon/hooks.py | Python | _wrap_with_before | _wrap_with_before | 221 | 269 | 221 | 221 | 456552c89b7d1d6abb37962f36e660462efe85a0 | bigcode/the-stack | train |
a784f32c183665dc02380980 | train | function | def _wrap_with_after(action, responder, resource=None, is_method=False):
"""Execute the given action function after a responder method.
Args:
action: A function with a signature similar to a resource responder
method, taking the form ``func(req, resp, resource)``.
responder: The res... | def _wrap_with_after(action, responder, resource=None, is_method=False):
| """Execute the given action function after a responder method.
Args:
action: A function with a signature similar to a resource responder
method, taking the form ``func(req, resp, resource)``.
responder: The responder method to wrap.
resource: The resource affected by `action... | ).
spec = inspect.getargspec(func.__call__)
return spec
def _has_self(spec):
"""Checks whether the given argspec includes a self param.
Warning:
If a method's spec lists "self", that doesn't necessarily mean
that it should be called with a `self` param; if the method
inst... | 122 | 122 | 409 | 16 | 106 | cdepman/falcon_api | site-packages/falcon/hooks.py | Python | _wrap_with_after | _wrap_with_after | 172 | 218 | 172 | 172 | 6f396e76641f0a3de608cada879f71e62f9a343e | bigcode/the-stack | train |
c1e3c248203d13d628ef28dd | train | function | def _has_self(spec):
"""Checks whether the given argspec includes a self param.
Warning:
If a method's spec lists "self", that doesn't necessarily mean
that it should be called with a `self` param; if the method
instance is bound, the caller must omit `self` on invocation.
"""
... | def _has_self(spec):
| """Checks whether the given argspec includes a self param.
Warning:
If a method's spec lists "self", that doesn't necessarily mean
that it should be called with a `self` param; if the method
instance is bound, the caller must omit `self` on invocation.
"""
return len(spec.args... | for regular functions and methods, because in
# that case, __call__ isn't actually a Python function under
# Python 2.6-3.3 (fixed in 3.4).
spec = inspect.getargspec(func.__call__)
return spec
def _has_self(spec):
| 64 | 64 | 90 | 6 | 57 | cdepman/falcon_api | site-packages/falcon/hooks.py | Python | _has_self | _has_self | 159 | 169 | 159 | 159 | 97c0756a4e980ddf27411e05f48eea39147b51f9 | bigcode/the-stack | train |
56389aac08a9d6936e1f5847 | train | function | def after(action):
"""Decorator to execute the given action function *after* the responder.
Args:
action (callable): A function of the form
``func(req, resp, resource)``, where `resource` is a
reference to the resource class instance associated with the
request
... | def after(action):
| """Decorator to execute the given action function *after* the responder.
Args:
action (callable): A function of the form
``func(req, resp, resource)``, where `resource` is a
reference to the resource class instance associated with the
request
"""
def _after... | _wrap_with_before(
action, responder, resource, True)
setattr(resource, responder_name, do_before_all)
let()
return resource
else:
responder = responder_or_resource
do_before_one = _wrap_... | 74 | 74 | 248 | 4 | 69 | cdepman/falcon_api | site-packages/falcon/hooks.py | Python | after | after | 87 | 130 | 87 | 87 | 62d354d3052adbc9a2e015b4d825abb6d60c809d | bigcode/the-stack | train |
f7b2068f36cf691213d67b5d | train | function | def _get_argspec(func): # pragma: no cover
"""Wrapper around inspect.getargspec to handle Py2/Py3 differences."""
try:
# NOTE(kgriffs): This will fail for callable classes, which
# explicitly define __call__, except under Python 3.4.
spec = inspect.getargspec(func)
except TypeErro... | def _get_argspec(func): # pragma: no cover
| """Wrapper around inspect.getargspec to handle Py2/Py3 differences."""
try:
# NOTE(kgriffs): This will fail for callable classes, which
# explicitly define __call__, except under Python 3.4.
spec = inspect.getargspec(func)
except TypeError:
# NOTE(kgriffs): If this is a cla... | after
# -----------------------------------------------------------------------------
# Helpers
# -----------------------------------------------------------------------------
# NOTE(kgriffs): Coverage disabled because under Python 3.4, the exception
# is never raised. Coverage has been verified when running under o... | 64 | 64 | 181 | 14 | 50 | cdepman/falcon_api | site-packages/falcon/hooks.py | Python | _get_argspec | _get_argspec | 140 | 156 | 140 | 140 | 528fbe0de575d66e6a6a53a6b3376e7e6fd2dab2 | bigcode/the-stack | train |
1e884a2e16cfdf6dc4d121a2 | train | class | class PrintingHouse(models.Model):
class Meta:
db_table = 'Printing House'
STATUSES = (('Working', 'Working'),
('Closed', 'Closed'))
name = models.CharField(max_length=40)
address = models.CharField(max_length=40)
status = models.CharField(max_length=7, choices=STATUSES)
... | class PrintingHouse(models.Model):
| class Meta:
db_table = 'Printing House'
STATUSES = (('Working', 'Working'),
('Closed', 'Closed'))
name = models.CharField(max_length=40)
address = models.CharField(max_length=40)
status = models.CharField(max_length=7, choices=STATUSES)
def __str__(self):
retur... | PostOffice(models.Model):
class Meta:
db_table = 'Post Office'
number = models.IntegerField(default=22)
address = models.CharField(max_length=40)
def __str__(self):
return 'Post Office №' + str(self.number)
class PrintingHouse(models.Model):
| 64 | 64 | 86 | 6 | 58 | KataevaVeronika/ITMO_ICT_WebProgramming_2020 | students/k3342/laboratory_works/Kataeva_Veronika/laboratory_work_23/newspapers/newspapersapp/models.py | Python | PrintingHouse | PrintingHouse | 49 | 62 | 49 | 50 | 52cf08c191ec20624a3cf8e13f048ad5d5204081 | bigcode/the-stack | train |
9a0d9451d92a0f6e62c593f5 | train | class | class Editor(models.Model):
class Meta:
db_table = 'Editor'
first_name = models.CharField(max_length=40)
middle_name = models.CharField(max_length=40, default='John')
last_name = models.CharField(max_length=40)
def __str__(self):
full_name = self.first_name + ' ' + self.middle_na... | class Editor(models.Model):
| class Meta:
db_table = 'Editor'
first_name = models.CharField(max_length=40)
middle_name = models.CharField(max_length=40, default='John')
last_name = models.CharField(max_length=40)
def __str__(self):
full_name = self.first_name + ' ' + self.middle_name + ' ' + self.last_name
... | from django.db import models
from django.contrib.auth import get_user_model
User = get_user_model()
class Editor(models.Model):
| 26 | 64 | 90 | 5 | 21 | KataevaVeronika/ITMO_ICT_WebProgramming_2020 | students/k3342/laboratory_works/Kataeva_Veronika/laboratory_work_23/newspapers/newspapersapp/models.py | Python | Editor | Editor | 8 | 20 | 8 | 9 | bb40b69c67e53a53ba88076a1c116e822256826d | bigcode/the-stack | train |
60dd443fec86b1b4fd1573d0 | train | class | class InStock(models.Model):
class Meta:
db_table = 'In Stock'
newspaper = models.ForeignKey(Newspaper, on_delete=models.CASCADE)
post_office = models.ForeignKey(PostOffice, on_delete=models.CASCADE)
printing_house = models.ForeignKey(PrintingHouse, on_delete=models.CASCADE)
print_run = mo... | class InStock(models.Model):
| class Meta:
db_table = 'In Stock'
newspaper = models.ForeignKey(Newspaper, on_delete=models.CASCADE)
post_office = models.ForeignKey(PostOffice, on_delete=models.CASCADE)
printing_house = models.ForeignKey(PrintingHouse, on_delete=models.CASCADE)
print_run = models.IntegerField()
| '),
('Closed', 'Closed'))
name = models.CharField(max_length=40)
address = models.CharField(max_length=40)
status = models.CharField(max_length=7, choices=STATUSES)
def __str__(self):
return self.name
class InStock(models.Model):
| 64 | 64 | 72 | 6 | 57 | KataevaVeronika/ITMO_ICT_WebProgramming_2020 | students/k3342/laboratory_works/Kataeva_Veronika/laboratory_work_23/newspapers/newspapersapp/models.py | Python | InStock | InStock | 65 | 73 | 65 | 66 | 925349398f11125c545160b8136b1cd65d120035 | bigcode/the-stack | train |
645ba86ed9fefa3c4aa32f65 | train | class | class PostOffice(models.Model):
class Meta:
db_table = 'Post Office'
number = models.IntegerField(default=22)
address = models.CharField(max_length=40)
def __str__(self):
return 'Post Office №' + str(self.number)
| class PostOffice(models.Model):
| class Meta:
db_table = 'Post Office'
number = models.IntegerField(default=22)
address = models.CharField(max_length=40)
def __str__(self):
return 'Post Office №' + str(self.number)
| _table = 'Newspaper'
name = models.CharField(max_length=40)
edition_index = models.IntegerField()
editor = models.ForeignKey(Editor, on_delete=models.CASCADE)
price = models.FloatField()
def __str__(self):
return self.name
class PostOffice(models.Model):
| 64 | 64 | 59 | 6 | 57 | KataevaVeronika/ITMO_ICT_WebProgramming_2020 | students/k3342/laboratory_works/Kataeva_Veronika/laboratory_work_23/newspapers/newspapersapp/models.py | Python | PostOffice | PostOffice | 37 | 46 | 37 | 38 | 69a109510a5ca86cb4a71a018a9968e5c5adc542 | bigcode/the-stack | train |
fcc68d7fd9b45d6fdfa3ceca | train | class | class Newspaper(models.Model):
class Meta:
db_table = 'Newspaper'
name = models.CharField(max_length=40)
edition_index = models.IntegerField()
editor = models.ForeignKey(Editor, on_delete=models.CASCADE)
price = models.FloatField()
def __str__(self):
return self.name
| class Newspaper(models.Model):
| class Meta:
db_table = 'Newspaper'
name = models.CharField(max_length=40)
edition_index = models.IntegerField()
editor = models.ForeignKey(Editor, on_delete=models.CASCADE)
price = models.FloatField()
def __str__(self):
return self.name
| = models.CharField(max_length=40, default='John')
last_name = models.CharField(max_length=40)
def __str__(self):
full_name = self.first_name + ' ' + self.middle_name + ' ' + self.last_name
return full_name
class Newspaper(models.Model):
| 64 | 64 | 69 | 5 | 58 | KataevaVeronika/ITMO_ICT_WebProgramming_2020 | students/k3342/laboratory_works/Kataeva_Veronika/laboratory_work_23/newspapers/newspapersapp/models.py | Python | Newspaper | Newspaper | 23 | 34 | 23 | 24 | b425f78407295c895fe52df6f7bc6592bf5f0c31 | bigcode/the-stack | train |
a9164db00236cd0718343465 | train | class | @TestMLRunSystem.skip_test_if_env_not_configured
class TestDB(TestMLRunSystem):
project_name = "db-system-test-project"
def custom_setup(self):
self._logger.debug("Connecting to database")
self._logger.debug("Creating dummy task for db queries")
# {{run.uid}} will be substituted with... | @TestMLRunSystem.skip_test_if_env_not_configured
class TestDB(TestMLRunSystem):
| project_name = "db-system-test-project"
def custom_setup(self):
self._logger.debug("Connecting to database")
self._logger.debug("Creating dummy task for db queries")
# {{run.uid}} will be substituted with the run id, so output will be written to different directories per run
o... | import mlrun.runtimes
from mlrun import new_task, run_local
from tests.system.base import TestMLRunSystem
@TestMLRunSystem.skip_test_if_env_not_configured
class TestDB(TestMLRunSystem):
| 47 | 162 | 543 | 20 | 26 | rpatil524/mlrun | tests/system/examples/basics/test_db.py | Python | TestDB | TestDB | 6 | 74 | 6 | 8 | 5e555d9a6c330f937431fddde3fe3016774fd53b | bigcode/the-stack | train |
474da6448f76705209bb8f5f | train | function | def validate_session_persistence(pool, listener, completor):
sp = pool.get('session_persistence')
LOG.debug("validate_session_persistence called with session_persistence "
"%s", sp)
if not listener or not sp:
# safety first!
return
# L4 listeners only allow source IP persis... | def validate_session_persistence(pool, listener, completor):
| sp = pool.get('session_persistence')
LOG.debug("validate_session_persistence called with session_persistence "
"%s", sp)
if not listener or not sp:
# safety first!
return
# L4 listeners only allow source IP persistence
# (HTTPS is also considers L4 listener)
if ((li... | the License.
from neutron_lib import exceptions as n_exc
from oslo_log import log as logging
from vmware_nsx._i18n import _
from vmware_nsx.services.lbaas import lb_const
LOG = logging.getLogger(__name__)
def validate_session_persistence(pool, listener, completor):
| 64 | 64 | 211 | 12 | 52 | yebinama/vmware-nsx | vmware_nsx/services/lbaas/lb_common.py | Python | validate_session_persistence | validate_session_persistence | 24 | 42 | 24 | 24 | a454d93e1d119a6baedba4f2f9754b79b1930754 | bigcode/the-stack | train |
2f0756e85b20f6cc99ecfd79 | train | function | def session_persistence_type_changed(pool, old_pool):
cookie_pers_types = (lb_const.LB_SESSION_PERSISTENCE_HTTP_COOKIE,
lb_const.LB_SESSION_PERSISTENCE_APP_COOKIE)
sp = pool.get('session_persistence')
if not sp:
return False
if old_pool:
oldsp = old_pool.get('ses... | def session_persistence_type_changed(pool, old_pool):
| cookie_pers_types = (lb_const.LB_SESSION_PERSISTENCE_HTTP_COOKIE,
lb_const.LB_SESSION_PERSISTENCE_APP_COOKIE)
sp = pool.get('session_persistence')
if not sp:
return False
if old_pool:
oldsp = old_pool.get('session_persistence')
if not oldsp:
r... | )s with %(proto)s protocol") %
{'sp_type': sp['type'],
'lst_id': listener['id'],
'proto': listener['protocol']})
raise n_exc.BadRequest(resource='lbaas-pool', msg=msg)
def session_persistence_type_changed(pool, old_pool):
| 64 | 64 | 160 | 11 | 53 | yebinama/vmware-nsx | vmware_nsx/services/lbaas/lb_common.py | Python | session_persistence_type_changed | session_persistence_type_changed | 45 | 60 | 45 | 45 | 29a9356cf10bf72aba65697c46f6c63655151a9f | bigcode/the-stack | train |
a887c9b2814f78eb841a663b | train | function | def get_listener_cert_ref(listener):
return listener.get('default_tls_container_id',
listener.get('default_tls_container_ref'))
| def get_listener_cert_ref(listener):
| return listener.get('default_tls_container_id',
listener.get('default_tls_container_ref'))
| _SOURCE_IP and
oldsp['type'] in cookie_pers_types) or
(sp['type'] in cookie_pers_types and
oldsp['type'] == lb_const.LB_SESSION_PERSISTENCE_SOURCE_IP)):
return True
return False
def get_listener_cert_ref(listener):
| 64 | 64 | 26 | 7 | 56 | yebinama/vmware-nsx | vmware_nsx/services/lbaas/lb_common.py | Python | get_listener_cert_ref | get_listener_cert_ref | 63 | 65 | 63 | 63 | 7328c93c7258299fff8bf756ae89459e72c45ef3 | bigcode/the-stack | train |
8b38194916cdf2071b5f3212 | train | class | class TestPlayerService(unittest.TestCase):
def setUp(self):
self.svc = PlayerService()
def test_get_player_not_found(self):
data = self.svc.get_player(1234)
self.assertIsNone(data)
def test_create_player(self):
player_id = self.svc.create_player("Joe", "password")
... | class TestPlayerService(unittest.TestCase):
| def setUp(self):
self.svc = PlayerService()
def test_get_player_not_found(self):
data = self.svc.get_player(1234)
self.assertIsNone(data)
def test_create_player(self):
player_id = self.svc.create_player("Joe", "password")
player = self.svc.get_player(player_id)
... | import unittest
from hearts.services.player import PlayerService, PlayerStateError
class TestPlayerService(unittest.TestCase):
| 23 | 147 | 490 | 8 | 14 | MHeasell/hearts-server | tests/test_player_service.py | Python | TestPlayerService | TestPlayerService | 6 | 80 | 6 | 7 | 48d19d4e46cbf994b2b23ee2294f040e41dbe2c9 | bigcode/the-stack | train |
395216ce075981786678262c | train | function | def move_all_files_to_inbox() -> None:
# create inbox directory
inbox_directory = current_directory / "inbox"
filesystem.create_directory(inbox_directory)
paths_to_skip = [
inbox_directory,
current_directory / "templates",
current_directory / "images",
current_directory ... | def move_all_files_to_inbox() -> None:
# create inbox directory
| inbox_directory = current_directory / "inbox"
filesystem.create_directory(inbox_directory)
paths_to_skip = [
inbox_directory,
current_directory / "templates",
current_directory / "images",
current_directory / "websites",
current_directory / "log.txt",
]
# mo... | import os
import logging
from pathlib import Path
from . import logger
from . import filesystem
from . import note
from . import constants
current_directory = filesystem.get_current_directory()
logger = logging.getLogger(__name__)
def move_all_files_to_inbox() -> None:
# create inbox directory
| 64 | 64 | 181 | 17 | 47 | eveningtree/markdemic | markdemic/markdemic.py | Python | move_all_files_to_inbox | move_all_files_to_inbox | 15 | 42 | 15 | 16 | ee5d55c8035099f83f2d1745dbbd77fea4dad84e | bigcode/the-stack | train |
243a35941e960706f37047aa | train | function | def create_sorted_directories() -> None:
"""
went with a flat structure
c <category>
t <tag>
"""
source_of_truth_directory_path = current_directory / "source_of_truth"
# bad variable name parent_tag_directory_path
tag_directories_parent_path = current_directory
# bad variable name pa... | def create_sorted_directories() -> None:
| """
went with a flat structure
c <category>
t <tag>
"""
source_of_truth_directory_path = current_directory / "source_of_truth"
# bad variable name parent_tag_directory_path
tag_directories_parent_path = current_directory
# bad variable name parent_category_directory_path
category... | )
if file_is_fit:
# move to sourceoftruth_directory_path
note.move_note(
note_path=file_path,
destination_directory=sourceoftruth_directory_path / file_path.name,
replace=False,
)
else:
# move to unfit_files... | 101 | 101 | 339 | 9 | 92 | eveningtree/markdemic | markdemic/markdemic.py | Python | create_sorted_directories | create_sorted_directories | 179 | 216 | 179 | 179 | a5a24e2725c39e94f88405b751fa3445aa98f581 | bigcode/the-stack | train |
954a78058ccdd811e57b7d25 | train | function | def str_to_datetime(str_datetime, format) -> datetime:
return datetime.strptime(str_datetime, format)
| def str_to_datetime(str_datetime, format) -> datetime:
| return datetime.strptime(str_datetime, format)
| def clean_and_update_file_metadata() -> None:
inbox_path = current_directory
for file in current_directory.rglob("*.md"):
# update metadata entries: guid(if missing), md5
note.update_metadata_and_file(file_path=file)
def str_to_datetime(str_datetime, format) -> datetime:
| 64 | 64 | 21 | 12 | 52 | eveningtree/markdemic | markdemic/markdemic.py | Python | str_to_datetime | str_to_datetime | 52 | 53 | 52 | 52 | 732912115477039b6db89f380d5e37c1198ae8db | bigcode/the-stack | train |
ba4b13b72974b613f9619a28 | train | function | def clean_and_update_file_metadata() -> None:
inbox_path = current_directory
for file in current_directory.rglob("*.md"):
# update metadata entries: guid(if missing), md5
note.update_metadata_and_file(file_path=file)
| def clean_and_update_file_metadata() -> None:
| inbox_path = current_directory
for file in current_directory.rglob("*.md"):
# update metadata entries: guid(if missing), md5
note.update_metadata_and_file(file_path=file)
| _skip:
if node.is_file():
filesystem.move_file(
source=node,
destination_directory=inbox_directory / node.name,
replace=False,
)
else:
filesystem.move_directory(
from_d... | 64 | 64 | 52 | 10 | 54 | eveningtree/markdemic | markdemic/markdemic.py | Python | clean_and_update_file_metadata | clean_and_update_file_metadata | 45 | 49 | 45 | 45 | 4b96827e9493795c9dc0973f22713509d79285fc | bigcode/the-stack | train |
38ebf16fc4b4379f7d79be61 | train | function | def generate_sourceoftruth() -> None:
inbox_path = current_directory / "inbox"
old_files_directory_path = current_directory / "old_notes"
filesystem.create_directory(path=old_files_directory_path)
# First generate sourceoftruth_dictionary in memory
# Then use sourceoftruth_dictionary to generate so... | def generate_sourceoftruth() -> None:
| inbox_path = current_directory / "inbox"
old_files_directory_path = current_directory / "old_notes"
filesystem.create_directory(path=old_files_directory_path)
# First generate sourceoftruth_dictionary in memory
# Then use sourceoftruth_dictionary to generate sourceoftruth directory on disk
# [... | () -> None:
# create inbox directory
inbox_directory = current_directory / "inbox"
filesystem.create_directory(inbox_directory)
paths_to_skip = [
inbox_directory,
current_directory / "templates",
current_directory / "images",
current_directory / "websites",
curre... | 256 | 256 | 1,037 | 9 | 247 | eveningtree/markdemic | markdemic/markdemic.py | Python | generate_sourceoftruth | generate_sourceoftruth | 56 | 176 | 56 | 56 | cedd8f534b2ff674282a172378e7b5867a92acb9 | bigcode/the-stack | train |
f8a51f2f0100d72674ef56e3 | train | function | def remove_empty_directories() -> None:
# remove all the empty directories in inbox
inbox_path = current_directory / "inbox"
for dirpath, _, _ in os.walk(inbox_path, topdown=False): # Listing the files
if dirpath == inbox_path:
pass
try:
os.rmdir(dirpath)
exc... | def remove_empty_directories() -> None:
# remove all the empty directories in inbox
| inbox_path = current_directory / "inbox"
for dirpath, _, _ in os.walk(inbox_path, topdown=False): # Listing the files
if dirpath == inbox_path:
pass
try:
os.rmdir(dirpath)
except OSError as ex:
pass
| bulletproof
# metadata didn't specify tags, so keep file in the "untagged" directory
note.copy_note_to_directory(
note_path=file, target_directory_path=untagged_directory
)
def remove_empty_directories() -> None:
# remove all the empty directories in inbox
| 64 | 64 | 85 | 19 | 45 | eveningtree/markdemic | markdemic/markdemic.py | Python | remove_empty_directories | remove_empty_directories | 219 | 228 | 219 | 220 | c2f0a1291565e1dfa075b4fcae2aaa5f2dd8969c | bigcode/the-stack | train |
f0d9850372bb4b1b1ebc7060 | train | function | def clean_outdated_notes():
old_files_directory_path = current_directory / "old_notes"
filesystem.delete_directory(
directory_path=old_files_directory_path, delete_children=True
)
| def clean_outdated_notes():
| old_files_directory_path = current_directory / "old_notes"
filesystem.delete_directory(
directory_path=old_files_directory_path, delete_children=True
)
| inbox"
for dirpath, _, _ in os.walk(inbox_path, topdown=False): # Listing the files
if dirpath == inbox_path:
pass
try:
os.rmdir(dirpath)
except OSError as ex:
pass
def clean_outdated_notes():
| 64 | 64 | 39 | 6 | 57 | eveningtree/markdemic | markdemic/markdemic.py | Python | clean_outdated_notes | clean_outdated_notes | 231 | 235 | 231 | 231 | aafce7c784cd8f60613b8752a416278f3ee8e5a2 | bigcode/the-stack | train |
ef227548e490daa80ba33a4d | train | function | def process() -> None:
# Prepare and terraform the directory
logger.info("[Step 1/6]cleaning and updating file metadata")
clean_and_update_file_metadata()
logger.info("[Step 2/6]moving all files to inbox")
move_all_files_to_inbox()
# Generate sorted notes
logger.info("[Step 3/6]generating s... | def process() -> None:
# Prepare and terraform the directory
| logger.info("[Step 1/6]cleaning and updating file metadata")
clean_and_update_file_metadata()
logger.info("[Step 2/6]moving all files to inbox")
move_all_files_to_inbox()
# Generate sorted notes
logger.info("[Step 3/6]generating source of truth")
generate_sourceoftruth()
logger.info("[S... | )
except OSError as ex:
pass
def clean_outdated_notes():
old_files_directory_path = current_directory / "old_notes"
filesystem.delete_directory(
directory_path=old_files_directory_path, delete_children=True
)
def process() -> None:
# Prepare and terraform the directory
| 64 | 64 | 160 | 14 | 50 | eveningtree/markdemic | markdemic/markdemic.py | Python | process | process | 238 | 255 | 238 | 239 | 6a6778cad78ad1ab6715701d13620bd18d4110dc | bigcode/the-stack | train |
c5fd99eb42e8f1f38cca2b6a | train | function | def pylons_globals():
"""Create and return a dictionary of global Pylons variables
Render functions should call this to retrieve a list of global
Pylons variables that should be included in the global template
namespace if possible.
Pylons variables that are returned in the dictionary:
``c... | def pylons_globals():
| """Create and return a dictionary of global Pylons variables
Render functions should call this to retrieve a list of global
Pylons variables that should be included in the global template
namespace if possible.
Pylons variables that are returned in the dictionary:
``c``, ``h``, ``_``, ``N_... | ons.templating` comes with. The render_*
functions look for the template loader to render the template.
"""
import logging
from webhelpers.html import literal
import pylons
__all__ = ['render_genshi', 'render_jinja2', 'render_mako']
PYLONS_VARS = ['c', 'app_globals', 'config', 'h', 'render', 'request',
... | 114 | 114 | 380 | 5 | 109 | KinSai1975/Menira.py | pylons/templating.py | Python | pylons_globals | pylons_globals | 118 | 158 | 118 | 118 | 5b01f1844994d377a6118cd8394073f1d0efa210 | bigcode/the-stack | train |
b7e5a58d175569f7a4ea22fd | train | function | def render_jinja2(template_name, extra_vars=None, cache_key=None,
cache_type=None, cache_expire=None):
"""Render a template with Jinja2
Accepts the cache options ``cache_key``, ``cache_type``, and
``cache_expire``.
"""
# Create a render callable for the cache function
def rend... | def render_jinja2(template_name, extra_vars=None, cache_key=None,
cache_type=None, cache_expire=None):
| """Render a template with Jinja2
Accepts the cache options ``cache_key``, ``cache_type``, and
``cache_expire``.
"""
# Create a render callable for the cache function
def render_template():
# Pull in extra vars if needed
globs = extra_vars or {}
# Second, get the global... | _template(template_name, render_template, cache_key=cache_key,
cache_type=cache_type, cache_expire=cache_expire,
ns_options=('method'), method=method)
def render_jinja2(template_name, extra_vars=None, cache_key=None,
cache_type=None, cache_expire=No... | 64 | 64 | 179 | 26 | 38 | KinSai1975/Menira.py | pylons/templating.py | Python | render_jinja2 | render_jinja2 | 311 | 334 | 311 | 312 | ca0fd06c13a6850f5cb2cd361b22505bbbce508a | bigcode/the-stack | train |
369224f76379fbd665281f90 | train | function | def render_mako(template_name, extra_vars=None, cache_key=None,
cache_type=None, cache_expire=None):
"""Render a template with Mako
Accepts the cache options ``cache_key``, ``cache_type``, and
``cache_expire``.
"""
# Create a render callable for the cache function
def render_te... | def render_mako(template_name, extra_vars=None, cache_key=None,
cache_type=None, cache_expire=None):
| """Render a template with Mako
Accepts the cache options ``cache_key``, ``cache_type``, and
``cache_expire``.
"""
# Create a render callable for the cache function
def render_template():
# Pull in extra vars if needed
globs = extra_vars or {}
# Second, get the globals
... | =cache_type)
content = cache.get_value(cache_key, createfunc=render_func,
expiretime=cache_expire)
return content
else:
return render_func()
def render_mako(template_name, extra_vars=None, cache_key=None,
cache_type=None, cache_expire=None):
| 64 | 64 | 175 | 25 | 39 | KinSai1975/Menira.py | pylons/templating.py | Python | render_mako | render_mako | 222 | 244 | 222 | 223 | 7e4e4354a1fae72b292e4a1953d3f8c029bfd9b8 | bigcode/the-stack | train |
fdf0bf2e2623a2f92866ce87 | train | function | def cached_template(template_name, render_func, ns_options=(),
cache_key=None, cache_type=None, cache_expire=None,
**kwargs):
"""Cache and render a template
Cache a template to the namespace ``template_name``, along with a
specific key if provided.
Basic Options... | def cached_template(template_name, render_func, ns_options=(),
cache_key=None, cache_type=None, cache_expire=None,
**kwargs):
| """Cache and render a template
Cache a template to the namespace ``template_name``, along with a
specific key if provided.
Basic Options
``template_name``
Name of the template, which is used as the template namespace.
``render_func``
Function used to generate the template shou... | .i18n.N_
)
# If the session was overriden to be None, don't populate the session
# var
econf = pylons.config['pylons.environ_config']
if 'beaker.session' in pylons.request.environ or \
('session' in econf and econf['session'] in pylons.request.environ):
pylons_vars['session'] = pylo... | 146 | 146 | 488 | 31 | 114 | KinSai1975/Menira.py | pylons/templating.py | Python | cached_template | cached_template | 161 | 219 | 161 | 163 | 36472eae8c602ff12fe9ffde2d162a764a1b1d4f | bigcode/the-stack | train |
929d0967431693d0e7d94188 | train | function | def render_genshi(template_name, extra_vars=None, cache_key=None,
cache_type=None, cache_expire=None, method='xhtml'):
"""Render a template with Genshi
Accepts the cache options ``cache_key``, ``cache_type``, and
``cache_expire`` in addition to method which are passed to Genshi's
rend... | def render_genshi(template_name, extra_vars=None, cache_key=None,
cache_type=None, cache_expire=None, method='xhtml'):
| """Render a template with Genshi
Accepts the cache options ``cache_key``, ``cache_type``, and
``cache_expire`` in addition to method which are passed to Genshi's
render function.
"""
# Create a render callable for the cache function
def render_template():
# Pull in extra vars if ne... | globs))
return cached_template(template_name, render_template, cache_key=cache_key,
cache_type=cache_type, cache_expire=cache_expire)
def render_genshi(template_name, extra_vars=None, cache_key=None,
cache_type=None, cache_expire=None, method='xhtml'):
| 64 | 64 | 213 | 30 | 34 | KinSai1975/Menira.py | pylons/templating.py | Python | render_genshi | render_genshi | 283 | 308 | 283 | 284 | f39208e9fc48494380fd7228cb3b2c38d9f921d4 | bigcode/the-stack | train |
9ea1d5162b7d82e38a2e69b0 | train | function | def render_mako_def(template_name, def_name, cache_key=None,
cache_type=None, cache_expire=None, **kwargs):
"""Render a def block within a Mako template
Takes the template name, and the name of the def within it to call.
If the def takes arguments, they should be passed in as keyword
... | def render_mako_def(template_name, def_name, cache_key=None,
cache_type=None, cache_expire=None, **kwargs):
| """Render a def block within a Mako template
Takes the template name, and the name of the def within it to call.
If the def takes arguments, they should be passed in as keyword
arguments.
Example::
# To call the def 'header' within the 'layout.mako' template
# with a title argumen... | app_globals'].mako_lookup.get_template(template_name)
return literal(template.render_unicode(**globs))
return cached_template(template_name, render_template, cache_key=cache_key,
cache_type=cache_type, cache_expire=cache_expire)
def render_mako_def(template_name, def_name, cache... | 80 | 80 | 267 | 28 | 52 | KinSai1975/Menira.py | pylons/templating.py | Python | render_mako_def | render_mako_def | 247 | 280 | 247 | 248 | 2f32aa5097a32841a0001531d2983373eba9a1f9 | bigcode/the-stack | train |
a34316c0dac66441371a7a3e | train | function | def test_stereo_effect():
fx = StereoEffect()
assert fx.input.channel_count == 2
assert fx.input.channel_count_mode == "explicit"
| def test_stereo_effect():
| fx = StereoEffect()
assert fx.input.channel_count == 2
assert fx.input.channel_count_mode == "explicit"
| Tremolo,
Vibrato,
)
from ipytone.effect import Effect, StereoEffect
def test_effect():
fx = Effect()
assert isinstance(fx.input, Gain)
assert isinstance(fx.output, CrossFade)
assert fx.wet is fx.output.fade
def test_stereo_effect():
| 64 | 64 | 33 | 6 | 57 | benbovy/ipytone | ipytone/tests/test_effect.py | Python | test_stereo_effect | test_stereo_effect | 25 | 29 | 25 | 25 | 9e48c450d6177455cb9df945daa44c644cdb5e58 | bigcode/the-stack | train |
b54b05f364a1929be5fdb63d | train | function | def test_effect():
fx = Effect()
assert isinstance(fx.input, Gain)
assert isinstance(fx.output, CrossFade)
assert fx.wet is fx.output.fade
| def test_effect():
| fx = Effect()
assert isinstance(fx.input, Gain)
assert isinstance(fx.output, CrossFade)
assert fx.wet is fx.output.fade
| pytest
from traitlets import TraitError
from ipytone import (
CrossFade,
Distortion,
FeedbackDelay,
Gain,
PingPongDelay,
Reverb,
Tremolo,
Vibrato,
)
from ipytone.effect import Effect, StereoEffect
def test_effect():
| 64 | 64 | 38 | 4 | 59 | benbovy/ipytone | ipytone/tests/test_effect.py | Python | test_effect | test_effect | 17 | 22 | 17 | 17 | 3da78884a7dce19d569a37886ba7e9c5063756cd | bigcode/the-stack | train |
4dcec0e5bfb00ab56459c2fd | train | function | def test_distortion():
dist = Distortion()
assert dist.distortion == 0.4
assert dist.oversample == "none"
for value in [-1.2, 1.2]:
with pytest.raises(TraitError, match="Distortion value must be in range.*"):
dist.distortion = value
# just test enum values
dist.oversample ... | def test_distortion():
| dist = Distortion()
assert dist.distortion == 0.4
assert dist.oversample == "none"
for value in [-1.2, 1.2]:
with pytest.raises(TraitError, match="Distortion value must be in range.*"):
dist.distortion = value
# just test enum values
dist.oversample = "2x"
dist.oversam... | (fx.input, Gain)
assert isinstance(fx.output, CrossFade)
assert fx.wet is fx.output.fade
def test_stereo_effect():
fx = StereoEffect()
assert fx.input.channel_count == 2
assert fx.input.channel_count_mode == "explicit"
def test_distortion():
| 64 | 64 | 99 | 5 | 59 | benbovy/ipytone | ipytone/tests/test_effect.py | Python | test_distortion | test_distortion | 32 | 44 | 32 | 32 | 4c7a94a143cd41e7eb792b5deeb6727c98b510a5 | bigcode/the-stack | train |
15ed5e53a9dbd1aee6b9818f | train | function | def test_tremolo(mocker):
tre = Tremolo()
mocker.patch.object(tre, "send")
assert tre.type == "sine"
assert tre.frequency.value == 10
assert tre.frequency.units == "frequency"
assert tre.depth.value == 0.5
assert tre.depth.units == "normalRange"
assert tre.spread == 180
e = tre.sta... | def test_tremolo(mocker):
| tre = Tremolo()
mocker.patch.object(tre, "send")
assert tre.type == "sine"
assert tre.frequency.value == 10
assert tre.frequency.units == "frequency"
assert tre.depth.value == 0.5
assert tre.depth.units == "normalRange"
assert tre.spread == 180
e = tre.start()
tre.send.assert_c... | == 1.5
assert rv.pre_delay == 0.01
with pytest.raises(TraitError, match="Decay must be greater than 0.001 seconds"):
rv.decay = 0
with pytest.raises(TraitError, match="Pre-delay value must be positive"):
rv.pre_delay = -1
def test_tremolo(mocker):
| 79 | 79 | 265 | 8 | 70 | benbovy/ipytone | ipytone/tests/test_effect.py | Python | test_tremolo | test_tremolo | 88 | 127 | 88 | 88 | f4658c3ec8236c1d989e0d0e018961e58b609bf6 | bigcode/the-stack | train |
65d176cd06bcbd378119b217 | train | function | def test_vibrato():
vib = Vibrato()
assert vib.type == "sine"
assert vib.frequency.value == 5
assert vib.frequency.units == "frequency"
assert vib.depth.value == 0.1
assert vib.depth.units == "normalRange"
with pytest.raises(TraitError, match="Invalid oscillator type"):
vib.type = ... | def test_vibrato():
| vib = Vibrato()
assert vib.type == "sine"
assert vib.frequency.value == 5
assert vib.frequency.units == "frequency"
assert vib.depth.value == 0.1
assert vib.depth.units == "normalRange"
with pytest.raises(TraitError, match="Invalid oscillator type"):
vib.type = "not a good oscillat... | is tre
with pytest.raises(TraitError, match="Invalid oscillator type"):
tre.type = "not a good oscillator wave"
e = tre.dispose()
assert e is tre
assert tre.frequency.disposed is True
assert tre.depth.disposed is True
def test_vibrato():
| 64 | 64 | 115 | 6 | 57 | benbovy/ipytone | ipytone/tests/test_effect.py | Python | test_vibrato | test_vibrato | 130 | 145 | 130 | 130 | ad002eac5c421ab129624a65bf35d695b010d494 | bigcode/the-stack | train |
9d9216f7e221583e786724db | train | function | def test_reverb():
rv = Reverb()
assert rv.decay == 1.5
assert rv.pre_delay == 0.01
with pytest.raises(TraitError, match="Decay must be greater than 0.001 seconds"):
rv.decay = 0
with pytest.raises(TraitError, match="Pre-delay value must be positive"):
rv.pre_delay = -1
| def test_reverb():
| rv = Reverb()
assert rv.decay == 1.5
assert rv.pre_delay == 0.01
with pytest.raises(TraitError, match="Decay must be greater than 0.001 seconds"):
rv.decay = 0
with pytest.raises(TraitError, match="Pre-delay value must be positive"):
rv.pre_delay = -1
| "
assert dly.feedback.value == 0.125
assert dly.feedback.units == "normalRange"
e = dly.dispose()
assert e is dly
assert dly.delay_time.disposed is True
assert dly.feedback.disposed is True
def test_reverb():
| 64 | 64 | 87 | 5 | 58 | benbovy/ipytone | ipytone/tests/test_effect.py | Python | test_reverb | test_reverb | 75 | 85 | 75 | 75 | e4c4c5498badc68955291091166efd71200143f6 | bigcode/the-stack | train |
476d351e9f46ce2e7624d2fc | train | function | def test_pingpong_delay():
dly = PingPongDelay()
assert dly.delay_time.value == 0.25
assert dly.delay_time.units == "time"
assert dly.feedback.value == 0.125
assert dly.feedback.units == "normalRange"
e = dly.dispose()
assert e is dly
assert dly.delay_time.disposed is True
assert d... | def test_pingpong_delay():
| dly = PingPongDelay()
assert dly.delay_time.value == 0.25
assert dly.delay_time.units == "time"
assert dly.feedback.value == 0.125
assert dly.feedback.units == "normalRange"
e = dly.dispose()
assert e is dly
assert dly.delay_time.disposed is True
assert dly.feedback.disposed is Tru... | assert dly.feedback.value == 0.125
assert dly.feedback.units == "normalRange"
e = dly.dispose()
assert e is dly
assert dly.delay_time.disposed is True
assert dly.feedback.disposed is True
def test_pingpong_delay():
| 64 | 64 | 97 | 6 | 57 | benbovy/ipytone | ipytone/tests/test_effect.py | Python | test_pingpong_delay | test_pingpong_delay | 61 | 72 | 61 | 61 | 2250883eca4845f993584498970123d3c6abe560 | bigcode/the-stack | train |
4dbf0177af158ea7ca9cfb1b | train | function | def test_feedback_delay():
dly = FeedbackDelay()
assert dly.delay_time.value == 0.25
assert dly.delay_time.units == "time"
assert dly.feedback.value == 0.125
assert dly.feedback.units == "normalRange"
e = dly.dispose()
assert e is dly
assert dly.delay_time.disposed is True
assert d... | def test_feedback_delay():
| dly = FeedbackDelay()
assert dly.delay_time.value == 0.25
assert dly.delay_time.units == "time"
assert dly.feedback.value == 0.125
assert dly.feedback.units == "normalRange"
e = dly.dispose()
assert e is dly
assert dly.delay_time.disposed is True
assert dly.feedback.disposed is Tru... | , 1.2]:
with pytest.raises(TraitError, match="Distortion value must be in range.*"):
dist.distortion = value
# just test enum values
dist.oversample = "2x"
dist.oversample = "4x"
def test_feedback_delay():
| 64 | 64 | 94 | 5 | 59 | benbovy/ipytone | ipytone/tests/test_effect.py | Python | test_feedback_delay | test_feedback_delay | 47 | 58 | 47 | 47 | abaa95863f56ce4f1f0269f07f085a88f361d2f9 | bigcode/the-stack | train |
8f7e3fe8e2ef391d17031f06 | train | class | class Figure(Artist):
"""
The Figure instance supports callbacks through a *callbacks*
attribute which is a :class:`matplotlib.cbook.CallbackRegistry`
instance. The events you can connect to are 'dpi_changed', and
the callback will be called with ``func(fig)`` where fig is the
:class:`Figure` ... | class Figure(Artist):
| """
The Figure instance supports callbacks through a *callbacks*
attribute which is a :class:`matplotlib.cbook.CallbackRegistry`
instance. The events you can connect to are 'dpi_changed', and
the callback will be called with ``func(fig)`` where fig is the
:class:`Figure` instance.
*patch*
... | )
thiswspace = getattr(self, 'wspace', None)
thishspace = getattr(self, 'hspace', None)
self._update_this('left', left)
self._update_this('right', right)
self._update_this('bottom', bottom)
self._update_this('top', top)
self._update_this('wspace', wspace)
... | 256 | 256 | 10,021 | 5 | 251 | lthurlow/Network-Grapher | proj/external/matplotlib-1.2.1/lib/matplotlib/figure.py | Python | Figure | Figure | 233 | 1,545 | 233 | 234 | 1f2840b5e4429ae28d690186b7a3f6889a2bfeb2 | bigcode/the-stack | train |
2abc9357ce2bb1873ca5882f | train | function | def figaspect(arg):
"""
Create a figure with specified aspect ratio. If *arg* is a number,
use that aspect ratio. If *arg* is an array, figaspect will
determine the width and height for a figure that would fit array
preserving aspect ratio. The figure width, height in inches are
returned. Be... | def figaspect(arg):
| """
Create a figure with specified aspect ratio. If *arg* is a number,
use that aspect ratio. If *arg* is an array, figaspect will
determine the width and height for a figure that would fit array
preserving aspect ratio. The figure width, height in inches are
returned. Be sure to create an a... | whole subplots area (including
labels) will fit into. Default is (0, 0, 1, 1).
"""
from tight_layout import (get_renderer, get_tight_layout_figure,
get_subplotspec_list)
subplotspec_list = get_subplotspec_list(self.axes)
if None in subplot... | 173 | 173 | 578 | 5 | 168 | lthurlow/Network-Grapher | proj/external/matplotlib-1.2.1/lib/matplotlib/figure.py | Python | figaspect | figaspect | 1,548 | 1,608 | 1,548 | 1,548 | 0f30dd079283f91ab1e409ca9d79be2f112d14fc | bigcode/the-stack | train |
a67b26de3f8070d8bba4f821 | train | class | class SubplotParams:
"""
A class to hold the parameters for a subplot
"""
def __init__(self, left=None, bottom=None, right=None, top=None,
wspace=None, hspace=None):
"""
All dimensions are fraction of the figure width or height.
All values default to their rc par... | class SubplotParams:
| """
A class to hold the parameters for a subplot
"""
def __init__(self, left=None, bottom=None, right=None, top=None,
wspace=None, hspace=None):
"""
All dimensions are fraction of the figure width or height.
All values default to their rc params
The foll... | being replaced" % key)
# I don't think the above should ever happen.
if a in self:
return None
self._ind += 1
return Stack.push(self, (key, (self._ind, a)))
def current_key_axes(self):
"""
Return a tuple of ``(key, axes)`` for the active axes.
... | 178 | 178 | 595 | 5 | 173 | lthurlow/Network-Grapher | proj/external/matplotlib-1.2.1/lib/matplotlib/figure.py | Python | SubplotParams | SubplotParams | 149 | 230 | 149 | 149 | f576a0f54e4c2181803821fc2347567464b209e2 | bigcode/the-stack | train |
e57b3bf9b5252d11590ce724 | train | class | class AxesStack(Stack):
"""
Specialization of the Stack to handle all tracking of Axes in a Figure.
This stack stores ``key, (ind, axes)`` pairs, where:
* **key** should be a hash of the args and kwargs
used in generating the Axes.
* **ind** is a serial number for tracking the ord... | class AxesStack(Stack):
| """
Specialization of the Stack to handle all tracking of Axes in a Figure.
This stack stores ``key, (ind, axes)`` pairs, where:
* **key** should be a hash of the args and kwargs
used in generating the Axes.
* **ind** is a serial number for tracking the order
in which ax... | elements
"""
from __future__ import print_function
import warnings
from operator import itemgetter
import numpy as np
from matplotlib import rcParams
from matplotlib import docstring
from matplotlib import __version__ as _mpl_version
import matplotlib.artist as martist
from matplotlib.artist import Artist, allow_... | 226 | 226 | 756 | 6 | 220 | lthurlow/Network-Grapher | proj/external/matplotlib-1.2.1/lib/matplotlib/figure.py | Python | AxesStack | AxesStack | 49 | 146 | 49 | 49 | 55629c3b36713a0bcc0f57a4e9d506fc71e0a7b1 | bigcode/the-stack | train |
af39208a393d003fb1f4cce3 | train | function | def construct_filter(query, items, conjunction='and'):
""" Construct a filter from a combination of filter items
Args:
query (sqlalchemy.orm.query.Query): The SQLAlchemy SQL ORM object
items (list[str]): List of query expressions in form of
"[KEY][OPERATOR][VALUE...]"
conjun... | def construct_filter(query, items, conjunction='and'):
| """ Construct a filter from a combination of filter items
Args:
query (sqlalchemy.orm.query.Query): The SQLAlchemy SQL ORM object
items (list[str]): List of query expressions in form of
"[KEY][OPERATOR][VALUE...]"
conjunction (str): Combine the filter items using 'and' or 'o... | column `key`
Args:
column (sqlalchemy.orm.attributes.QueryableAttribute): A SQLAlchemy
ORM attribute
value (str): A value to convert
Returns:
type: `value`, converted to a different type
"""
if isinstance(column.type, DATETIME_TYPES):
return arrow.get(value... | 170 | 170 | 567 | 11 | 158 | ceholden/landsat_tiles | tilezilla/db/_queries.py | Python | construct_filter | construct_filter | 129 | 196 | 129 | 129 | b9ab5d46bade33f1680ffa4ce05ec7b5e641129e | bigcode/the-stack | train |
5d7d6b0df515c5e992a47190 | train | function | def _parse_expression_filter(expr):
""" Convert a filter expression into [KEY], [OPERATOR], [VALUE...]
Args:
str: A filter expression
Returns:
tuple (str, str, str): The key, operator, and value or values
Raises:
KeyError: Raise if operator not in available comparators
... | def _parse_expression_filter(expr):
| """ Convert a filter expression into [KEY], [OPERATOR], [VALUE...]
Args:
str: A filter expression
Returns:
tuple (str, str, str): The key, operator, and value or values
Raises:
KeyError: Raise if operator not in available comparators
(:attr:`COMPARATORS`)
"""
... | '],
' gt ': ['>'],
' ge ': ['>=', '=>']
}
for op, matches in six.iteritems(TO_CONVERT):
for match in matches:
if match in expr:
return expr.replace(match, op)
return expr
def _parse_expression_filter(expr):
| 64 | 64 | 153 | 7 | 56 | ceholden/landsat_tiles | tilezilla/db/_queries.py | Python | _parse_expression_filter | _parse_expression_filter | 71 | 89 | 71 | 71 | db6a58041751163253c8b64fcff8e53e56cd2743 | bigcode/the-stack | train |
60948a7d58b32b8636587187 | train | function | def convert_query_type(column, value):
""" Return `value` converted to type expected by `table` for column `key`
Args:
column (sqlalchemy.orm.attributes.QueryableAttribute): A SQLAlchemy
ORM attribute
value (str): A value to convert
Returns:
type: `value`, converted to ... | def convert_query_type(column, value):
| """ Return `value` converted to type expected by `table` for column `key`
Args:
column (sqlalchemy.orm.attributes.QueryableAttribute): A SQLAlchemy
ORM attribute
value (str): A value to convert
Returns:
type: `value`, converted to a different type
"""
if isinsta... | , tablename):
""" Return class of tablename
"""
for c in base._decl_class_registry.values():
if hasattr(c, '__tablename__') and c.__tablename__ == tablename:
return c
# [VALUE]
# TYPE CAST SYSTEM
def convert_query_type(column, value):
| 64 | 64 | 169 | 8 | 55 | ceholden/landsat_tiles | tilezilla/db/_queries.py | Python | convert_query_type | convert_query_type | 102 | 124 | 102 | 102 | b97c68bc56292f0e40b61abaca725accdda0dd7f | bigcode/the-stack | train |
695d8291073ab21699527afe | train | function | def _link_path(graph, start, end, path=[]):
path = path + [start]
if start == end:
return path
if start not in graph:
return None
for node in graph[start]:
if node not in path:
newpath = _link_path(graph, node, end, path)
if newpath: return newpath
ret... | def _link_path(graph, start, end, path=[]):
| path = path + [start]
if start == end:
return path
if start not in graph:
return None
for node in graph[start]:
if node not in path:
newpath = _link_path(graph, node, end, path)
if newpath: return newpath
return None
| ages as graph ---------------------------------------------------
def _make_table_graph(tables):
graph = {}
for t in tables:
relations = sa.inspect(t).relationships
graph[t] = [relation.mapper.class_ for relation in relations]
return graph
def _link_path(graph, start, end, path=[]):
| 64 | 64 | 84 | 13 | 50 | ceholden/landsat_tiles | tilezilla/db/_queries.py | Python | _link_path | _link_path | 32 | 42 | 32 | 32 | 7a2278dcc47d1839f955238ebc7fd1d1d13b8f3c | bigcode/the-stack | train |
de785bcbeaf10282879cb9b0 | train | function | def _tablename_to_class(base, tablename):
""" Return class of tablename
"""
for c in base._decl_class_registry.values():
if hasattr(c, '__tablename__') and c.__tablename__ == tablename:
return c
| def _tablename_to_class(base, tablename):
| """ Return class of tablename
"""
for c in base._decl_class_registry.values():
if hasattr(c, '__tablename__') and c.__tablename__ == tablename:
return c
| .split('\s(?i)%s\s' % comp, expr)
if len(split) == 2:
return split[0].strip(), comp, split[1].lstrip()
raise KeyError('Could not find a supported comparator in expression')
def _tablename_to_class(base, tablename):
| 64 | 64 | 53 | 10 | 54 | ceholden/landsat_tiles | tilezilla/db/_queries.py | Python | _tablename_to_class | _tablename_to_class | 92 | 97 | 92 | 92 | 33c80e3bbf8d89755717e77500729dc20e11b876 | bigcode/the-stack | train |
3e7fb7b3c756561aaf2d0c76 | train | function | def _convert_expression_operator(expr):
""" Convert expression operators from '=' style to 'eq' style
Args:
expr (str): Expression to convert
Returns:
str: Converted expression
"""
TO_CONVERT = {
' eq ': ['=', '=='],
' ne ': ['!=', '=!'],
' lt ': ['<'],
... | def _convert_expression_operator(expr):
| """ Convert expression operators from '=' style to 'eq' style
Args:
expr (str): Expression to convert
Returns:
str: Converted expression
"""
TO_CONVERT = {
' eq ': ['=', '=='],
' ne ': ['!=', '=!'],
' lt ': ['<'],
' le ': ['<=', '=<'],
' gt ': ... | not in path:
newpath = _link_path(graph, node, end, path)
if newpath: return newpath
return None
TABLES_GRAPH = _make_table_graph(TABLES.values())
# [KEY]
# 1. PARSE SYSTEM --------------------------------------------------------------
def _convert_expression_operator(expr):
| 64 | 64 | 142 | 7 | 57 | ceholden/landsat_tiles | tilezilla/db/_queries.py | Python | _convert_expression_operator | _convert_expression_operator | 49 | 68 | 49 | 49 | d75be9facf1519abc6e7defa3f633bd0ed179110 | bigcode/the-stack | train |
b3c98fa2294e3af5387e35e0 | train | function | def _make_table_graph(tables):
graph = {}
for t in tables:
relations = sa.inspect(t).relationships
graph[t] = [relation.mapper.class_ for relation in relations]
return graph
| def _make_table_graph(tables):
| graph = {}
for t in tables:
relations = sa.inspect(t).relationships
graph[t] = [relation.mapper.class_ for relation in relations]
return graph
| sa.sql.sqltypes.DateTime,
sa.sql.sqltypes.Date,
sau.ArrowType)
COMPARATORS = ['eq', 'ne', 'le', 'lt', 'ge', 'gt', 'in', 'like']
# Database linkages as graph ---------------------------------------------------
def _make_table_graph(tables):
| 64 | 64 | 46 | 8 | 56 | ceholden/landsat_tiles | tilezilla/db/_queries.py | Python | _make_table_graph | _make_table_graph | 24 | 29 | 24 | 24 | 084919188661eba887e03b6bac26f83076fa44ca | bigcode/the-stack | train |
1c6368e26ffd51a269a2154b | train | function | def sigmoid(z):
"""The sigmoid function."""
#return 1.0/(1.0+np.exp(-z))
return np.maximum(z,0)
| def sigmoid(z):
| """The sigmoid function."""
#return 1.0/(1.0+np.exp(-z))
return np.maximum(z,0)
| h position
and zeroes elsewhere. This is used to convert a digit (0...9)
into a corresponding desired output from the neural network.
"""
e = np.zeros((10, 1))
e[j] = 1.0
return e
def sigmoid(z):
| 64 | 64 | 35 | 4 | 59 | jeonggunlee/neuralNetwork | Tut-6/network2.py | Python | sigmoid | sigmoid | 326 | 329 | 326 | 326 | 581718dea3bd59d2a0cc848344cc52284fda6952 | bigcode/the-stack | train |
ee3bf9ec7599cfb94b216e85 | train | function | def load(filename):
"""Load a neural network from the file ``filename``. Returns an
instance of Network.
"""
f = open(filename, "r")
data = json.load(f)
f.close()
cost = getattr(sys.modules[__name__], data["cost"])
net = Network(data["sizes"], cost=cost)
net.weights = [np.array(w) ... | def load(filename):
| """Load a neural network from the file ``filename``. Returns an
instance of Network.
"""
f = open(filename, "r")
data = json.load(f)
f.close()
cost = getattr(sys.modules[__name__], data["cost"])
net = Network(data["sizes"], cost=cost)
net.weights = [np.array(w) for w in data["weigh... | .tolist() for w in self.weights],
"biases": [b.tolist() for b in self.biases],
"cost": str(self.cost.__name__)}
f = open(filename, "w")
json.dump(data, f)
f.close()
#### Loading a Network
def load(filename):
| 64 | 64 | 115 | 4 | 59 | jeonggunlee/neuralNetwork | Tut-6/network2.py | Python | load | load | 301 | 313 | 301 | 301 | c62db97bba803c96de0334d7fb8f098d055172fe | bigcode/the-stack | train |
09904eefe19dbe7f6a3982ec | train | class | class QuadraticCost(object):
@staticmethod
def fn(a, y):
"""Return the cost associated with an output ``a`` and desired output
``y``.
"""
return 0.5*np.linalg.norm(a-y)**2
@staticmethod
def delta(z, a, y):
"""Return the error delta from the output layer."""
... | class QuadraticCost(object):
@staticmethod
| def fn(a, y):
"""Return the cost associated with an output ``a`` and desired output
``y``.
"""
return 0.5*np.linalg.norm(a-y)**2
@staticmethod
def delta(z, a, y):
"""Return the error delta from the output layer."""
return (a-y) * sigmoid_prime(z)
| ifiable. It is not optimized, and omits many desirable
features.
"""
#### Libraries
# Standard library
import json
import random
import sys
# Third-party libraries
import numpy as np
#### Define the quadratic and cross-entropy cost functions
class QuadraticCost(object):
@staticmethod
| 64 | 64 | 88 | 10 | 53 | jeonggunlee/neuralNetwork | Tut-6/network2.py | Python | QuadraticCost | QuadraticCost | 26 | 39 | 26 | 28 | a486a121a419d88a1be320860e3e431486832a40 | bigcode/the-stack | train |
8b784f58e85c221727cbe35e | train | function | def vectorized_result(j):
"""Return a 10-dimensional unit vector with a 1.0 in the j'th position
and zeroes elsewhere. This is used to convert a digit (0...9)
into a corresponding desired output from the neural network.
"""
e = np.zeros((10, 1))
e[j] = 1.0
return e
| def vectorized_result(j):
| """Return a 10-dimensional unit vector with a 1.0 in the j'th position
and zeroes elsewhere. This is used to convert a digit (0...9)
into a corresponding desired output from the neural network.
"""
e = np.zeros((10, 1))
e[j] = 1.0
return e
| "])
net = Network(data["sizes"], cost=cost)
net.weights = [np.array(w) for w in data["weights"]]
net.biases = [np.array(b) for b in data["biases"]]
return net
#### Miscellaneous functions
def vectorized_result(j):
| 64 | 64 | 85 | 6 | 57 | jeonggunlee/neuralNetwork | Tut-6/network2.py | Python | vectorized_result | vectorized_result | 316 | 324 | 316 | 316 | 9fc6a481d6abee6a70c7ec1ed4fd0c9eb4bba9e8 | bigcode/the-stack | train |
8f2bbe1b955f990f5f65a9ef | train | class | class Network(object):
def __init__(self, sizes, cost=CrossEntropyCost):
"""The list ``sizes`` contains the number of neurons in the respective
layers of the network. For example, if the list was [2, 3, 1]
then it would be a three-layer network, with the first layer
containing 2 ne... | class Network(object):
| def __init__(self, sizes, cost=CrossEntropyCost):
"""The list ``sizes`` contains the number of neurons in the respective
layers of the network. For example, if the list was [2, 3, 1]
then it would be a three-layer network, with the first layer
containing 2 neurons, the second layer ... | , y):
"""Return the error delta from the output layer."""
return (a-y) * sigmoid_prime(z)
class CrossEntropyCost(object):
@staticmethod
def fn(a, y):
"""Return the cost associated with an output ``a`` and desired output
``y``. Note that np.nan_to_num is used to ensure numeric... | 256 | 256 | 2,532 | 4 | 251 | jeonggunlee/neuralNetwork | Tut-6/network2.py | Python | Network | Network | 68 | 298 | 68 | 69 | 763515e8d18a97bf7cf8474f53b5513c089eea3e | bigcode/the-stack | train |
56e154c2c11b1a1e0c065784 | train | class | class CrossEntropyCost(object):
@staticmethod
def fn(a, y):
"""Return the cost associated with an output ``a`` and desired output
``y``. Note that np.nan_to_num is used to ensure numerical
stability. In particular, if both ``a`` and ``y`` have a 1.0
in the same slot, then the ... | class CrossEntropyCost(object):
@staticmethod
| def fn(a, y):
"""Return the cost associated with an output ``a`` and desired output
``y``. Note that np.nan_to_num is used to ensure numerical
stability. In particular, if both ``a`` and ``y`` have a 1.0
in the same slot, then the expression (1-y)*np.log(1-a)
returns nan. ... |
``y``.
"""
return 0.5*np.linalg.norm(a-y)**2
@staticmethod
def delta(z, a, y):
"""Return the error delta from the output layer."""
return (a-y) * sigmoid_prime(z)
class CrossEntropyCost(object):
@staticmethod
| 66 | 66 | 222 | 10 | 56 | jeonggunlee/neuralNetwork | Tut-6/network2.py | Python | CrossEntropyCost | CrossEntropyCost | 42 | 64 | 42 | 44 | cee0c52d645c86394ed3e5f27efc505e620a9d9c | bigcode/the-stack | train |
08eec0314f1a9dad5ad968ec | train | function | def sigmoid_prime(z):
"""Derivative of the sigmoid function."""
#return sigmoid(z)*(1-sigmoid(z))
return 1. * (z > 0)
| def sigmoid_prime(z):
| """Derivative of the sigmoid function."""
#return sigmoid(z)*(1-sigmoid(z))
return 1. * (z > 0)
| e = np.zeros((10, 1))
e[j] = 1.0
return e
def sigmoid(z):
"""The sigmoid function."""
#return 1.0/(1.0+np.exp(-z))
return np.maximum(z,0)
def sigmoid_prime(z):
| 64 | 64 | 37 | 5 | 59 | jeonggunlee/neuralNetwork | Tut-6/network2.py | Python | sigmoid_prime | sigmoid_prime | 331 | 334 | 331 | 331 | e8825f0f06b3d1eb09613ffaf5f5e6df67e4e532 | bigcode/the-stack | train |
ba7377d3b7267721c4accaf0 | train | class | class MDPVehicle(ControlledVehicle):
"""A controlled vehicle with a specified discrete range of allowed target speeds."""
SPEED_COUNT: int = 3 # []
SPEED_MIN: float = 20 # [m/s]
SPEED_MAX: float = 30 # [m/s]
def __init__(self,
road: Road,
position: List[float]... | class MDPVehicle(ControlledVehicle):
| """A controlled vehicle with a specified discrete range of allowed target speeds."""
SPEED_COUNT: int = 3 # []
SPEED_MIN: float = 20 # [m/s]
SPEED_MAX: float = 30 # [m/s]
def __init__(self,
road: Road,
position: List[float],
heading: float = 0,... | _to: int) -> None:
"""
Set the road to be followed at the next intersection.
Erase current planned route.
:param _to: index of the road to follow at next intersection, in the road network
"""
routes = self.get_routes_at_intersection()
if routes:
if... | 229 | 230 | 769 | 8 | 221 | t6-thu/highway-env | highway_env/vehicle/controller.py | Python | MDPVehicle | MDPVehicle | 200 | 286 | 200 | 201 | 516a189456fdef0a25555b4945f245c89f3b171e | bigcode/the-stack | train |
abacd99f19b733e47c2b2330 | train | class | class ControlledVehicle(Vehicle):
"""
A vehicle piloted by two low-level controller, allowing high-level actions such as cruise control and lane changes.
- The longitudinal controller is a speed controller;
- The lateral controller is a heading controller cascaded with a lateral position controller.
... | class ControlledVehicle(Vehicle):
| """
A vehicle piloted by two low-level controller, allowing high-level actions such as cruise control and lane changes.
- The longitudinal controller is a speed controller;
- The lateral controller is a heading controller cascaded with a lateral position controller.
"""
target_speed: float
... | from typing import List, Tuple, Union
import numpy as np
import copy
from highway_env import utils
from highway_env.road.road import Road, LaneIndex, Route
from highway_env.types import Vector
from highway_env.vehicle.kinematics import Vehicle
class ControlledVehicle(Vehicle):
| 62 | 256 | 1,822 | 6 | 55 | t6-thu/highway-env | highway_env/vehicle/controller.py | Python | ControlledVehicle | ControlledVehicle | 11 | 197 | 11 | 11 | dc352306dc0f3f7c8ee9c22a93348ded9e26a127 | bigcode/the-stack | train |
e044f557072d183064d50020 | train | class | class RLModule(Module):
def __init__(self):
super().__init__()
self.name = "lambda_group_privesc"
self.description = ("Elevate privilege by using iam:PassRole, "
"lambda:CreateFunction, and "
"lambda:InvokeFunction. "
... | class RLModule(Module):
| def __init__(self):
super().__init__()
self.name = "lambda_group_privesc"
self.description = ("Elevate privilege by using iam:PassRole, "
"lambda:CreateFunction, and "
"lambda:InvokeFunction. "
"(and lambda:D... | import shlex
import boto3
from rebelykos.core.response import Response as res
from rebelykos.core.teamserver.module import Module
class RLModule(Module):
| 35 | 112 | 375 | 5 | 29 | Takahiro-Yoko/rebelykos | rebelykos/core/teamserver/modules/lambda_group_privesc.py | Python | RLModule | RLModule | 9 | 60 | 9 | 9 | d2baa45846555fc7a13d25da3ded644272a51f9b | bigcode/the-stack | train |
66e8ece9a11ca255a5a066cf | train | class | class YiBanGao(BaseType):
"""
一般高
"""
def __init__(self):
super(YiBanGao, self).__init__()
def is_this_type(self, hand_card, card_analyse):
j, s, k = card_analyse.get_jiang_ke_shun(hand_card.hand_card_vals)
if hand_card.chi_card_vals:
for chi_group in hand_card.c... | class YiBanGao(BaseType):
| """
一般高
"""
def __init__(self):
super(YiBanGao, self).__init__()
def is_this_type(self, hand_card, card_analyse):
j, s, k = card_analyse.get_jiang_ke_shun(hand_card.hand_card_vals)
if hand_card.chi_card_vals:
for chi_group in hand_card.chi_card_vals:
... | # coding=utf-8
from service.mahjong.models.hutype.basetype import BaseType
from service.mahjong.constants.carddefine import CardType
class YiBanGao(BaseType):
| 41 | 64 | 140 | 8 | 32 | obespoir/echecs | echecs_espoir/service/mahjong/models/hutype/one/yibangao.py | Python | YiBanGao | YiBanGao | 6 | 27 | 6 | 6 | 885cf5ba24ec1fefa8d88bc034d1ef1de5317f17 | bigcode/the-stack | train |
bb61234e42afed2a61ace9f0 | train | function | def uint32_to_uint8(img):
"""Cast a uint32 RGBA image to a 4-channel uint8 image array."""
return img.view(dtype=np.uint8).reshape(img.shape + (4,))
| def uint32_to_uint8(img):
| """Cast a uint32 RGBA image to a 4-channel uint8 image array."""
return img.view(dtype=np.uint8).reshape(img.shape + (4,))
| import xarray as xr
from datashader import reductions
from datashader import transfer_functions as tf
from datashader.core import bypixel, Canvas
from datashader.pipeline import Pipeline
__all__ = ["DSArtist", "dsshow"]
def uint32_to_uint8(img):
| 63 | 64 | 43 | 8 | 55 | biprateep/DESI | spectrograph/mpl_ext.py | Python | uint32_to_uint8 | uint32_to_uint8 | 19 | 21 | 19 | 19 | 12d3e00e7bef915240305bb4dcc32912bbbcc9b4 | bigcode/the-stack | train |
5de5ceda4fc2a9cece6791ca | train | function | def dsshow(
df,
glyph,
agg=reductions.count(),
transform_fn=None,
color_fn=tf.shade,
spread_fn=None,
width_scale=1.0,
height_scale=1.0,
ax=None,
fignum=None,
aspect=None,
**kwargs
):
"""
Display the output of a datashading pipeline applied to a dataframe.
The... | def dsshow(
df,
glyph,
agg=reductions.count(),
transform_fn=None,
color_fn=tf.shade,
spread_fn=None,
width_scale=1.0,
height_scale=1.0,
ax=None,
fignum=None,
aspect=None,
**kwargs
):
| """
Display the output of a datashading pipeline applied to a dataframe.
The plot will respond to changes in the bounding box being displayed (in
data coordinates), such as pan/zoom events. Both quantitative and
categorical datashading pipelines are supported.
Parameters
----------
df ... | None* if the
event is outside the bounds of the current view.
"""
xmin, xmax, ymin, ymax = self.get_extent()
if self.origin == "upper":
ymin, ymax = ymax, ymin
arr = self.get_ds_data().data
data_extent = Bbox([[ymin, xmin], [ymax, xmax]])
array_extent... | 256 | 256 | 1,190 | 70 | 186 | biprateep/DESI | spectrograph/mpl_ext.py | Python | dsshow | dsshow | 255 | 391 | 255 | 268 | 132abef6ae41bff4ab48c4cf87a000eae3fe9268 | bigcode/the-stack | train |
ec9c3d5660f9f5b91b6273bc | train | class | class DSArtist(_ImageBase):
"""
Matplotlib artist for a datashading pipeline.
Unlike the AxesImage artist, by default the ``origin`` for this artist
is "lower" and interpolation is disabled.
Parameters
----------
ax : :class:`matplotlib.axes.Axes`
The axes the raster image will bel... | class DSArtist(_ImageBase):
| """
Matplotlib artist for a datashading pipeline.
Unlike the AxesImage artist, by default the ``origin`` for this artist
is "lower" and interpolation is disabled.
Parameters
----------
ax : :class:`matplotlib.axes.Axes`
The axes the raster image will belong to.
pipeline : :clas... | import warnings
from matplotlib.image import _ImageBase
from matplotlib.patches import Patch
from matplotlib.transforms import Bbox, TransformedBbox, BboxTransform
from toolz import identity
import matplotlib as mpl
import numpy as np
import xarray as xr
from datashader import reductions
from datashader import transf... | 156 | 256 | 1,902 | 7 | 150 | biprateep/DESI | spectrograph/mpl_ext.py | Python | DSArtist | DSArtist | 24 | 252 | 24 | 24 | f982b475551c47cb6dbb3535eb51f05a20e2a08c | bigcode/the-stack | train |
65bb64a8597c5f39aa524de0 | train | class | class LogHandler(object):
def __init__(self, stream_name):
self.boto_config = Config(
retries = {
'max_attempts': 10
}
)
self.stream_name = stream_name.upper()
self.log_group = os.getenv('SOLUTION_LOGGROUP', 'SO0111-SHARR')
self._log_... | class LogHandler(object):
| def __init__(self, stream_name):
self.boto_config = Config(
retries = {
'max_attempts': 10
}
)
self.stream_name = stream_name.upper()
self.log_group = os.getenv('SOLUTION_LOGGROUP', 'SO0111-SHARR')
self._log_client = boto3.client('logs... | . A copy of the License #
# is located at #
# #
# http://www.apache.org/licenses/ #
# ... | 236 | 236 | 789 | 5 | 230 | chandinipenmetsa/aws-security-hub-automated-response-and-remediation | source/playbooks/python_lib/applogger.py | Python | LogHandler | LogHandler | 40 | 129 | 40 | 41 | 79edc10bd4ff7af55fa298666a5237b768e52572 | bigcode/the-stack | train |
9b981c901b292b748578c2ea | train | function | def save_model(model):
if not os.path.exists('Data/Model/'):
os.makedirs('Data/Model/')
model_json = model.to_json()
with open("Data/Model/model.json", "w") as model_file:
model_file.write(model_json)
# serialize weights to HDF5
model.save_weights("Data/Model/weights.h5")
print('... | def save_model(model):
| if not os.path.exists('Data/Model/'):
os.makedirs('Data/Model/')
model_json = model.to_json()
with open("Data/Model/model.json", "w") as model_file:
model_file.write(model_json)
# serialize weights to HDF5
model.save_weights("Data/Model/weights.h5")
print('Model and weights saved... | # Arda Mavi
import os
from keras.models import Model
from keras.optimizers import Adadelta
from keras.layers import Input, Conv2D, Activation, MaxPooling2D, Flatten, Dense, Dropout
def save_model(model):
| 53 | 64 | 90 | 5 | 47 | brunodpoliveira/Game-Bot | get_model.py | Python | save_model | save_model | 8 | 17 | 8 | 8 | d36a4112af52113de8e1ef8407c8ceba43902cdd | bigcode/the-stack | train |
60af4e82d84bc2032a5a3d96 | train | function | def get_model():
inputs = Input(shape=(150, 150, 3))
conv_1 = Conv2D(32, (3, 3), strides=(1, 1))(inputs)
act_1 = Activation('relu')(conv_1)
conv_2 = Conv2D(64, (3, 3), strides=(1, 1))(act_1)
act_2 = Activation('relu')(conv_2)
conv_3 = Conv2D(64, (3, 3), strides=(1, 1))(act_2)
act_3 = Acti... | def get_model():
| inputs = Input(shape=(150, 150, 3))
conv_1 = Conv2D(32, (3, 3), strides=(1, 1))(inputs)
act_1 = Activation('relu')(conv_1)
conv_2 = Conv2D(64, (3, 3), strides=(1, 1))(act_1)
act_2 = Activation('relu')(conv_2)
conv_3 = Conv2D(64, (3, 3), strides=(1, 1))(act_2)
act_3 = Activation('relu')(co... | Flatten, Dense, Dropout
def save_model(model):
if not os.path.exists('Data/Model/'):
os.makedirs('Data/Model/')
model_json = model.to_json()
with open("Data/Model/model.json", "w") as model_file:
model_file.write(model_json)
# serialize weights to HDF5
model.save_weights("Data/Mod... | 101 | 101 | 337 | 4 | 96 | brunodpoliveira/Game-Bot | get_model.py | Python | get_model | get_model | 20 | 52 | 20 | 20 | fa2348ee6fc6e675f48fe00490f36d683c227840 | bigcode/the-stack | train |
caaa7f998c11beac57c0eea6 | train | class | class TestTypes(unittest.TestCase):
def test_check_types_not_enough_types_provided(self):
self.assertRaises(
ParseThisException, _check_types, "function", {}, ["i_dont_have_a_type"], ()
)
def test_check_types_too_many_types_provided(self):
self.assertRaises(
Pars... | class TestTypes(unittest.TestCase):
| def test_check_types_not_enough_types_provided(self):
self.assertRaises(
ParseThisException, _check_types, "function", {}, ["i_dont_have_a_type"], ()
)
def test_check_types_too_many_types_provided(self):
self.assertRaises(
ParseThisException,
_check_t... | import unittest
from parse_this.exception import ParseThisException
from parse_this.types import _check_types
class TestTypes(unittest.TestCase):
| 28 | 132 | 441 | 7 | 20 | bertrandvidal/parse_this | test/types_test.py | Python | TestTypes | TestTypes | 7 | 72 | 7 | 7 | 5a007061ddb29b37b4f59c2f3e448042bcd2225e | bigcode/the-stack | train |
de7f9bea5c4b6541216e2fc4 | train | class | class OAuth2ClientCredentialsSession(requests.Session):
"""
Wrapper around `requests.Session <https://docs.python-requests.org/en/latest/api/#requests.Session>`_
which receives authentication tokens through the ``client_credentials`` type of OAuth2 grant,
and adds tokens to the requests made through the... | class OAuth2ClientCredentialsSession(requests.Session):
| """
Wrapper around `requests.Session <https://docs.python-requests.org/en/latest/api/#requests.Session>`_
which receives authentication tokens through the ``client_credentials`` type of OAuth2 grant,
and adds tokens to the requests made through the session.
It also attempts to keep track of the toke... | # -*- coding: utf-8 -*-
# (c) Copyright IBM Corp. 2010, 2021. All Rights Reserved.
import time
import logging
import requests
log = logging.getLogger(__name__)
class OAuth2ClientCredentialsSession(requests.Session):
| 55 | 256 | 1,807 | 10 | 45 | COLDTURNIP/resilient-python-api | resilient-lib/resilient_lib/components/oauth2_client_credentials_session.py | Python | OAuth2ClientCredentialsSession | OAuth2ClientCredentialsSession | 10 | 219 | 10 | 10 | 73394435125d2a9128565eb8fa3eae411d801f23 | bigcode/the-stack | train |
91debc83d1017c70ed4dacf8 | train | class | class ParallelDataset(data.Dataset):
""" Define a N-parallel dataset: supports abitriry numbers of input streams"""
@staticmethod
def sort_key(ex):
return data.interleave_keys(len(ex.src), len(ex.trg))
def __init__(self, path, exts, fields, max_len=None, **kwargs):
assert len(exts) == ... | class ParallelDataset(data.Dataset):
| """ Define a N-parallel dataset: supports abitriry numbers of input streams"""
@staticmethod
def sort_key(ex):
return data.interleave_keys(len(ex.src), len(ex.trg))
def __init__(self, path, exts, fields, max_len=None, **kwargs):
assert len(exts) == len(fields), 'N parallel dataset must... | os.path.join(path, train), exts, fields, **kwargs)
val_data = None if validation is None else cls(
os.path.join(path, validation), exts, fields, **kwargs)
test_data = None if test is None else cls(
os.path.join(path, test), exts, fields, **kwargs)
return tuple... | 102 | 102 | 341 | 6 | 96 | middlekisser/GMNMT | data/data.py | Python | ParallelDataset | ParallelDataset | 163 | 196 | 163 | 163 | 20ce571af470234053f5e9fd396fc16d4ed446a4 | bigcode/the-stack | train |
d18ce0f1203349528a4788ac | train | class | class TranslationDataset(data.Dataset):
"""Defines a dataset for machine translation."""
@staticmethod
def sort_key(ex):
return data.interleave_keys(len(ex.src), len(ex.trg))
def __init__(self, path, exts, fields, **kwargs):
"""Create a TranslationDataset given paths and fields.
... | class TranslationDataset(data.Dataset):
| """Defines a dataset for machine translation."""
@staticmethod
def sort_key(ex):
return data.interleave_keys(len(ex.src), len(ex.trg))
def __init__(self, path, exts, fields, **kwargs):
"""Create a TranslationDataset given paths and fields.
Arguments:
path: Common pr... | return x.strip()
def process(self, x, device=None):
batch_imgs = []
batch_alighs = []
region_num = []
for i in x:
i = i.split()
img = i[0]
align = i[1:]
align = list(map(lambda item: list(map(int, item.split('-'))), align))
... | 174 | 174 | 581 | 6 | 167 | middlekisser/GMNMT | data/data.py | Python | TranslationDataset | TranslationDataset | 105 | 160 | 105 | 105 | 71f7d5828ac25d44e29515f89ba006fd9a140bee | bigcode/the-stack | train |
0e8546dc3950274236c6e7c9 | train | class | class GraphField(data.Field):
def preprocess(self, x):
return x.strip()
def process(self, x, device=None):
batch_imgs = []
batch_alighs = []
region_num = []
for i in x:
i = i.split()
img = i[0]
align = i[1:]
align = list(ma... | class GraphField(data.Field):
| def preprocess(self, x):
return x.strip()
def process(self, x, device=None):
batch_imgs = []
batch_alighs = []
region_num = []
for i in x:
i = i.split()
img = i[0]
align = i[1:]
align = list(map(lambda item: list(map(int, i... | (filter(filter_special, ex)).replace("@@ ", "") for ex in batch]
else:
batch = [" ".join(filter(filter_special, ex)) for ex in batch]
if returen_token:
batch = [ex.split() for ex in batch]
return batch
class GraphField(data.Field):
| 64 | 64 | 182 | 6 | 57 | middlekisser/GMNMT | data/data.py | Python | GraphField | GraphField | 80 | 102 | 80 | 80 | ff7aa1e6f5fbf5d471a2c3ca55fc10924a02413c | bigcode/the-stack | train |
70037e1cfb8c6e4e9945b894 | train | class | class NormalField(data.Field):
def build_vocab(self, *args, **kwargs):
"""Construct the Vocab object for this field from one or more datasets.
Arguments:
Positional arguments: Dataset objects or other iterable data
sources from which to construct the Vocab object that
... | class NormalField(data.Field):
| def build_vocab(self, *args, **kwargs):
"""Construct the Vocab object for this field from one or more datasets.
Arguments:
Positional arguments: Dataset objects or other iterable data
sources from which to construct the Vocab object that
represents the se... | import math
# import ipdb
from collections import OrderedDict, Counter
from itertools import chain
import torch
import os
from torchtext import data, datasets
from torchtext.data import Example
from contextlib import ExitStack
# load the dataset + reversible tokenization
class NormalField(data.Field):
| 64 | 147 | 493 | 6 | 57 | middlekisser/GMNMT | data/data.py | Python | NormalField | NormalField | 15 | 77 | 15 | 16 | 661c5e65cab4262a51a336d02681c16395c5d4ba | bigcode/the-stack | train |
3408f6fdc18aae4d2912a2bc | train | class | class SearchComputers(komand.Action):
def __init__(self):
super(self.__class__, self).__init__(
name='search_computers',
description=Component.DESCRIPTION,
input=SearchComputersInput(),
output=SearchComputersOutput())
def run(self, params... | class SearchComputers(komand.Action):
| def __init__(self):
super(self.__class__, self).__init__(
name='search_computers',
description=Component.DESCRIPTION,
input=SearchComputersInput(),
output=SearchComputersOutput())
def run(self, params={}):
'''
Searches for ... | import komand
from .schema import SearchComputersInput, SearchComputersOutput, Input, Output, Component
# Custom imports below
import json
from komand.exceptions import PluginException
from icon_trendmicro_deepsecurity.util.shared import tryJSON
from icon_trendmicro_deepsecurity.util.shared import checkResponse
class ... | 75 | 177 | 591 | 9 | 65 | killstrelok/insightconnect-plugins | trendmicro_deepsecurity/icon_trendmicro_deepsecurity/actions/search_computers/action.py | Python | SearchComputers | SearchComputers | 11 | 85 | 11 | 12 | e8b51db01c41341c6314bd636e7d911997a9ff1a | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.