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
da02201eba8a87048a44a94b
train
function
def makeBLASTdb(fastafile, databasename, dbtype, parse_seqids=False): #dbtype can be 'nucl' or 'prot' """takes fastafile filepath, databasename filepath and dbtype args""" import subprocess if parse_seqids==False: cmdArgs=['makeblastdb', '-dbtype', dbtype, '-in', fastafile, '-out', databasename] ...
def makeBLASTdb(fastafile, databasename, dbtype, parse_seqids=False): #dbtype can be 'nucl' or 'prot'
"""takes fastafile filepath, databasename filepath and dbtype args""" import subprocess if parse_seqids==False: cmdArgs=['makeblastdb', '-dbtype', dbtype, '-in', fastafile, '-out', databasename] else: cmdArgs=['makeblastdb', '-dbtype', dbtype, '-in', fastafile, '-out', databasename, '-pa...
interrupt is more drastic than sys.exit - only use for subscript subprocess errors which wouldn't otherwise trigger driverscript abort else: return stdout def makeBLASTdb(fastafile, databasename, dbtype, parse_seqids=False): #dbtype can be 'nucl' or 'prot'
64
64
132
34
29
AlexOrlek/metamorth
pythonmods.py
Python
makeBLASTdb
makeBLASTdb
116
123
116
116
d218e89f14782efcbedc4c56e73d49017fa0a1c0
bigcode/the-stack
train
afbac31f9380f3091b5561b1
train
class
class BootModeObject(CommonPropertiesObject, HelpTextListObject): def __init__(self): self.SupportedBootModes = '' CommonPropertiesObject.__init__(self) HelpTextListObject.__init__(self) def SetSupportedBootModes(self, SupportedBootModes): self.SupportedBootModes = SupportedBoot...
class BootModeObject(CommonPropertiesObject, HelpTextListObject):
def __init__(self): self.SupportedBootModes = '' CommonPropertiesObject.__init__(self) HelpTextListObject.__init__(self) def SetSupportedBootModes(self, SupportedBootModes): self.SupportedBootModes = SupportedBootModes def GetSupportedBootModes(self): return self.Su...
Object.POM.CommonObject import CommonHeaderObject from Object.POM.CommonObject import BinaryHeaderObject from Object.POM.CommonObject import HelpTextListObject from Object.POM.CommonObject import GuidVersionObject ## # BootModeObject # class BootModeObject(CommonPropertiesObject, HelpTextListObject):
64
64
86
13
51
KaoTuz/edk2-stable202108
BaseTools/Source/Python/UPT/Object/POM/ModuleObject.py
Python
BootModeObject
BootModeObject
26
36
26
26
30dc9a7fcd747c50bd745b185ba3c9fad9313585
bigcode/the-stack
train
5ff684e53b3a06f7cbf354af
train
class
class ExternObject(CommonPropertiesObject): def __init__(self): self.EntryPoint = '' self.UnloadImage = '' self.Constructor = '' self.Destructor = '' self.SupModList = [] CommonPropertiesObject.__init__(self) def SetEntryPoint(self, EntryPoint): self.Entr...
class ExternObject(CommonPropertiesObject):
def __init__(self): self.EntryPoint = '' self.UnloadImage = '' self.Constructor = '' self.Destructor = '' self.SupModList = [] CommonPropertiesObject.__init__(self) def SetEntryPoint(self, EntryPoint): self.EntryPoint = EntryPoint def GetEntryPoint(s...
return self.Family def SetAsBuiltOptionFlags(self, AsBuiltOptionFlags): self.AsBuiltOptionFlags = AsBuiltOptionFlags def GetAsBuiltOptionFlags(self): return self.AsBuiltOptionFlags ## # ExternObject # class ExternObject(CommonPropertiesObject):
64
64
216
8
56
KaoTuz/edk2-stable202108
BaseTools/Source/Python/UPT/Object/POM/ModuleObject.py
Python
ExternObject
ExternObject
383
419
383
383
790242e12e60622ceeeb43d6c4d832f89974fbdf
bigcode/the-stack
train
0ce4eb033710a3d9003a731c
train
class
class SpecObject(object): def __init__(self): self.Spec = '' self.Version = '' def SetSpec(self, Spec): self.Spec = Spec def GetSpec(self): return self.Spec def SetVersion(self, Version): self.Version = Version def GetVersion(self): return self.Ver...
class SpecObject(object):
def __init__(self): self.Spec = '' self.Version = '' def SetSpec(self, Spec): self.Spec = Spec def GetSpec(self): return self.Spec def SetVersion(self, Version): self.Version = Version def GetVersion(self): return self.Version
CommonPropertiesObject.__init__(self) HelpTextListObject.__init__(self) def SetHobType(self, HobType): self.HobType = HobType def GetHobType(self): return self.HobType ## # SpecObject # class SpecObject(object):
64
64
72
5
59
KaoTuz/edk2-stable202108
BaseTools/Source/Python/UPT/Object/POM/ModuleObject.py
Python
SpecObject
SpecObject
71
86
71
71
2ed267202b69e3c2d0bf85d45c64b238ed25732d
bigcode/the-stack
train
6ae671e03975d1fd5b11df59
train
class
class DepexObject(CommonPropertiesObject): def __init__(self): self.Depex = '' self.ModuelType = '' CommonPropertiesObject.__init__(self) def SetDepex(self, Depex): self.Depex = Depex def GetDepex(self): return self.Depex def SetModuleType(self, ModuleType): ...
class DepexObject(CommonPropertiesObject):
def __init__(self): self.Depex = '' self.ModuelType = '' CommonPropertiesObject.__init__(self) def SetDepex(self, Depex): self.Depex = Depex def GetDepex(self): return self.Depex def SetModuleType(self, ModuleType): self.ModuelType = ModuleType def...
GetDestructor(self): return self.Destructor def SetSupModList(self, SupModList): self.SupModList = SupModList def GetSupModList(self): return self.SupModList ## # DepexObject # class DepexObject(CommonPropertiesObject):
64
64
101
8
56
KaoTuz/edk2-stable202108
BaseTools/Source/Python/UPT/Object/POM/ModuleObject.py
Python
DepexObject
DepexObject
424
440
424
424
f196442b35c26d3d4caaa83aafca02f69b12caaf
bigcode/the-stack
train
5d94f74c9506e19f9b79a607
train
class
class SourceFileObject(CommonPropertiesObject): def __init__(self): CommonPropertiesObject.__init__(self) self.SourceFile = '' self.TagName = '' self.ToolCode = '' self.Family = '' self.FileType = '' def SetSourceFile(self, SourceFile): self.SourceFile = ...
class SourceFileObject(CommonPropertiesObject):
def __init__(self): CommonPropertiesObject.__init__(self) self.SourceFile = '' self.TagName = '' self.ToolCode = '' self.Family = '' self.FileType = '' def SetSourceFile(self, SourceFile): self.SourceFile = SourceFile def GetSourceFile(self): ...
ArchList(self): return self.SupArchList def SetModuleUniFile(self, ModuleUniFile): self.ModuleUniFile = ModuleUniFile def GetModuleUniFile(self): return self.ModuleUniFile ## # SourceFileObject # class SourceFileObject(CommonPropertiesObject):
64
64
206
8
56
KaoTuz/edk2-stable202108
BaseTools/Source/Python/UPT/Object/POM/ModuleObject.py
Python
SourceFileObject
SourceFileObject
214
251
214
214
5e902a08672329fc93f875db0bcbcc8d59c6613a
bigcode/the-stack
train
87f648c87f8a26d184f19d2b
train
class
class AsBuildLibraryClassObject(object): def __init__(self): self.LibGuid = '' self.LibVersion = '' self.SupArchList = [] def SetLibGuid(self, LibGuid): self.LibGuid = LibGuid def GetLibGuid(self): return self.LibGuid def SetLibVersion(self, LibVersion): ...
class AsBuildLibraryClassObject(object):
def __init__(self): self.LibGuid = '' self.LibVersion = '' self.SupArchList = [] def SetLibGuid(self, LibGuid): self.LibGuid = LibGuid def GetLibGuid(self): return self.LibGuid def SetLibVersion(self, LibVersion): self.LibVersion = LibVersion def Get...
List(self): return self.FileNamList def SetAsBuiltList(self, AsBuiltList): self.AsBuiltList = AsBuiltList def GetAsBuiltList(self): return self.AsBuiltList ## # AsBuildLibraryClassObject # class AsBuildLibraryClassObject(object):
64
64
136
8
56
KaoTuz/edk2-stable202108
BaseTools/Source/Python/UPT/Object/POM/ModuleObject.py
Python
AsBuildLibraryClassObject
AsBuildLibraryClassObject
279
298
279
279
d10d9d79b94d986b2557557a2be009c7204eb8cc
bigcode/the-stack
train
02cd43602cc54de1f695b747
train
class
class BuildOptionObject(CommonPropertiesObject): def __init__(self): CommonPropertiesObject.__init__(self) self.BuildOption = '' def SetBuildOption(self, BuildOption): self.BuildOption = BuildOption def GetBuildOption(self): return self.BuildOption
class BuildOptionObject(CommonPropertiesObject):
def __init__(self): CommonPropertiesObject.__init__(self) self.BuildOption = '' def SetBuildOption(self, BuildOption): self.BuildOption = BuildOption def GetBuildOption(self): return self.BuildOption
self.PackageFilePath = PackageFilePath def GetPackageFilePath(self): return self.PackageFilePath def SetPackage(self, Package): self.Package = Package def GetPackage(self): return self.Package ## # BuildOptionObject # class BuildOptionObject(CommonPropertiesObject):
64
64
61
8
56
KaoTuz/edk2-stable202108
BaseTools/Source/Python/UPT/Object/POM/ModuleObject.py
Python
BuildOptionObject
BuildOptionObject
467
476
467
467
d13fd2d1e54212999fda6493a9e1280249424dbe
bigcode/the-stack
train
1715a1eda22372ddb914d7b3
train
class
class ModuleObject(ModuleHeaderObject): def __init__(self): # # {Arch : ModuleHeaderObject} # self.HeaderDict = {} # # LibraryClassObject # self.LibraryClassList = [] # # SourceFileObject # self.SourceFileList = [] ...
class ModuleObject(ModuleHeaderObject):
def __init__(self): # # {Arch : ModuleHeaderObject} # self.HeaderDict = {} # # LibraryClassObject # self.LibraryClassList = [] # # SourceFileObject # self.SourceFileList = [] # # BinaryFileObject ...
Depex): self.Depex = Depex def GetDepex(self): return self.Depex def SetModuleType(self, ModuleType): self.ModuelType = ModuleType def GetModuleType(self): return self.ModuelType ## # PackageDependencyObject # class PackageDependencyObject(GuidVersionObject, CommonProper...
256
256
945
7
249
KaoTuz/edk2-stable202108
BaseTools/Source/Python/UPT/Object/POM/ModuleObject.py
Python
ModuleObject
ModuleObject
481
654
481
481
a584b41f33619f4d9fa42f6b38cb06ab451004d0
bigcode/the-stack
train
f1f0935cb6ad01f7018a83ef
train
class
class BinaryFileObject(CommonPropertiesObject): def __init__(self): self.FileNamList = [] self.AsBuiltList = [] CommonPropertiesObject.__init__(self) def SetFileNameList(self, FileNamList): self.FileNamList = FileNamList def GetFileNameList(self): return self.FileNa...
class BinaryFileObject(CommonPropertiesObject):
def __init__(self): self.FileNamList = [] self.AsBuiltList = [] CommonPropertiesObject.__init__(self) def SetFileNameList(self, FileNamList): self.FileNamList = FileNamList def GetFileNameList(self): return self.FileNamList def SetAsBuiltList(self, AsBuiltList)...
self.Family = Family def GetFamily(self): return self.Family def SetFileType(self, FileType): self.FileType = FileType def GetFileType(self): return self.FileType ## # BinaryFileObject # class BinaryFileObject(CommonPropertiesObject):
64
64
112
8
56
KaoTuz/edk2-stable202108
BaseTools/Source/Python/UPT/Object/POM/ModuleObject.py
Python
BinaryFileObject
BinaryFileObject
257
273
257
257
f300e030ee2e7ae1f51381f0c4b1b656cd13f525
bigcode/the-stack
train
38fc6a09fb78962083b2fe35
train
class
class BinaryBuildFlagObject(object): def __init__(self): self.Target = '' self.TagName = '' self.Family = '' self.AsBuiltOptionFlags = '' def SetTarget(self, Target): self.Target = Target def GetTarget(self): return self.Target def SetTagName(self, TagN...
class BinaryBuildFlagObject(object):
def __init__(self): self.Target = '' self.TagName = '' self.Family = '' self.AsBuiltOptionFlags = '' def SetTarget(self, Target): self.Target = Target def GetTarget(self): return self.Target def SetTagName(self, TagName): self.TagName = TagName ...
): self.BinaryBuildFlagList = BinaryBuildFlagList def GetBuildFlagsList(self): return self.BinaryBuildFlagList ## # BinaryBuildFlag, this object will include those fields that are not # covered by the UPT Spec BinaryFile field # class BinaryBuildFlagObject(object):
64
64
165
7
57
KaoTuz/edk2-stable202108
BaseTools/Source/Python/UPT/Object/POM/ModuleObject.py
Python
BinaryBuildFlagObject
BinaryBuildFlagObject
350
378
350
350
21a36bbdba828c2e2106ed63724031c38a06a658
bigcode/the-stack
train
56f927037508235f0e205175
train
class
class ModuleHeaderObject(IdentificationObject, CommonHeaderObject, BinaryHeaderObject): def __init__(self): self.IsLibrary = False self.IsLibraryModList = [] self.ModuleType = '' self.BinaryModule = False self.PcdIsDriver = '' self.PiSpecificationVersion = '' ...
class ModuleHeaderObject(IdentificationObject, CommonHeaderObject, BinaryHeaderObject):
def __init__(self): self.IsLibrary = False self.IsLibraryModList = [] self.ModuleType = '' self.BinaryModule = False self.PcdIsDriver = '' self.PiSpecificationVersion = '' self.UefiSpecificationVersion = '' self.UNIFlag = False self.ModuleUniFi...
EventType def GetEventType(self): return self.EventType ## # HobObject # class HobObject(CommonPropertiesObject, HelpTextListObject): def __init__(self): self.HobType = '' CommonPropertiesObject.__init__(self) HelpTextListObject.__init__(self) def SetHobType(self, HobType...
214
214
715
16
198
KaoTuz/edk2-stable202108
BaseTools/Source/Python/UPT/Object/POM/ModuleObject.py
Python
ModuleHeaderObject
ModuleHeaderObject
92
210
92
92
00c97ccda1df905068c6887823ce4b2b4245ca9a
bigcode/the-stack
train
d855dc43a33df8d1f50a9233
train
class
class EventObject(CommonPropertiesObject, HelpTextListObject): def __init__(self): self.EventType = '' CommonPropertiesObject.__init__(self) HelpTextListObject.__init__(self) def SetEventType(self, EventType): self.EventType = EventType def GetEventType(self): retur...
class EventObject(CommonPropertiesObject, HelpTextListObject):
def __init__(self): self.EventType = '' CommonPropertiesObject.__init__(self) HelpTextListObject.__init__(self) def SetEventType(self, EventType): self.EventType = EventType def GetEventType(self): return self.EventType
ListObject.__init__(self) def SetSupportedBootModes(self, SupportedBootModes): self.SupportedBootModes = SupportedBootModes def GetSupportedBootModes(self): return self.SupportedBootModes ## # EventObject # class EventObject(CommonPropertiesObject, HelpTextListObject):
64
64
75
12
52
KaoTuz/edk2-stable202108
BaseTools/Source/Python/UPT/Object/POM/ModuleObject.py
Python
EventObject
EventObject
41
51
41
41
a30bd19f845ebbbcd73fdef810c0b2eea6da9798
bigcode/the-stack
train
a419188a91ffc597b893b437
train
class
class PackageDependencyObject(GuidVersionObject, CommonPropertiesObject): def __init__(self): self.Package = '' self.PackageFilePath = '' GuidVersionObject.__init__(self) CommonPropertiesObject.__init__(self) def SetPackageFilePath(self, PackageFilePath): self.PackageFil...
class PackageDependencyObject(GuidVersionObject, CommonPropertiesObject):
def __init__(self): self.Package = '' self.PackageFilePath = '' GuidVersionObject.__init__(self) CommonPropertiesObject.__init__(self) def SetPackageFilePath(self, PackageFilePath): self.PackageFilePath = PackageFilePath def GetPackageFilePath(self): return ...
def GetDepex(self): return self.Depex def SetModuleType(self, ModuleType): self.ModuelType = ModuleType def GetModuleType(self): return self.ModuelType ## # PackageDependencyObject # class PackageDependencyObject(GuidVersionObject, CommonPropertiesObject):
64
64
111
12
52
KaoTuz/edk2-stable202108
BaseTools/Source/Python/UPT/Object/POM/ModuleObject.py
Python
PackageDependencyObject
PackageDependencyObject
445
462
445
445
1033ced8a76888f7c70009ffc7d4fa080fd7c650
bigcode/the-stack
train
3038eede492fd68db1fdb8e1
train
class
class HobObject(CommonPropertiesObject, HelpTextListObject): def __init__(self): self.HobType = '' CommonPropertiesObject.__init__(self) HelpTextListObject.__init__(self) def SetHobType(self, HobType): self.HobType = HobType def GetHobType(self): return self.HobType...
class HobObject(CommonPropertiesObject, HelpTextListObject):
def __init__(self): self.HobType = '' CommonPropertiesObject.__init__(self) HelpTextListObject.__init__(self) def SetHobType(self, HobType): self.HobType = HobType def GetHobType(self): return self.HobType
.__init__(self) HelpTextListObject.__init__(self) def SetEventType(self, EventType): self.EventType = EventType def GetEventType(self): return self.EventType ## # HobObject # class HobObject(CommonPropertiesObject, HelpTextListObject):
64
64
80
12
52
KaoTuz/edk2-stable202108
BaseTools/Source/Python/UPT/Object/POM/ModuleObject.py
Python
HobObject
HobObject
56
66
56
56
8d6ce2260e262677b9b802cdd86701f89868c1f8
bigcode/the-stack
train
7a7f67ef423b6a57e449bfb9
train
class
class AsBuiltObject(object): def __init__(self): # # list of PcdObject # self.PatchPcdList = [] # # list of PcdObject # self.PcdExValueList = [] # # list of GuidVersionObject # self.LibraryInstancesList = [] # ...
class AsBuiltObject(object):
def __init__(self): # # list of PcdObject # self.PatchPcdList = [] # # list of PcdObject # self.PcdExValueList = [] # # list of GuidVersionObject # self.LibraryInstancesList = [] # # List of BinaryBuildFl...
Version(self, LibVersion): self.LibVersion = LibVersion def GetLibVersion(self): return self.LibVersion def SetSupArchList(self, SupArchList): self.SupArchList = SupArchList def GetSupArchList(self): return self.SupArchList ## # AsBuiltObject # class AsBuiltObject(object):
79
79
265
6
73
KaoTuz/edk2-stable202108
BaseTools/Source/Python/UPT/Object/POM/ModuleObject.py
Python
AsBuiltObject
AsBuiltObject
303
344
303
303
57902405030f25b07dc0ba2538753ed839679e8b
bigcode/the-stack
train
0e6c88313d308c3b3081c411
train
function
def rebuild_index_for_model(model_, engine_slug_, verbosity_): '''rebuilds index for a model''' search_engine_ = get_engine(engine_slug_) local_refreshed_model_count = [0] # HACK: Allows assignment to outer scope. def iter_search_entries(): for obj in model_._default_manager.all().iterator():...
def rebuild_index_for_model(model_, engine_slug_, verbosity_):
'''rebuilds index for a model''' search_engine_ = get_engine(engine_slug_) local_refreshed_model_count = [0] # HACK: Allows assignment to outer scope. def iter_search_entries(): for obj in model_._default_manager.all().iterator(): for search_entry in search_engine_._update_obj_ind...
_): '''returns search engine with a given name''' try: return [x[1] for x in SearchEngine.get_created_engines() if x[0] == engine_slug_][0] except IndexError: raise CommandError("Search Engine \"%s\" is not registered!" % force_text(engine_slug_)) def rebuild_index_for_model(model_, engine_s...
83
83
278
13
70
deadlylaid/study_alone
wef/watson/management/commands/buildwatson.py
Python
rebuild_index_for_model
rebuild_index_for_model
31
55
31
31
1c3d84afadec085608d9ebb1784ca09d78ae6f02
bigcode/the-stack
train
2bbc4ebab65a1e8cbdf34d73
train
function
def get_engine(engine_slug_): '''returns search engine with a given name''' try: return [x[1] for x in SearchEngine.get_created_engines() if x[0] == engine_slug_][0] except IndexError: raise CommandError("Search Engine \"%s\" is not registered!" % force_text(engine_slug_))
def get_engine(engine_slug_):
'''returns search engine with a given name''' try: return [x[1] for x in SearchEngine.get_created_engines() if x[0] == engine_slug_][0] except IndexError: raise CommandError("Search Engine \"%s\" is not registered!" % force_text(engine_slug_))
import force_text from django.utils.translation import activate from django.conf import settings from watson.search import SearchEngine, _bulk_save_search_entries from watson.models import SearchEntry # Sets up registration for django-watson's admin integration. admin.autodiscover() def get_engine(engine_slug_):
64
64
75
7
57
deadlylaid/study_alone
wef/watson/management/commands/buildwatson.py
Python
get_engine
get_engine
24
29
24
24
2d5ce47b79230ac89bf91c4664d7a6f25b50d1f1
bigcode/the-stack
train
aa40855cc1abb814b8649221
train
class
class Command(BaseCommand): args = "[[--engine=search_engine] <app.model|model> <app.model|model> ... ]" help = "Rebuilds the database indices needed by django-watson. You can (re-)build index for selected models by specifying them" def add_arguments(self, parser): parser.add_argument("apps", nargs...
class Command(BaseCommand):
args = "[[--engine=search_engine] <app.model|model> <app.model|model> ... ]" help = "Rebuilds the database indices needed by django-watson. You can (re-)build index for selected models by specifying them" def add_arguments(self, parser): parser.add_argument("apps", nargs="*", action="store", defaul...
= get_engine(engine_slug_) local_refreshed_model_count = [0] # HACK: Allows assignment to outer scope. def iter_search_entries(): for obj in model_._default_manager.all().iterator(): for search_entry in search_engine_._update_obj_index_iter(obj): yield search_entry ...
256
256
917
5
251
deadlylaid/study_alone
wef/watson/management/commands/buildwatson.py
Python
Command
Command
57
151
57
57
fc2a66e1387850b325a67b2b210c227c07049c8c
bigcode/the-stack
train
1e52d8eacb31f0bf7f4c807d
train
class
class GetObjectStream(ReadableStream): def __init__(self, resp): super().__init__() self._resp = resp self._content = resp.content async def read(self, n: int = -1) -> bytes: assert not self._closed return await self._content.read(n) def headers(self) -> 'CIMultiDic...
class GetObjectStream(ReadableStream):
def __init__(self, resp): super().__init__() self._resp = resp self._content = resp.content async def read(self, n: int = -1) -> bytes: assert not self._closed return await self._content.read(n) def headers(self) -> 'CIMultiDictProxy[str]': return self._resp...
def _wait_closed(self): assert self._closed assert self._write_buffer.size() < self._chunk_size while not self._done: await self._write_chunk() assert self._done and self._write_buffer.size() == 0 class GetObjectStream(ReadableStream):
64
64
122
8
55
saponas/hail
hail/python/hailtop/aiogoogle/client/storage_client.py
Python
GetObjectStream
GetObjectStream
305
321
305
305
bdb8725b61e31cc7cb95936aca3eadbc953d9183
bigcode/the-stack
train
5c5f0d9df5a208ab333ba44b
train
class
class _TaskManager: def __init__(self, coro): self._coro = coro self._task = None async def __aenter__(self) -> asyncio.Task: self._task = asyncio.create_task(self._coro) return self._task async def __aexit__(self, exc_type: Optional[Type[BaseExcepti...
class _TaskManager:
def __init__(self, coro): self._coro = coro self._task = None async def __aenter__(self) -> asyncio.Task: self._task = asyncio.create_task(self._coro) return self._task async def __aexit__(self, exc_type: Optional[Type[BaseException]], ...
> 0: b = self._buffers[i] n = len(b) if n <= remaining: yield b remaining -= n i += 1 else: yield b[:remaining] break self._iterating = False class _TaskManager:
64
64
177
5
58
saponas/hail
hail/python/hailtop/aiogoogle/client/storage_client.py
Python
_TaskManager
_TaskManager
140
163
140
140
1990f542f010a548149bd5cae1a3a448a2288e98
bigcode/the-stack
train
b04209becf9ce43fcf85f2fc
train
class
class GoogleStorageMultiPartCreate(MultiPartCreate): def __init__(self, sema: asyncio.Semaphore, fs: 'GoogleStorageAsyncFS', dest_url: str, num_parts: int): self._sema = sema self._fs = fs self._dest_url = dest_url self._num_parts = num_parts bucket, dest_name = fs._get_bucke...
class GoogleStorageMultiPartCreate(MultiPartCreate):
def __init__(self, sema: asyncio.Semaphore, fs: 'GoogleStorageAsyncFS', dest_url: str, num_parts: int): self._sema = sema self._fs = fs self._dest_url = dest_url self._num_parts = num_parts bucket, dest_name = fs._get_bucket_name(dest_url) self._bucket = bucket ...
def __init__(self, url: str, items: Optional[Dict[str, Any]]): assert url.endswith('/') == (items is None), f'{url} {items}' self._url = url self._items = items self._status: Optional[GetObjectFileStatus] = None def name(self) -> str: parsed = urllib.parse.urlparse(self....
234
234
782
11
222
saponas/hail
hail/python/hailtop/aiogoogle/client/storage_client.py
Python
GoogleStorageMultiPartCreate
GoogleStorageMultiPartCreate
456
543
456
456
3659154f4806bedd3cff56e120c8a8325ea6d125
bigcode/the-stack
train
fab74e1bd7f25f9514535ae5
train
class
class PageIterator: def __init__(self, client: 'BaseClient', path: str, request_kwargs: MutableMapping[str, Any]): if 'params' in request_kwargs: request_params = request_kwargs['params'] del request_kwargs['params'] else: request_params = {} self._client ...
class PageIterator:
def __init__(self, client: 'BaseClient', path: str, request_kwargs: MutableMapping[str, Any]): if 'params' in request_kwargs: request_params = request_kwargs['params'] del request_kwargs['params'] else: request_params = {} self._client = client sel...
_transient_errors) from hailtop.aiotools import ( FileStatus, FileListEntry, ReadableStream, WritableStream, AsyncFS, FeedableAsyncIterable, FileAndDirectoryError, MultiPartCreate) from hailtop.aiogoogle.auth import BaseSession from .base_client import BaseClient log = logging.getLogger(__name__) class PageIt...
76
76
256
4
72
saponas/hail
hail/python/hailtop/aiogoogle/client/storage_client.py
Python
PageIterator
PageIterator
24
52
24
24
611cc3e1aa1878ee74846bdf6ce1c7acdad0bdaf
bigcode/the-stack
train
df55f7b57b302e68542e1f85
train
class
class GoogleStorageAsyncFS(AsyncFS): def __init__(self, *, storage_client: Optional[StorageClient] = None, **kwargs): if not storage_client: storage_client = StorageClient(**kwargs) self._storage_client = storage_client def schemes(self) -> Set[str]...
class GoogleStorageAsyncFS(AsyncFS):
def __init__(self, *, storage_client: Optional[StorageClient] = None, **kwargs): if not storage_client: storage_client = StorageClient(**kwargs) self._storage_client = storage_client def schemes(self) -> Set[str]: return {'gs'} @staticm...
: # each chunk gets q, and the first r get one more chunk_size = q if i < r: chunk_size += 1 chunks.append(names[p:p + chunk_size]) p += chunk_size ...
255
256
1,591
9
246
saponas/hail
hail/python/hailtop/aiogoogle/client/storage_client.py
Python
GoogleStorageAsyncFS
GoogleStorageAsyncFS
546
749
546
546
bc62cf016ca894895c23c4cd09afa9d3a0c35814
bigcode/the-stack
train
8a9143f13407ef3ab5e583e4
train
class
class InsertObjectStream(WritableStream): def __init__(self, it, request_task): super().__init__() self._it = it self._request_task = request_task self._value = None async def write(self, b): assert not self.closed await self._it.feed(b) return len(b) ...
class InsertObjectStream(WritableStream):
def __init__(self, it, request_task): super().__init__() self._it = it self._request_task = request_task self._value = None async def write(self, b): assert not self.closed await self._it.feed(b) return len(b) async def _wait_closed(self): aw...
is not None: self._request_params['pageToken'] = next_page_token self._page = await self._client.get(self._path, params=self._request_params, **self._request_kwargs) return self._page raise StopAsyncIteration class InsertObjectStream(WritableStream):
64
64
110
8
55
saponas/hail
hail/python/hailtop/aiogoogle/client/storage_client.py
Python
InsertObjectStream
InsertObjectStream
55
70
55
55
2ac2382a068814558c280e725880ad92990c1b14
bigcode/the-stack
train
e481a1c9a7d0d2bca28135cc
train
class
class _WriteBuffer: def __init__(self): """Long writes that might fail need to be broken into smaller chunks that can be retried. _WriteBuffer stores data at the end of the write stream that has not been committed and may be needed to retry the failed write of a chunk.""" se...
class _WriteBuffer:
def __init__(self): """Long writes that might fail need to be broken into smaller chunks that can be retried. _WriteBuffer stores data at the end of the write stream that has not been committed and may be needed to retry the failed write of a chunk.""" self._buffers = collec...
['pageToken'] = next_page_token self._page = await self._client.get(self._path, params=self._request_params, **self._request_kwargs) return self._page raise StopAsyncIteration class InsertObjectStream(WritableStream): def __init__(self, it, request_task): super().__init__(...
162
162
541
5
157
saponas/hail
hail/python/hailtop/aiogoogle/client/storage_client.py
Python
_WriteBuffer
_WriteBuffer
73
137
73
73
a87eb7a4f78aceead9bc8c254746ef231ac500fe
bigcode/the-stack
train
cab79972d3abb50e1277e514
train
class
class StorageClient(BaseClient): def __init__(self, **kwargs): super().__init__('https://storage.googleapis.com/storage/v1', **kwargs) # docs: # https://cloud.google.com/storage/docs/json_api/v1 async def insert_object(self, bucket: str, name: str, **kwargs) -> WritableStream: assert n...
class StorageClient(BaseClient):
def __init__(self, **kwargs): super().__init__('https://storage.googleapis.com/storage/v1', **kwargs) # docs: # https://cloud.google.com/storage/docs/json_api/v1 async def insert_object(self, bucket: str, name: str, **kwargs) -> WritableStream: assert name # Insert an object. ...
assert not self._closed assert self._write_buffer.size() < self._chunk_size self._write_buffer.append(b) while self._write_buffer.size() >= self._chunk_size: await self._write_chunk() assert self._write_buffer.size() < self._chunk_size return len(b) async...
255
255
850
6
248
saponas/hail
hail/python/hailtop/aiogoogle/client/storage_client.py
Python
StorageClient
StorageClient
324
411
324
324
c6eab4af7ec7b7132ac2b8b22edec58c1af1197f
bigcode/the-stack
train
c04431b8c74aa46c36db38cc
train
class
class ResumableInsertObjectStream(WritableStream): def __init__(self, session: BaseSession, session_url: str, chunk_size: int): super().__init__() self._session = session self._session_url = session_url self._write_buffer = _WriteBuffer() self._broken = False self._do...
class ResumableInsertObjectStream(WritableStream):
def __init__(self, session: BaseSession, session_url: str, chunk_size: int): super().__init__() self._session = session self._session_url = session_url self._write_buffer = _WriteBuffer() self._broken = False self._done = False self._chunk_size = chunk_size ...
i = 0 while remaining > 0: b = self._buffers[i] n = len(b) if n <= remaining: yield b remaining -= n i += 1 else: yield b[:remaining] break self._iterating = False cl...
256
256
1,110
11
244
saponas/hail
hail/python/hailtop/aiogoogle/client/storage_client.py
Python
ResumableInsertObjectStream
ResumableInsertObjectStream
166
302
166
166
3ef6fe937d974293886bf699fd963d58bf718d11
bigcode/the-stack
train
1b5fb00dcf6ab91832415b9f
train
class
class GoogleStorageFileListEntry(FileListEntry): def __init__(self, url: str, items: Optional[Dict[str, Any]]): assert url.endswith('/') == (items is None), f'{url} {items}' self._url = url self._items = items self._status: Optional[GetObjectFileStatus] = None def name(self) -> ...
class GoogleStorageFileListEntry(FileListEntry):
def __init__(self, url: str, items: Optional[Dict[str, Any]]): assert url.endswith('/') == (items is None), f'{url} {items}' self._url = url self._items = items self._status: Optional[GetObjectFileStatus] = None def name(self) -> str: parsed = urllib.parse.urlparse(self....
__init__(self, items: Dict[str, str]): self._items = items async def size(self) -> int: return int(self._items['size']) async def __getitem__(self, key: str) -> str: return self._items[key] class GoogleStorageFileListEntry(FileListEntry):
69
69
233
10
59
saponas/hail
hail/python/hailtop/aiogoogle/client/storage_client.py
Python
GoogleStorageFileListEntry
GoogleStorageFileListEntry
425
453
425
425
06e09fa2749f6822ea471c529b5171ff09b832f8
bigcode/the-stack
train
667fd602f6eea85284ad1a1f
train
class
class GetObjectFileStatus(FileStatus): def __init__(self, items: Dict[str, str]): self._items = items async def size(self) -> int: return int(self._items['size']) async def __getitem__(self, key: str) -> str: return self._items[key]
class GetObjectFileStatus(FileStatus):
def __init__(self, items: Dict[str, str]): self._items = items async def size(self) -> int: return int(self._items['size']) async def __getitem__(self, key: str) -> str: return self._items[key]
body' not in kwargs kwargs['json'] = { 'sourceObjects': [{'name': name} for name in names] } await self.post(f'/b/{bucket}/o/{urllib.parse.quote(destination, safe="")}/compose', **kwargs) class GetObjectFileStatus(FileStatus):
64
64
69
8
56
saponas/hail
hail/python/hailtop/aiogoogle/client/storage_client.py
Python
GetObjectFileStatus
GetObjectFileStatus
414
422
414
414
2bbd4929c6b9098fd84457e10449aebe0e6ce7b8
bigcode/the-stack
train
e5049e80dc71b25ef8e7fcaa
train
function
def iconv(): maybe( http_archive, name = "iconv", urls = [ "https://ftp.gnu.org/pub/gnu/libiconv/libiconv-1.16.tar.gz" ], sha256 = "e6a1b1b589654277ee790cce3734f07876ac4ccfaecbee8afa0b649cf529cc04", build_file = "@rules_third_party//libraries:iconv.BUILD" ...
def iconv():
maybe( http_archive, name = "iconv", urls = [ "https://ftp.gnu.org/pub/gnu/libiconv/libiconv-1.16.tar.gz" ], sha256 = "e6a1b1b589654277ee790cce3734f07876ac4ccfaecbee8afa0b649cf529cc04", build_file = "@rules_third_party//libraries:iconv.BUILD" )
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe") load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") def iconv():
64
64
106
4
60
DraconicEnt/Third-Party
libraries/iconv.bzl
Python
iconv
iconv
18
27
18
18
3315b3538f1c836702bd6286eb4ac82e4837f09b
bigcode/the-stack
train
bbdcaff9178daeeac9997da7
train
class
class OrderManagerErrorSkip(Exception): pass
class OrderManagerErrorSkip(Exception):
pass
from ztom import TradeOrder from ztom.exchange_wrapper import ccxtExchangeWrapper from datetime import datetime import time class OrderManagerError(Exception): pass class OrderManagerErrorUnFilled(Exception): pass class OrderManagerErrorSkip(Exception):
53
64
10
7
45
ztomsy/ztom
ztom/trade_order_manager.py
Python
OrderManagerErrorSkip
OrderManagerErrorSkip
14
15
14
14
31997fdb232e5c63fcbfa74293aa8ed57d60e7f1
bigcode/the-stack
train
6daf8e75f97e9c4765bf8309
train
class
class OrderManagerCancelAttemptsExceeded(Exception): pass
class OrderManagerCancelAttemptsExceeded(Exception):
pass
from ztom import TradeOrder from ztom.exchange_wrapper import ccxtExchangeWrapper from datetime import datetime import time class OrderManagerError(Exception): pass class OrderManagerErrorUnFilled(Exception): pass class OrderManagerErrorSkip(Exception): pass class OrderManagerCancelAttemptsExceeded(Exc...
64
64
11
8
55
ztomsy/ztom
ztom/trade_order_manager.py
Python
OrderManagerCancelAttemptsExceeded
OrderManagerCancelAttemptsExceeded
18
19
18
18
915939897d32b26172de7f8e59eb1a0bcac8820c
bigcode/the-stack
train
aef3d3644f6f72c244080034
train
class
class OrderManagerErrorUnFilled(Exception): pass
class OrderManagerErrorUnFilled(Exception):
pass
from ztom import TradeOrder from ztom.exchange_wrapper import ccxtExchangeWrapper from datetime import datetime import time class OrderManagerError(Exception): pass class OrderManagerErrorUnFilled(Exception):
43
64
11
8
34
ztomsy/ztom
ztom/trade_order_manager.py
Python
OrderManagerErrorUnFilled
OrderManagerErrorUnFilled
10
11
10
10
3dbe7905d9273d80fd20a12d6ca6a66b5b1e0708
bigcode/the-stack
train
3517b5198fc389fab9cfd1fa
train
class
class OrderManagerFok(object): # limits - dict of limits to wait till cancel the order. ex: {"BTC": 0.002, "ETH": 0.02, "BNB": 1, "USDT": 20} # updates_to_kill - number of updates after which to cancel the order if it's not filled # usage: # after init and the update of the order call the proceed_updat...
class OrderManagerFok(object): # limits - dict of limits to wait till cancel the order. ex: {"BTC": 0.002, "ETH": 0.02, "BNB": 1, "USDT": 20} # updates_to_kill - number of updates after which to cancel the order if it's not filled # usage: # after init and the update of the order call the proceed_updat...
LOG_DEBUG = "DEBUG" LOG_INFO = "INFO" LOG_ERROR = "ERROR" LOG_CRITICAL = "CRITICAL" def __init__(self, order: TradeOrder, limits=None, updates_to_kill=100, max_cancel_attempts=10, max_order_update_attempts=1, request_sleep=0.0): """ Creates single order FOK order ma...
from ztom import TradeOrder from ztom.exchange_wrapper import ccxtExchangeWrapper from datetime import datetime import time class OrderManagerError(Exception): pass class OrderManagerErrorUnFilled(Exception): pass class OrderManagerErrorSkip(Exception): pass class OrderManagerCancelAttemptsExceeded(E...
240
256
2,166
173
66
ztomsy/ztom
ztom/trade_order_manager.py
Python
OrderManagerFok
OrderManagerFok
22
278
22
32
b24b922de7f34791f0b709126cbe9fe4231ebceb
bigcode/the-stack
train
707c5380363b6ec3f08e7417
train
class
class OrderManagerError(Exception): pass
class OrderManagerError(Exception):
pass
from ztom import TradeOrder from ztom.exchange_wrapper import ccxtExchangeWrapper from datetime import datetime import time class OrderManagerError(Exception):
32
64
9
6
25
ztomsy/ztom
ztom/trade_order_manager.py
Python
OrderManagerError
OrderManagerError
6
7
6
6
328c5cbab9edbc236688b0b70789b505f94ff98d
bigcode/the-stack
train
56bc7f55141366b3a0da6835
train
class
class SearchRequestHandler(CardRequestHandler): def get(self, *args, **kwargs): scope = self.get_argument("scope") query = self.get_argument("query") card = self.CARDS.get(scope) if not card or not hasattr(card, "search"): raise tornado.web.HTTPError(404) result =...
class SearchRequestHandler(CardRequestHandler):
def get(self, *args, **kwargs): scope = self.get_argument("scope") query = self.get_argument("query") card = self.CARDS.get(scope) if not card or not hasattr(card, "search"): raise tornado.web.HTTPError(404) result = card.search(self, query) self.set_heade...
2007-2019 The NOC Project # See LICENSE for details # ---------------------------------------------------------------------- # Third-party modules import tornado.web import orjson # NOC modules from noc.sa.models.useraccess import UserAccess from .card import CardRequestHandler class SearchRequestHandler(CardRequest...
64
64
113
8
55
prorevizor/noc
services/card/search.py
Python
SearchRequestHandler
SearchRequestHandler
17
29
17
17
80dfcd043db95e7642adb712a92c002a11e1aaca
bigcode/the-stack
train
c06a844e7f3b31eba627887c
train
class
class DirectoryFileName: def __init__(self, directory): self.directory = directory prepare_dir(directory) def get_path(self, filename): return os.path.join(self.directory, filename) def _eval_dev_name(self, types, eval_name, dev_name): if types == 'eval': return...
class DirectoryFileName:
def __init__(self, directory): self.directory = directory prepare_dir(directory) def get_path(self, filename): return os.path.join(self.directory, filename) def _eval_dev_name(self, types, eval_name, dev_name): if types == 'eval': return self.get_path(eval_name)...
def prepare_dir(directory): splitted = directory[1:].split('/') for i in range(1, len(splitted) + 1): d = '/' + '/'.join(splitted[:i]) if not os.path.exists(d): os.mkdir(d) class DirectoryFileName:
64
64
110
5
59
FraunhoferChalmersCentre/ska-sdc-2
pipeline/common/filename.py
Python
DirectoryFileName
DirectoryFileName
13
26
13
13
cbd9366b3bd3f57e8c450006701f0e7565948edc
bigcode/the-stack
train
18d6c1d603651733306abc9f
train
class
class ProcessedFileName(DirectoryFileName): def __init__(self): super().__init__(config['path']['processed']) def segmentmap(self, types): return self._eval_dev_name(types, 'segmap_eval.npz', 'segmap_{}dev.npz') def allocation_dict(self, types): return self._eval_dev_name(types, 's...
class ProcessedFileName(DirectoryFileName):
def __init__(self): super().__init__(config['path']['processed']) def segmentmap(self, types): return self._eval_dev_name(types, 'segmap_eval.npz', 'segmap_{}dev.npz') def allocation_dict(self, types): return self._eval_dev_name(types, 'segmap_eval.npz', 'allocation_{}dev.pb') ...
def new_model(self): return self.by_id(self.new_id) def new_id(self): return len([name for name in os.listdir(self.directory) if os.path.isfile(name)]) def by_id(self, id): return self.get_path('{}.pt'.format(id)) class ProcessedFileName(DirectoryFileName):
69
69
233
10
59
FraunhoferChalmersCentre/ska-sdc-2
pipeline/common/filename.py
Python
ProcessedFileName
ProcessedFileName
43
69
43
43
0554463aec4fb26390a1fc2f34215d19b3bc84f7
bigcode/the-stack
train
a5b256db9029905ca3c108bf
train
class
class DataFileName(DirectoryFileName): def __init__(self): super().__init__(config['path']['data']) def true(self, types): return self.get_path('sky_dev_{}truthcat_v2.txt'.format(types[-1].replace('s', ''))) def sky(self, types): return self._eval_dev_name(types, 'sky_eval.fits', '...
class DataFileName(DirectoryFileName):
def __init__(self): super().__init__(config['path']['data']) def true(self, types): return self.get_path('sky_dev_{}truthcat_v2.txt'.format(types[-1].replace('s', ''))) def sky(self, types): return self._eval_dev_name(types, 'sky_eval.fits', 'sky_{}dev.fits') def cont(self, ty...
hyperopt_dataset(self, size: str, reduction, checkpoint: str): name = 'hyperopt_dataset_{}_reduction_{}_{}'.format(size, int(reduction), checkpoint) path = self.get_path(name) prepare_dir(path) return path class DataFileName(DirectoryFileName):
64
64
191
9
54
FraunhoferChalmersCentre/ska-sdc-2
pipeline/common/filename.py
Python
DataFileName
DataFileName
72
89
72
72
6dfd7dcb75ae5e463ba658762c0429f28e76fff5
bigcode/the-stack
train
d57a7edc038308dee2f3eda7
train
class
class ModelsFileName(DirectoryFileName): def __init__(self): super().__init__(config['path']['models']) def new_model(self): return self.by_id(self.new_id) def new_id(self): return len([name for name in os.listdir(self.directory) if os.path.isfile(name)]) def by_id(self, id): ...
class ModelsFileName(DirectoryFileName):
def __init__(self): super().__init__(config['path']['models']) def new_model(self): return self.by_id(self.new_id) def new_id(self): return len([name for name in os.listdir(self.directory) if os.path.isfile(name)]) def by_id(self, id): return self.get_path('{}.pt'.form...
, dev_name): if types == 'eval': return self.get_path(eval_name) elif types[:3] == 'dev': return self.get_path(dev_name.format(types[-1].replace('s', ''))) raise ValueError('Unknown type') class ModelsFileName(DirectoryFileName):
64
64
87
9
55
FraunhoferChalmersCentre/ska-sdc-2
pipeline/common/filename.py
Python
ModelsFileName
ModelsFileName
29
40
29
29
32b75d822cdf20cbc28905e66bde17d3cf032ba1
bigcode/the-stack
train
d25da1143246bda8d6c6ce07
train
function
def prepare_dir(directory): splitted = directory[1:].split('/') for i in range(1, len(splitted) + 1): d = '/' + '/'.join(splitted[:i]) if not os.path.exists(d): os.mkdir(d)
def prepare_dir(directory):
splitted = directory[1:].split('/') for i in range(1, len(splitted) + 1): d = '/' + '/'.join(splitted[:i]) if not os.path.exists(d): os.mkdir(d)
import os from definitions import config def prepare_dir(directory):
13
64
58
5
7
FraunhoferChalmersCentre/ska-sdc-2
pipeline/common/filename.py
Python
prepare_dir
prepare_dir
5
10
5
5
b58cb81ba046e876aa261d30c8cadeb75df12184
bigcode/the-stack
train
c9b9b1a7fb2f3ec00d229bd3
train
function
def country_choice_kwargs(): allcountries = list(CachedCountries()) allcountries.insert(0, ('', _('Select country'))) return { 'choices': allcountries }
def country_choice_kwargs():
allcountries = list(CachedCountries()) allcountries.insert(0, ('', _('Select country'))) return { 'choices': allcountries }
pretix.base.reldate import ( RelativeDateField, RelativeDateTimeField, RelativeDateWrapper, SerializerRelativeDateField, SerializerRelativeDateTimeField, ) from pretix.control.forms import MultipleLanguagesWidget, SingleLanguageWidget from pretix.helpers.countries import CachedCountries def country_choice_kwar...
64
64
39
5
58
drskullster/pretix
src/pretix/base/settings.py
Python
country_choice_kwargs
country_choice_kwargs
33
38
33
33
631adf801fd75cd1a4cd0bad750582589676e8ed
bigcode/the-stack
train
1a74eb0f40da8ce9244f6c46
train
class
class LazyI18nStringList(UserList): def __init__(self, init_list=None): super().__init__() if init_list is not None: self.data = [v if isinstance(v, LazyI18nString) else LazyI18nString(v) for v in init_list] def serialize(self): return json.dumps([s.data for s in self.data])...
class LazyI18nStringList(UserList):
def __init__(self, init_list=None): super().__init__() if init_list is not None: self.data = [v if isinstance(v, LazyI18nString) else LazyI18nString(v) for v in init_list] def serialize(self): return json.dumps([s.data for s in self.data]) @classmethod def unseriali...
, SingleLanguageWidget from pretix.helpers.countries import CachedCountries def country_choice_kwargs(): allcountries = list(CachedCountries()) allcountries.insert(0, ('', _('Select country'))) return { 'choices': allcountries } class LazyI18nStringList(UserList):
64
64
101
10
54
drskullster/pretix
src/pretix/base/settings.py
Python
LazyI18nStringList
LazyI18nStringList
41
52
41
41
035f77d0bfdd8530fd22a35a6de04d738fe9645e
bigcode/the-stack
train
63a1bea0e9f7e0a29b816eef
train
class
class SettingsSandbox: """ Transparently proxied access to event settings, handling your prefixes for you. :param typestr: The first part of the pretix, e.g. ``plugin`` :param key: The prefix, e.g. the name of your plugin :param obj: The event or organizer that should be queried """ def __...
class SettingsSandbox:
""" Transparently proxied access to event settings, handling your prefixes for you. :param typestr: The first part of the pretix, e.g. ``plugin`` :param key: The prefix, e.g. the name of your plugin :param obj: The event or organizer that should be queried """ def __init__(self, typestr: s...
, serialize=lambda s: json.dumps(s.data), unserialize=i18n_uns) settings_hierarkey.add_type(LazyI18nStringList, serialize=operator.methodcaller("serialize"), unserialize=LazyI18nStringList.unserialize) settin...
123
123
412
4
119
drskullster/pretix
src/pretix/base/settings.py
Python
SettingsSandbox
SettingsSandbox
2,099
2,143
2,099
2,099
5518d85d7516018e8215e065f920b9fc0385bfda
bigcode/the-stack
train
2572ec07a6e3ee4ea6daa229
train
class
@settings_hierarkey.set_global(cache_namespace='global') class GlobalSettingsObject(GlobalSettingsBase): slug = '_global'
@settings_hierarkey.set_global(cache_namespace='global') class GlobalSettingsObject(GlobalSettingsBase):
slug = '_global'
18nStringList.unserialize) settings_hierarkey.add_type(RelativeDateWrapper, serialize=lambda rdw: rdw.to_string(), unserialize=lambda s: RelativeDateWrapper.from_string(s)) @settings_hierarkey.set_global(cache_namespace='global') class GlobalSettingsObject(GlobalS...
64
64
27
21
43
drskullster/pretix
src/pretix/base/settings.py
Python
GlobalSettingsObject
GlobalSettingsObject
2,094
2,096
2,094
2,095
cc00ecb1e53c6b7e97e047b187a71ef9c8f1134d
bigcode/the-stack
train
b51a73359596439cab0beaee
train
function
def i18n_uns(v): try: return LazyI18nString(json.loads(v)) except ValueError: return LazyI18nString(str(v))
def i18n_uns(v):
try: return LazyI18nString(json.loads(v)) except ValueError: return LazyI18nString(str(v))
['State', 'Outlying area', 'District'], 'short'), } settings_hierarkey = Hierarkey(attribute_name='settings') for k, v in DEFAULTS.items(): settings_hierarkey.add_default(k, v['default'], v['type']) def i18n_uns(v):
63
64
36
7
56
drskullster/pretix
src/pretix/base/settings.py
Python
i18n_uns
i18n_uns
2,076
2,080
2,076
2,076
e751c3e3c6e98eccef4387b9d2553b78c8bcd97a
bigcode/the-stack
train
a1e480435034cc3f356d46f0
train
function
def validate_settings(event, settings_dict): from pretix.base.signals import validate_event_settings if 'locales' in settings_dict and settings_dict['locale'] not in settings_dict['locales']: raise ValidationError({ 'locale': _('Your default locale must also be enabled for your event (see b...
def validate_settings(event, settings_dict):
from pretix.base.signals import validate_event_settings if 'locales' in settings_dict and settings_dict['locale'] not in settings_dict['locales']: raise ValidationError({ 'locale': _('Your default locale must also be enabled for your event (see box above).') }) if settings_dict....
def __delattr__(self, key: str) -> None: del self._event.settings[self._convert_key(key)] def get(self, key: str, default: Any = None, as_type: type = str): return self._event.settings.get(self._convert_key(key), default=default, as_type=as_type) def set(self, key: str, value: Any): ...
107
107
357
8
99
drskullster/pretix
src/pretix/base/settings.py
Python
validate_settings
validate_settings
2,146
2,177
2,146
2,146
6111dc7c8bec25b503dff9606d5bcb13764232dd
bigcode/the-stack
train
1e01282454a4b1e40830689f
train
function
def setup(app): app.connect('autodoc-skip-member', skip_member) app.connect('autodoc-process-docstring', process_docstring) from generate_api_docs import generate_docs generate_docs() # Generate modules_api.rst
def setup(app):
app.connect('autodoc-skip-member', skip_member) app.connect('autodoc-process-docstring', process_docstring) from generate_api_docs import generate_docs generate_docs() # Generate modules_api.rst
: for k, v in annotations.items(): if k == "return": if v and needs_return_type: lines.append(":rtype: %s" % v) elif needs_call_types: lines.append(":type %s: %s" % (k, v)) def setup(app):
64
64
54
4
60
aaron-parsons/pymalcolm
docs/conf.py
Python
setup
setup
119
123
119
119
32861fc27127fe90d590f72342e90043a11d6cf6
bigcode/the-stack
train
9d87e827cdcb1eb97dade3af
train
function
def process_docstring(app, what, name, obj, options, lines): # Work out if we need to work out the call types and return types needs_call_types = True needs_return_type = True for line in lines: strip = line.strip() if strip.startswith(":type"): needs_call_types = False ...
def process_docstring(app, what, name, obj, options, lines): # Work out if we need to work out the call types and return types
needs_call_types = True needs_return_type = True for line in lines: strip = line.strip() if strip.startswith(":type"): needs_call_types = False elif strip.startswith(":rtype"): needs_return_type = False # If we have annotated with @add_call_types, or this ...
mod_name, MagicMock()) for mod_name in MOCK_MODULES) sys.path.insert(0, os.path.abspath(os.path.join(__file__, '..', '..'))) sys.path.append(os.path.dirname(__file__)) # Autodoc event handlers def skip_member(app, what, name, obj, skip, options): # Override @add_call_types to always be documented if hasatt...
143
143
479
33
109
aaron-parsons/pymalcolm
docs/conf.py
Python
process_docstring
process_docstring
69
116
69
70
46f4fbea98d77e99111102b45e038f4ef9bb6c52
bigcode/the-stack
train
2da455e75defb4fae2ffe58a
train
function
def get_version(): """Extracts the version number from the version.py file.""" VERSION_FILE = '../malcolm/version.py' mo = re.search(r'^__version__ = [\'"]([^\'"]*)[\'"]', open(VERSION_FILE, 'rt').read(), re.M) if mo: return mo.group(1) else: raise RuntimeError( ...
def get_version():
"""Extracts the version number from the version.py file.""" VERSION_FILE = '../malcolm/version.py' mo = re.search(r'^__version__ = [\'"]([^\'"]*)[\'"]', open(VERSION_FILE, 'rt').read(), re.M) if mo: return mo.group(1) else: raise RuntimeError( 'Unable t...
# -*- coding: utf-8 -*- # # malcolm documentation build configuration file import inspect import os import re import sys from enum import Enum def get_version():
38
64
99
4
33
aaron-parsons/pymalcolm
docs/conf.py
Python
get_version
get_version
12
21
12
12
10fa5500ffcddc25f5bfdb62caf824822088945c
bigcode/the-stack
train
e0f7e829cb0bd79580468594
train
function
def skip_member(app, what, name, obj, skip, options): # Override @add_call_types to always be documented if hasattr(obj, "call_types") or hasattr(obj, "return_type"): return False elif isinstance(obj, Enum): return False
def skip_member(app, what, name, obj, skip, options): # Override @add_call_types to always be documented
if hasattr(obj, "call_types") or hasattr(obj, "return_type"): return False elif isinstance(obj, Enum): return False
sys.path.insert(0, os.path.abspath(os.path.join(__file__, '..', '..'))) sys.path.append(os.path.dirname(__file__)) # Autodoc event handlers def skip_member(app, what, name, obj, skip, options): # Override @add_call_types to always be documented
64
64
59
27
36
aaron-parsons/pymalcolm
docs/conf.py
Python
skip_member
skip_member
61
66
61
62
43828a6c3d465dafc0521639d225307d62ccb64d
bigcode/the-stack
train
2b49dbbf8b50b2e5a789b173
train
class
class Logger: """ A general-purpose logger. Makes it easy to save diagnostics, hyperparameter configurations, the state of a training run, and the trained model. """ def __init__(self, output_dir=None, output_fname='progress.txt', exp_name=None): """ Initialize a Logger. ...
class Logger:
""" A general-purpose logger. Makes it easy to save diagnostics, hyperparameter configurations, the state of a training run, and the trained model. """ def __init__(self, output_dir=None, output_fname='progress.txt', exp_name=None): """ Initialize a Logger. Args: ...
attr.append(str(num)) if bold: attr.append('1') return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string) def restore_tf_graph(sess, fpath): """ Loads graphs saved by Logger. Will output a dictionary whose keys and values are from the 'inputs' and 'outputs' dict you specified with logger.setu...
256
256
1,708
3
252
anyboby/CPO
utils/logx.py
Python
Logger
Logger
67
253
67
67
41138b45fdf0d918559fc34f6742da16d27d4820
bigcode/the-stack
train
99647e501aa2c19fb8022a75
train
function
def restore_tf_graph(sess, fpath): """ Loads graphs saved by Logger. Will output a dictionary whose keys and values are from the 'inputs' and 'outputs' dict you specified with logger.setup_tf_saver(). Args: sess: A Tensorflow session. fpath: Filepath to save directory. Return...
def restore_tf_graph(sess, fpath):
""" Loads graphs saved by Logger. Will output a dictionary whose keys and values are from the 'inputs' and 'outputs' dict you specified with logger.setup_tf_saver(). Args: sess: A Tensorflow session. fpath: Filepath to save directory. Returns: A dictionary mapping fro...
= color2num[color] if highlight: num += 10 attr.append(str(num)) if bold: attr.append('1') return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string) def restore_tf_graph(sess, fpath):
64
64
213
9
55
anyboby/CPO
utils/logx.py
Python
restore_tf_graph
restore_tf_graph
40
65
40
40
85fd369b624f6d05a46106864701aa622b988783
bigcode/the-stack
train
925ed3bf4e38f859f769e176
train
class
class EpochLogger(Logger): """ A variant of Logger tailored for tracking average values over epochs. Typical use case: there is some quantity which is calculated many times throughout an epoch, and at the end of the epoch, you would like to report the average / std / min / max value of that quanti...
class EpochLogger(Logger):
""" A variant of Logger tailored for tracking average values over epochs. Typical use case: there is some quantity which is calculated many times throughout an epoch, and at the end of the epoch, you would like to report the average / std / min / max value of that quantity. With an EpochLogge...
] max_key_len = max(15,max(key_lens)) keystr = '%'+'%d'%max_key_len fmt = "| " + keystr + "s | %15s |" n_slashes = 22 + max_key_len print("-"*n_slashes) for key in self.log_headers: val = self.log_current_row.get(key, "") ...
202
202
676
5
196
anyboby/CPO
utils/logx.py
Python
EpochLogger
EpochLogger
255
335
255
255
c1b35277981c2edde492fd2597a8a52df3d45d9f
bigcode/the-stack
train
37d2f98f8ffd9a4d8035a3c1
train
function
def colorize(string, color, bold=False, highlight=False): """ Colorize a string. This function was originally written by John Schulman. """ attr = [] num = color2num[color] if highlight: num += 10 attr.append(str(num)) if bold: attr.append('1') return '\x1b[%sm%s\x1b[0m' % (';'....
def colorize(string, color, bold=False, highlight=False):
""" Colorize a string. This function was originally written by John Schulman. """ attr = [] num = color2num[color] if highlight: num += 10 attr.append(str(num)) if bold: attr.append('1') return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string)
num = dict( gray=30, red=31, green=32, yellow=33, blue=34, magenta=35, cyan=36, white=37, crimson=38 ) def colorize(string, color, bold=False, highlight=False):
64
64
95
13
51
anyboby/CPO
utils/logx.py
Python
colorize
colorize
27
38
27
27
2298a2fb4e7e19c4c55488867831b71fd475821b
bigcode/the-stack
train
2998d05b6076f057f74f4705
train
function
@pytest.mark.parametrize("singular,plural", [ ("serum", "serums"), ("argi", "argii"), ("fibulatie", "fibulaties") ]) def test_pluralizer_scenarios(singular, plural): overrides = NounEndingMap({"argi": "argii"}) hnspll = new_hunspell_nl() hnspll.add("fibulatie") hnspll.add("argi") hn...
@pytest.mark.parametrize("singular,plural", [ ("serum", "serums"), ("argi", "argii"), ("fibulatie", "fibulaties") ]) def test_pluralizer_scenarios(singular, plural):
overrides = NounEndingMap({"argi": "argii"}) hnspll = new_hunspell_nl() hnspll.add("fibulatie") hnspll.add("argi") hnspll.add("argii") hnspll.add("fibulaties") p = Pluralizer(hnspll, overrides) assert p.pluralize_advanced(singular).plural == plural assert p.singularize_advanced(plu...
_pluralizer.speller import new_hunspell_nl @pytest.mark.parametrize("singular,plural", [ ("serum", "serums"), ("argi", "argii"), ("fibulatie", "fibulaties") ]) def test_pluralizer_scenarios(singular, plural):
64
64
157
52
11
KeesCBakker/dutch-pluralizer-py
tests/test_cls.py
Python
test_pluralizer_scenarios
test_pluralizer_scenarios
5
22
5
11
a5ec421066e1e90fd4c94d455ed68740a59de691
bigcode/the-stack
train
19f3a681c8161637b846ed90
train
function
def parse_args(): """parameters""" parser = argparse.ArgumentParser('mindspore adveast training') parser.add_argument('--device_target', type=str, default='Ascend', choices=['Ascend', 'GPU'], help='device where the code will be implemented. (Default: Ascend)') parser.add_argument...
def parse_args():
"""parameters""" parser = argparse.ArgumentParser('mindspore adveast training') parser.add_argument('--device_target', type=str, default='Ascend', choices=['Ascend', 'GPU'], help='device where the code will be implemented. (Default: Ascend)') parser.add_argument('--device_id', ty...
mindspore.common import set_seed from mindspore.communication.management import init, get_rank, get_group_size from mindspore.context import ParallelMode from mindspore.nn.optim import AdamWeightDecay from mindspore.train.callback import ModelCheckpoint, CheckpointConfig, LossMonitor, TimeMonitor from mindspore.train....
123
123
410
4
119
leelige/mindspore
research/cv/advanced_east/train.py
Python
parse_args
parse_args
39
71
39
39
f5fd78d0b7e58b5c65755198069944d63884bf1a
bigcode/the-stack
train
9181bbeca6f267b70e3dd68c
train
class
class DefaultTrainer(SimpleTrainer): """ A trainer with default training logic. Compared to `SimpleTrainer`, it contains the following logic in addition: 1. Create model, optimizer, scheduler, dataloader from the given config. 2. Load a checkpoint or `cfg.MODEL.WEIGHTS`, if exists, when `res...
class DefaultTrainer(SimpleTrainer):
""" A trainer with default training logic. Compared to `SimpleTrainer`, it contains the following logic in addition: 1. Create model, optimizer, scheduler, dataloader from the given config. 2. Load a checkpoint or `cfg.MODEL.WEIGHTS`, if exists, when `resume_or_load` is called. 3. Regist...
) self.input_format = cfg.INPUT.FORMAT assert self.input_format in ["RGB", "BGR"], self.input_format def __call__(self, original_image): """ Args: original_image (np.ndarray): an image of shape (H, W, C) (in BGR order). Returns: predictions ...
256
256
2,351
6
249
zsef123/detectron2
detectron2/engine/defaults.py
Python
DefaultTrainer
DefaultTrainer
201
512
201
201
76abf8324e699b5cf57bea7680da33c3a78e6db2
bigcode/the-stack
train
413c36d6f9728a18a4c8bd92
train
function
def default_setup(cfg, args): """ Perform some basic common setups at the beginning of a job, including: 1. Set up the detectron2 logger 2. Log basic information about environment, cmdline arguments, and config 3. Backup the config to the output directory Args: cfg (CfgNode): the full ...
def default_setup(cfg, args):
""" Perform some basic common setups at the beginning of a job, including: 1. Set up the detectron2 logger 2. Log basic information about environment, cmdline arguments, and config 3. Backup the config to the output directory Args: cfg (CfgNode): the full config to be used args...
Therefore we use a deterministic way to obtain port, # so that users are aware of orphan processes by seeing the port occupied. port = 2 ** 15 + 2 ** 14 + hash(os.getuid() if sys.platform != "win32" else 1) % 2 ** 14 parser.add_argument("--dist-url", default="tcp://127.0.0.1:{}".format(port)) parser.ad...
135
135
451
7
127
zsef123/detectron2
detectron2/engine/defaults.py
Python
default_setup
default_setup
84
130
84
84
0cae1dd25a08a68ad8fb331f581422abf721127d
bigcode/the-stack
train
d35365b922a3179a77ab6156
train
class
class DefaultPredictor: """ Create a simple end-to-end predictor with the given config that runs on single device for a single input image. Compared to using the model directly, this class does the following additions: 1. Load checkpoint from `cfg.MODEL.WEIGHTS`. 2. Always take BGR image as th...
class DefaultPredictor:
""" Create a simple end-to-end predictor with the given config that runs on single device for a single input image. Compared to using the model directly, this class does the following additions: 1. Load checkpoint from `cfg.MODEL.WEIGHTS`. 2. Always take BGR image as the input and apply conver...
output_dir: # Note: some of our scripts may expect the existence of # config.yaml in output directory path = os.path.join(output_dir, "config.yaml") with PathManager.open(path, "w") as f: f.write(cfg.dump()) logger.info("Full config saved to {}".format(path)) # ...
169
169
566
5
163
zsef123/detectron2
detectron2/engine/defaults.py
Python
DefaultPredictor
DefaultPredictor
133
198
133
133
62aedef61a4e0c636a2d8eb33b14b1935f783341
bigcode/the-stack
train
1eb09c8172636089c6735c5c
train
function
def default_argument_parser(): """ Create a parser with some common arguments used by detectron2 users. Returns: argparse.ArgumentParser: """ parser = argparse.ArgumentParser(description="Detectron2 Training") parser.add_argument("--config-file", default="", metavar="FILE", help="path t...
def default_argument_parser():
""" Create a parser with some common arguments used by detectron2 users. Returns: argparse.ArgumentParser: """ parser = argparse.ArgumentParser(description="Detectron2 Training") parser.add_argument("--config-file", default="", metavar="FILE", help="path to config file") parser.add_...
detectron2.utils import comm from detectron2.utils.collect_env import collect_env_info from detectron2.utils.env import seed_all_rng from detectron2.utils.events import CommonMetricPrinter, JSONWriter, TensorboardXWriter from detectron2.utils.logger import setup_logger from . import hooks from .train_loop import Simp...
99
100
335
5
94
zsef123/detectron2
detectron2/engine/defaults.py
Python
default_argument_parser
default_argument_parser
49
81
49
49
a71b46f436081cec2829d73a5f8caa97b4ce1f0f
bigcode/the-stack
train
f00b59b3966c2b24600e748f
train
function
def make_fill_polygons(xs, ys, zs): '''Make a set of polygons to fill the space below a line in 3d. Returns ------- mpl_toolkits.mplot3d.art3d.Poly3DCollection ''' from mpl_toolkits.mplot3d.art3d import Poly3DCollection v = [] h = 0 for k in range(0, len(xs) - 1): x = [xs[k]...
def make_fill_polygons(xs, ys, zs):
'''Make a set of polygons to fill the space below a line in 3d. Returns ------- mpl_toolkits.mplot3d.art3d.Poly3DCollection ''' from mpl_toolkits.mplot3d.art3d import Poly3DCollection v = [] h = 0 for k in range(0, len(xs) - 1): x = [xs[k], xs[k+1], xs[k+1], xs[k]] y...
torch.manual_seed(seed) if torch.cuda.is_available(): torch.cuda.manual_seed_all(seed) torch.backends.cudnn.deterministic = True np.random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) def make_fill_polygons(xs, ys, zs):
64
64
185
11
53
themightyoarfish/ikkuna
ikkuna/utils/utils.py
Python
make_fill_polygons
make_fill_polygons
39
55
39
39
173fa0962bd1ef0fa4bcfbd3178dbd60c2872ca6
bigcode/the-stack
train
9fc22cff32388c1d0254a492
train
class
class DatasetMeta(NamedTuple): '''Class encapsulating a dataset and makes information about it more easily accessible.''' dataset: object num_classes: int shape: tuple @property def size(self): '''int: Number of examples in the dataset''' return self.shape[0]
class DatasetMeta(NamedTuple):
'''Class encapsulating a dataset and makes information about it more easily accessible.''' dataset: object num_classes: int shape: tuple @property def size(self): '''int: Number of examples in the dataset''' return self.shape[0]
from typing import NamedTuple class DatasetMeta(NamedTuple):
13
64
67
7
5
themightyoarfish/ikkuna
ikkuna/utils/utils.py
Python
DatasetMeta
DatasetMeta
4
13
4
4
afeac2053fb9a87ec35c41cf164f60b586a01afb
bigcode/the-stack
train
715cec5931ebccd081dc31ce
train
function
def get_model(model_name, *args, **kwargs): from ikkuna import models try: if model_name.startswith('ResNet'): model_fn = getattr(models, model_name.lower()) if args: print(f'Warning: Ignored args for {model_name} ({args})') model = model_fn(**kwargs) ...
def get_model(model_name, *args, **kwargs):
from ikkuna import models try: if model_name.startswith('ResNet'): model_fn = getattr(models, model_name.lower()) if args: print(f'Warning: Ignored args for {model_name} ({args})') model = model_fn(**kwargs) else: Model = getattr(mo...
torch if name not in available_optimizers(): raise ValueError(f'Unknown optimizer {name}') params = [p for p in model.parameters() if p.requires_grad] return getattr(torch.optim, name)(params, **kwargs) def get_model(model_name, *args, **kwargs):
64
64
117
12
52
themightyoarfish/ikkuna
ikkuna/utils/utils.py
Python
get_model
get_model
105
119
105
105
b10a5b41c592f2ffa23bc4d87aa014f4b0c0b124
bigcode/the-stack
train
732dce5bfed07f71a88a48a7
train
function
def freeze_module(module): def freeze(m): for p in m.parameters(): m.requires_grad = False module.apply(freeze)
def freeze_module(module):
def freeze(m): for p in m.parameters(): m.requires_grad = False module.apply(freeze)
meta_train = DatasetMeta(dataset=dataset_train, num_classes=num_classes(dataset_train), shape=shape(dataset_train)) meta_test = DatasetMeta(dataset=dataset_test, num_classes=num_classes(dataset_test), shape=shape(dataset_test)) return meta_train, m...
64
64
30
5
58
themightyoarfish/ikkuna
ikkuna/utils/utils.py
Python
freeze_module
freeze_module
340
345
340
340
a3ef6efc73f7e1bfa2b34fbc6e5560dc5c6e6483
bigcode/the-stack
train
27075fb5c69c36268196385e
train
function
def available_optimizers(): '''List names of all available torch optimizers form :py:mod:`torch.optim`. Returns ------- list(str) A list of all optimizer names. ''' import torch # get all module properties which aren't magic available_optimizers = set(getattr(torch.optim, name) ...
def available_optimizers():
'''List names of all available torch optimizers form :py:mod:`torch.optim`. Returns ------- list(str) A list of all optimizer names. ''' import torch # get all module properties which aren't magic available_optimizers = set(getattr(torch.optim, name) ...
1], ys[k+1], ys[k]] z = [zs[k], zs[k+1], h, h] v.append(list(zip(x, y, z))) poly3dCollection = Poly3DCollection(v) return poly3dCollection def available_optimizers():
64
64
170
6
57
themightyoarfish/ikkuna
ikkuna/utils/utils.py
Python
available_optimizers
available_optimizers
58
76
58
58
34716e35853012a70f38eef1d1ae1bec64cb8c6b
bigcode/the-stack
train
017e3758827f9d06cbe1d3b4
train
function
def _load_imagenet_dogs(root, formats, train_transforms, test_transforms): '''Load the ImageNetDogs dataset from disk''' from torchvision.datasets import DatasetFolder from torch.utils.data import random_split from PIL import Image import copy def loader(path): '''Load image from fs pat...
def _load_imagenet_dogs(root, formats, train_transforms, test_transforms):
'''Load the ImageNetDogs dataset from disk''' from torchvision.datasets import DatasetFolder from torch.utils.data import random_split from PIL import Image import copy def loader(path): '''Load image from fs path''' return Image.open(path) dataset = DatasetFolder(root, loa...
/ factors[index] for x in memory.strip().split('\n')] return dict(zip(range(len(size)), size)) import torchvision from torchvision.transforms import ToTensor, Compose import numpy as np import torch def _load_imagenet_dogs(root, formats, train_transforms, test_transforms):
64
64
198
20
43
themightyoarfish/ikkuna
ikkuna/utils/utils.py
Python
_load_imagenet_dogs
_load_imagenet_dogs
205
228
205
205
a9c3d3f4c6a6feef44e03f24352020b6fdfac228
bigcode/the-stack
train
e3f5c860f20398df713db161
train
function
def get_memory_stats(mode='total', unit='mb'): '''Get the total|used|free gpu memory. Parameters ---------- mode : str One of ``'total'``, ``'used'`` or ``'free'`` Returns ------- dict Keys are device ids as integers. Values are memory usage as integers...
def get_memory_stats(mode='total', unit='mb'):
'''Get the total|used|free gpu memory. Parameters ---------- mode : str One of ``'total'``, ``'used'`` or ``'free'`` Returns ------- dict Keys are device ids as integers. Values are memory usage as integers in MB. ''' if mode not in ['total', 'u...
elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() elif isinstance(m, nn.Linear): m.bias.data.zero_() else: raise ValueError(f'Don\'t know how to initialize {module.__class__.__name__}') import subprocess d...
81
81
273
12
68
themightyoarfish/ikkuna
ikkuna/utils/utils.py
Python
get_memory_stats
get_memory_stats
165
196
165
165
29a465ca641d39aa6f96d2e79de64b1448407916
bigcode/the-stack
train
18646601a7ab84dcaecc5594
train
function
def create_optimizer(model, name, **kwargs): '''Create an optimizer for ``model``\ s parameters. Will disregard all params with ``requires_grad == False``. Parameters ---------- model : torch.nn.Module name : str Name of the optimizer kwargs : dict ...
def create_optimizer(model, name, **kwargs):
'''Create an optimizer for ``model``\ s parameters. Will disregard all params with ``requires_grad == False``. Parameters ---------- model : torch.nn.Module name : str Name of the optimizer kwargs : dict All arguments which should be passed to the...
(lambda o: isinstance(o, type), available_optimizers) # map them to their class name (w/o module) available_optimizers = map(lambda o: o.__name__, available_optimizers) return list(available_optimizers) def create_optimizer(model, name, **kwargs):
64
64
158
10
54
themightyoarfish/ikkuna
ikkuna/utils/utils.py
Python
create_optimizer
create_optimizer
79
102
79
79
94568993524f0c06cee6d4f350133833c2b37ad9
bigcode/the-stack
train
373dd6fc53857aa9ce382532
train
function
def initialize_model(module, bias_val=0.01): '''Perform weight initialization on `module`. This is somewhat hacky since it assumes the presence of `weight` and/or `bias` fields on the module. Will skip if not present. Parameters ---------- module : torch.nn.Module The model ...
def initialize_model(module, bias_val=0.01):
'''Perform weight initialization on `module`. This is somewhat hacky since it assumes the presence of `weight` and/or `bias` fields on the module. Will skip if not present. Parameters ---------- module : torch.nn.Module The model bias_val : float ...
_fn = getattr(models, model_name.lower()) if args: print(f'Warning: Ignored args for {model_name} ({args})') model = model_fn(**kwargs) else: Model = getattr(models, model_name) model = Model(*args, **kwargs) except AttributeError: rais...
96
96
320
12
83
themightyoarfish/ikkuna
ikkuna/utils/utils.py
Python
initialize_model
initialize_model
122
159
122
122
6161eebe8877b9bfaabaaa57cf138f132aab3258
bigcode/the-stack
train
876da81a021144a6dd4c8aed
train
function
def load_dataset(name, train_transforms=None, test_transforms=None, **kwargs): '''Retrieve a dataset and determine the number of classes. This estimate is obtained from the number of different values in the training labels. Parameters ---------- name : str Currently, dataset na...
def load_dataset(name, train_transforms=None, test_transforms=None, **kwargs):
'''Retrieve a dataset and determine the number of classes. This estimate is obtained from the number of different values in the training labels. Parameters ---------- name : str Currently, dataset names in :mod:`torchvision.datasets` and ``ImageNetDogs`` are sup...
return dict(zip(range(len(size)), size)) import torchvision from torchvision.transforms import ToTensor, Compose import numpy as np import torch def _load_imagenet_dogs(root, formats, train_transforms, test_transforms): '''Load the ImageNetDogs dataset from disk''' from torchvision.datasets import DatasetF...
245
245
818
18
226
themightyoarfish/ikkuna
ikkuna/utils/utils.py
Python
load_dataset
load_dataset
231
337
231
231
60da21b636f64e299ec36e6537e6b285986b51cc
bigcode/the-stack
train
d8ee691c68c3557abeb4d41d
train
function
def seed_everything(seed=1234): '''Set the seed for :mod:`torch`, :mod:`random`, :mod:`numpy` and :mod:`torch.cuda`, as well as the ``PYTHONHASHSEED`` env var. It also configures CuDNN to use deterministic mode. .. warning:: Setting the CuDNN backend to deterministic mode potentially incurs a perf...
def seed_everything(seed=1234):
'''Set the seed for :mod:`torch`, :mod:`random`, :mod:`numpy` and :mod:`torch.cuda`, as well as the ``PYTHONHASHSEED`` env var. It also configures CuDNN to use deterministic mode. .. warning:: Setting the CuDNN backend to deterministic mode potentially incurs a performance penalty Parameters ...
a dataset and makes information about it more easily accessible.''' dataset: object num_classes: int shape: tuple @property def size(self): '''int: Number of examples in the dataset''' return self.shape[0] def seed_everything(seed=1234):
64
64
178
9
55
themightyoarfish/ikkuna
ikkuna/utils/utils.py
Python
seed_everything
seed_everything
16
36
16
16
d1522bd5e7e437cbcb07b9f4b9372442e393762f
bigcode/the-stack
train
2836f262ad7333f151ca499b
train
function
def error_of_geo_to_meter_approx_NED(geo_origin, latitude_to_meter, longitude_to_meter, geo_coords_arr_rad): """ Computes error of linear transformation approximation with point correspondences to NED coordinates. :param geo_origin: The geo origin :param latitude_to_meter: ...
def error_of_geo_to_meter_approx_NED(geo_origin, latitude_to_meter, longitude_to_meter, geo_coords_arr_rad):
""" Computes error of linear transformation approximation with point correspondences to NED coordinates. :param geo_origin: The geo origin :param latitude_to_meter: The latitude to meter :param longitude_to_meter: The longitude to meter :param geo_coords_...
""" return error_of_geo_to_meter_approx_(geo_origin, latitude_to_meter, longitude_to_meter, geo_coords_arr_rad, lambda coord,origin: coord.toSEZ(origin)) def error_of_geo_to_meter_approx_NED(geo_origin, latitude_to_meter, longitude_to_meter, geo_coords_arr_rad):
67
67
224
27
40
xaedes/python-geo-coords-converter
src/geo_coords_converter/approx/meter.py
Python
error_of_geo_to_meter_approx_NED
error_of_geo_to_meter_approx_NED
290
308
290
290
35bcd493515b8a753ec8d5a49232ce73a0284963
bigcode/the-stack
train
05704f6b69bec583e69241fe
train
function
def transform_geo_to_meter(geo_origin, latitude_to_meter, longitude_to_meter, geo_coords_arr_rad): """ Transforms geo coordinates to metric carthesian coordinate system :param geo_origin: The geo origin :param latitude_to_meter: The latitude to meter conversion factor :para...
def transform_geo_to_meter(geo_origin, latitude_to_meter, longitude_to_meter, geo_coords_arr_rad):
""" Transforms geo coordinates to metric carthesian coordinate system :param geo_origin: The geo origin :param latitude_to_meter: The latitude to meter conversion factor :param longitude_to_meter: The longitude to meter conversion factor :param geo_coords_arr...
geo_origin.latitude], [0,1/longitude_to_meter,0,geo_origin.longitude], [0,0,1,0], [0,0,0,1], ]) def transform_geo_to_meter(geo_origin, latitude_to_meter, longitude_to_meter, geo_coords_arr_rad):
64
64
202
22
42
xaedes/python-geo-coords-converter
src/geo_coords_converter/approx/meter.py
Python
transform_geo_to_meter
transform_geo_to_meter
179
195
179
179
7e77544422567f5658510354bfcf1fcfe37f3dbb
bigcode/the-stack
train
8329e9c98bda65abfdd946d5
train
function
def approximate_geo_to_meter(geo_origin, geo_coords_arr_rad, carthesian_coords_arr_meter): """ Compute best latitude/longitude to meter factors for linear approximation of geo to carthesian from point correspondences. :param geo_origin: The geo coordinate where to center ...
def approximate_geo_to_meter(geo_origin, geo_coords_arr_rad, carthesian_coords_arr_meter):
""" Compute best latitude/longitude to meter factors for linear approximation of geo to carthesian from point correspondences. :param geo_origin: The geo coordinate where to center the approximation :param geo_coords_arr_...
import __version__ __author__ = "Martin Huenermund" __copyright__ = "Martin Huenermund" __license__ = "mit" _logger = logging.getLogger(__name__) import numpy as np from geo_coords_converter import coords from geo_coords_converter.utils import transform3d def approximate_geo_to_meter(geo_origin, geo_coords_arr_rad,...
82
82
274
21
60
xaedes/python-geo-coords-converter
src/geo_coords_converter/approx/meter.py
Python
approximate_geo_to_meter
approximate_geo_to_meter
24
48
24
24
114278be539df33b51f2ad2347b999197e1c80e9
bigcode/the-stack
train
a7bf659f8817ac0c44d55063
train
function
def approximate_geo_to_meter_SEZ(geo_origin, geo_coords_arr_rad): """ Compute best latitude/longitude to meter factors for linear approximation of geo to carthesian from geo coordinates and corresponding SEZ coordinates. :param geo_origin: The geo coordinate where to center the ...
def approximate_geo_to_meter_SEZ(geo_origin, geo_coords_arr_rad):
""" Compute best latitude/longitude to meter factors for linear approximation of geo to carthesian from geo coordinates and corresponding SEZ coordinates. :param geo_origin: The geo coordinate where to center the approximation :param geo_c...
odeticCoordinate(*coord), geo_origin).position * km_to_m for coord in geo_coords_arr_rad ]) return approximate_geo_to_meter(geo_origin, geo_coords_arr_rad, carthesian_coords_meter) def approximate_geo_to_meter_SEZ(geo_origin, geo_coords_arr_rad):
64
64
181
16
48
xaedes/python-geo-coords-converter
src/geo_coords_converter/approx/meter.py
Python
approximate_geo_to_meter_SEZ
approximate_geo_to_meter_SEZ
79
97
79
79
ad94b25a938106b3a1186e8fc32457cc4e3377ce
bigcode/the-stack
train
ab706a51cd8508dfe7bba0b9
train
function
def error_of_geo_to_meter_approx(geo_origin, latitude_to_meter, longitude_to_meter, geo_coords_arr_rad, carthesian_coords_meter): """ Computes error of linear transformation approximation in comparision with point correspondences. :param geo_origin: The geo origin :param ...
def error_of_geo_to_meter_approx(geo_origin, latitude_to_meter, longitude_to_meter, geo_coords_arr_rad, carthesian_coords_meter):
""" Computes error of linear transformation approximation in comparision with point correspondences. :param geo_origin: The geo origin :param latitude_to_meter: The latitude to meter conversion factor :param longi...
) :returns: The geo coordinates in radians :rtype: numpy.ndarray with shape(N,3) """ return transform3d(tf_geo_meter(geo_origin, latitude_to_meter, longitude_to_meter), geo_coords_arr_rad) def error_of_geo_to_meter_approx(geo_origin, latitude_to_meter, longitude_to_meter, geo_coords_arr_rad, ...
84
84
281
31
53
xaedes/python-geo-coords-converter
src/geo_coords_converter/approx/meter.py
Python
error_of_geo_to_meter_approx
error_of_geo_to_meter_approx
215
239
215
215
f1d0d64231d45dcc0f27b195e6e8c8f0d6df7099
bigcode/the-stack
train
10ca8c3ec3c64f4350d41f5f
train
function
def error_stats(error_arr, axis=0): """ Computes statistics for array of errors. :param error_arr: The error arr :param axis: The axis :type error_arr: numpy.ndarray :type axis: number :returns: dict containing stats of error array :rtype: ...
def error_stats(error_arr, axis=0):
""" Computes statistics for array of errors. :param error_arr: The error arr :param axis: The axis :type error_arr: numpy.ndarray :type axis: number :returns: dict containing stats of error array :rtype: dict """ return { ...
:rtype: numpy.ndarray with shape(N,3) """ return error_of_geo_to_meter_approx_(geo_origin, latitude_to_meter, longitude_to_meter, geo_coords_arr_rad, lambda coord,origin: coord.toENU(origin)) def error_stats(error_arr, axis=0):
64
64
191
10
54
xaedes/python-geo-coords-converter
src/geo_coords_converter/approx/meter.py
Python
error_stats
error_stats
329
349
329
329
e35803e78cd58c962f72890b42c5f7bebed4c99e
bigcode/the-stack
train
522ca91f6cbf3ff83446c8b0
train
function
def tf_geo_meter(geo_origin, latitude_to_meter, longitude_to_meter): """ Transformation matrix transforming from meter to geo coordinates. :param geo_origin: The geo origin :param latitude_to_meter: The latitude to meter conversion factor :param longitude_to_meter: Th...
def tf_geo_meter(geo_origin, latitude_to_meter, longitude_to_meter):
""" Transformation matrix transforming from meter to geo coordinates. :param geo_origin: The geo origin :param latitude_to_meter: The latitude to meter conversion factor :param longitude_to_meter: The longitude to meter conversion factor :type geo_origin: ...
geo_origin.latitude*latitude_to_meter], [0,longitude_to_meter,0,-geo_origin.longitude*longitude_to_meter], [0,0,1,0], [0,0,0,1], ]) def tf_geo_meter(geo_origin, latitude_to_meter, longitude_to_meter):
64
64
192
16
48
xaedes/python-geo-coords-converter
src/geo_coords_converter/approx/meter.py
Python
tf_geo_meter
tf_geo_meter
158
177
158
158
c685dbf5b79297c04c3f997dcfb495629a88f172
bigcode/the-stack
train
ebc852186a4140e369a1b908
train
function
def error_of_geo_to_meter_approx_ENU(geo_origin, latitude_to_meter, longitude_to_meter, geo_coords_arr_rad): """ Computes error of linear transformation approximation with point correspondences to ENU coordinates. :param geo_origin: The geo origin :param latitude_to_meter: The ...
def error_of_geo_to_meter_approx_ENU(geo_origin, latitude_to_meter, longitude_to_meter, geo_coords_arr_rad):
""" Computes error of linear transformation approximation with point correspondences to ENU coordinates. :param geo_origin: The geo origin :param latitude_to_meter: The latitude to meter :param longitude_to_meter: The longitude to meter :param geo_coords_arr_...
return error_of_geo_to_meter_approx_(geo_origin, latitude_to_meter, longitude_to_meter, geo_coords_arr_rad, lambda coord,origin: coord.toNED(origin)) def error_of_geo_to_meter_approx_ENU(geo_origin, latitude_to_meter, longitude_to_meter, geo_coords_arr_rad):
66
66
222
27
39
xaedes/python-geo-coords-converter
src/geo_coords_converter/approx/meter.py
Python
error_of_geo_to_meter_approx_ENU
error_of_geo_to_meter_approx_ENU
310
327
310
310
20aa8a799c55e30e8c98f9d9b944600164de110e
bigcode/the-stack
train
0ac4205d61abdf5c5da2e1be
train
function
def approximate_geo_to_meter_(geo_origin, geo_coords_arr_rad, geo_to_carth_func): """ Compute best latitude/longitude to meter factors for linear approximation of geo to carthesian from geo coordinates and geo coordinate conversion function. :param geo_origin: The geo coordinate w...
def approximate_geo_to_meter_(geo_origin, geo_coords_arr_rad, geo_to_carth_func):
""" Compute best latitude/longitude to meter factors for linear approximation of geo to carthesian from geo coordinates and geo coordinate conversion function. :param geo_origin: The geo coordinate where to center the approximation :param ...
latlon = np.array(geo_coords_arr_rad[:,:2]) - (geo_origin.latitude, geo_origin.longitude) dxy = carthesian_coords_arr_meter[:,:2] latitude_to_meter, longitude_to_meter = (dxy / dlatlon).mean(axis=0) return latitude_to_meter, longitude_to_meter def approximate_geo_to_meter_(geo_origin, geo_coords_arr_rad, ge...
90
90
303
20
69
xaedes/python-geo-coords-converter
src/geo_coords_converter/approx/meter.py
Python
approximate_geo_to_meter_
approximate_geo_to_meter_
50
77
50
50
885cba8e21f61a475f6a000ce2f3220442484e71
bigcode/the-stack
train
821564644150f4bdbffd022b
train
function
def error_of_geo_to_meter_approx_SEZ(geo_origin, latitude_to_meter, longitude_to_meter, geo_coords_arr_rad): """ Computes error of linear transformation approximation with point correspondences to SEZ coordinates. :param geo_origin: The geo origin :param latitude_to_meter: ...
def error_of_geo_to_meter_approx_SEZ(geo_origin, latitude_to_meter, longitude_to_meter, geo_coords_arr_rad):
""" Computes error of linear transformation approximation with point correspondences to SEZ coordinates. :param geo_origin: The geo origin :param latitude_to_meter: The latitude to meter :param longitude_to_meter: The longitude to meter :param geo_coords_...
in geo_coords_arr_rad ]) return error_of_geo_to_meter_approx(geo_origin, latitude_to_meter, longitude_to_meter, geo_coords_arr_rad, carthesian_coords_meter) def error_of_geo_to_meter_approx_SEZ(geo_origin, latitude_to_meter, longitude_to_meter, geo_coords_arr_rad):
67
67
224
27
40
xaedes/python-geo-coords-converter
src/geo_coords_converter/approx/meter.py
Python
error_of_geo_to_meter_approx_SEZ
error_of_geo_to_meter_approx_SEZ
270
288
270
270
f879b66c032ba2a5cef784d6f7c0e1d3659b7385
bigcode/the-stack
train
fdf556f55a450658ecf91550
train
function
def approximate_geo_to_meter_NED(geo_origin, geo_coords_arr_rad): """ Compute best latitude/longitude to meter factors for linear approximation of geo to carthesian from geo coordinates and corresponding NED coordinates. :param geo_origin: The geo origin :param geo_coords_arr...
def approximate_geo_to_meter_NED(geo_origin, geo_coords_arr_rad):
""" Compute best latitude/longitude to meter factors for linear approximation of geo to carthesian from geo coordinates and corresponding NED coordinates. :param geo_origin: The geo origin :param geo_coords_arr_rad: The geo coordinates in radians :type geo_origin: ...
latitude_to_meter, longitude_to_meter :rtype: number """ return approximate_geo_to_meter_( geo_origin, geo_coords_arr_rad, lambda coord,origin: coord.toSEZ(origin)) def approximate_geo_to_meter_NED(geo_origin, geo_coords_arr_rad):
64
64
174
16
48
xaedes/python-geo-coords-converter
src/geo_coords_converter/approx/meter.py
Python
approximate_geo_to_meter_NED
approximate_geo_to_meter_NED
99
115
99
99
ed6b5dddb7b92478349bb06448f0a25fa365c90b
bigcode/the-stack
train
6f7f725d1bca342c8f65e748
train
function
def approximate_geo_to_meter_ENU(geo_origin, geo_coords_arr_rad): """ Compute best latitude/longitude to meter factors for linear approximation of geo to carthesian from geo coordinates and corresponding ENU coordinates. :param geo_origin: The geo origin :param geo_coords_arr...
def approximate_geo_to_meter_ENU(geo_origin, geo_coords_arr_rad):
""" Compute best latitude/longitude to meter factors for linear approximation of geo to carthesian from geo coordinates and corresponding ENU coordinates. :param geo_origin: The geo origin :param geo_coords_arr_rad: The geo coordinates radians :type geo_origin: ...
latitude_to_meter, longitude_to_meter :rtype: number """ return approximate_geo_to_meter_( geo_origin, geo_coords_arr_rad, lambda coord,origin: coord.toNED(origin)) def approximate_geo_to_meter_ENU(geo_origin, geo_coords_arr_rad):
64
64
172
16
48
xaedes/python-geo-coords-converter
src/geo_coords_converter/approx/meter.py
Python
approximate_geo_to_meter_ENU
approximate_geo_to_meter_ENU
117
133
117
117
c25d1e22fad75030fb704c8563347076e328df60
bigcode/the-stack
train
471f847c9d385fe16148e510
train
function
def tf_meter_geo(geo_origin, latitude_to_meter, longitude_to_meter): """ Transformation matrix transforming from geo coordinates to meter. :param geo_origin: The geo origin :param latitude_to_meter: The latitude to meter conversion factor :param longitude_to_meter: Th...
def tf_meter_geo(geo_origin, latitude_to_meter, longitude_to_meter):
""" Transformation matrix transforming from geo coordinates to meter. :param geo_origin: The geo origin :param latitude_to_meter: The latitude to meter conversion factor :param longitude_to_meter: The longitude to meter conversion factor :type geo_origin: ...
latitude_to_meter, longitude_to_meter :rtype: number """ return approximate_geo_to_meter_( geo_origin, geo_coords_arr_rad, lambda coord,origin: coord.toENU(origin)) def tf_meter_geo(geo_origin, latitude_to_meter, longitude_to_meter):
63
64
196
16
47
xaedes/python-geo-coords-converter
src/geo_coords_converter/approx/meter.py
Python
tf_meter_geo
tf_meter_geo
137
156
137
137
a47c450073cdca4ec59edfda069406bcd2a1bc8a
bigcode/the-stack
train
fef355eb7bbe76796f5ea7a8
train
function
def error_of_geo_to_meter_approx_(geo_origin, latitude_to_meter, longitude_to_meter, geo_coords_arr_rad, geo_to_carth_func): """ Computes error of linear transformation approximation with implicit point correspondences. :param geo_origin: The geo origin :param latitude_to_met...
def error_of_geo_to_meter_approx_(geo_origin, latitude_to_meter, longitude_to_meter, geo_coords_arr_rad, geo_to_carth_func):
""" Computes error of linear transformation approximation with implicit point correspondences. :param geo_origin: The geo origin :param latitude_to_meter: The latitude to meter conversion factor :param longitude_to_meter: The longitude to meter conversion factor ...
returns: errors of linear transformation in comparision with point correspondences :rtype: numpy.ndarray with shape(N,3) """ meter = transform_geo_to_meter(geo_origin, latitude_to_meter, longitude_to_meter, geo_coords_arr_rad) error = carthesian_coords_meter - meter return erro...
102
102
343
31
70
xaedes/python-geo-coords-converter
src/geo_coords_converter/approx/meter.py
Python
error_of_geo_to_meter_approx_
error_of_geo_to_meter_approx_
241
268
241
241
fdd8dd0dda027361b71b29e402e7701aaa84ff06
bigcode/the-stack
train
0836d87442a9053b9e98d4d5
train
function
def transform_meter_to_geo(geo_origin, latitude_to_meter, longitude_to_meter, meter_arr): """ Transforms metric carthesian coordinates to geodetic coordinate system :param geo_origin: The geo origin :param latitude_to_meter: The latitude to meter conversion factor :param ...
def transform_meter_to_geo(geo_origin, latitude_to_meter, longitude_to_meter, meter_arr):
""" Transforms metric carthesian coordinates to geodetic coordinate system :param geo_origin: The geo origin :param latitude_to_meter: The latitude to meter conversion factor :param longitude_to_meter: The longitude to meter conversion factor :param meter_arr...
coordinates in meter :rtype: numpy.ndarray with shape(N,3) """ return transform3d(tf_meter_geo(geo_origin, latitude_to_meter, longitude_to_meter), geo_coords_arr_rad) def transform_meter_to_geo(geo_origin, latitude_to_meter, longitude_to_meter, meter_arr):
64
64
198
20
44
xaedes/python-geo-coords-converter
src/geo_coords_converter/approx/meter.py
Python
transform_meter_to_geo
transform_meter_to_geo
197
213
197
197
44b4f8deba0f2dc3bc25a026c7f81ac582e610f8
bigcode/the-stack
train
06ce0f0cc780c7f05e769e11
train
class
class ps_procmark(ps_object): def __init__(self): self.value = 'procmark' self.type = self.__class__.__name__[3:] + "type"
class ps_procmark(ps_object):
def __init__(self): self.value = 'procmark' self.type = self.__class__.__name__[3:] + "type"
access) return psstring + 'end ' def __repr__(self): return "<dict>" class ps_mark(ps_object): def __init__(self): self.value = 'mark' self.type = self.__class__.__name__[3:] + "type" class ps_procmark(ps_object):
64
64
37
7
57
anntzer/fonttools
Lib/fontTools/misc/psOperators.py
Python
ps_procmark
ps_procmark
177
180
177
177
85be8d29184ab3decaf5774f31a5c755d9601d12
bigcode/the-stack
train
b5da9ff649c81b921848f47c
train
class
class ps_real(ps_object): def __str__(self): return repr(self.value)
class ps_real(ps_object):
def __str__(self): return repr(self.value)
return 'true' else: return 'false' class ps_string(ps_object): def __str__(self): return "(%s)" % repr(self.value)[1:-1] class ps_integer(ps_object): def __str__(self): return repr(self.value) class ps_real(ps_object):
64
64
18
6
58
anntzer/fonttools
Lib/fontTools/misc/psOperators.py
Python
ps_real
ps_real
201
203
201
201
472a38db151ed44a14664ba4458ede2a691026b4
bigcode/the-stack
train
e7443339c50c63c53d8fe85a
train
class
class ps_array(ps_object): def __str__(self): psstring = '[' for i in range(len(self.value)): item = self.value[i] access = _accessstrings[item.access] if access: access = ' ' + access if i: psstring = psstring + ' ' + str(item) + access else: psstring = psstring + str(item) + access r...
class ps_array(ps_object):
def __str__(self): psstring = '[' for i in range(len(self.value)): item = self.value[i] access = _accessstrings[item.access] if access: access = ' ' + access if i: psstring = psstring + ' ' + str(item) + access else: psstring = psstring + str(item) + access return psstring + ']' def _...
' class ps_name(ps_object): literal = 0 def __str__(self): if self.literal: return '/' + self.value else: return self.value class ps_literal(ps_object): def __str__(self): return '/' + self.value class ps_array(ps_object):
64
64
111
6
57
anntzer/fonttools
Lib/fontTools/misc/psOperators.py
Python
ps_array
ps_array
56
70
56
56
4d0dd72bc483dc2f64c5edb479b139bcd5a1b282
bigcode/the-stack
train
9d4a007934c847812eac7a1f
train
function
def _type1_Encoding_repr(encoding, access): encoding = encoding.value psstring = "/Encoding 256 array\n0 1 255 {1 index exch /.notdef put} for\n" for i in range(256): name = encoding[i].value if name != '.notdef': psstring = psstring + "dup %d /%s put\n" % (i, name) return psstring + access + "def\n"
def _type1_Encoding_repr(encoding, access):
encoding = encoding.value psstring = "/Encoding 256 array\n0 1 255 {1 index exch /.notdef put} for\n" for i in range(256): name = encoding[i].value if name != '.notdef': psstring = psstring + "dup %d /%s put\n" % (i, name) return psstring + access + "def\n"
Encoding': psstring = psstring + _type1_Encoding_repr(value, access) else: psstring = psstring + "/%s %s %sdef\n" % (str(key), str(value), access) return psstring def _type1_Encoding_repr(encoding, access):
64
64
100
12
51
anntzer/fonttools
Lib/fontTools/misc/psOperators.py
Python
_type1_Encoding_repr
_type1_Encoding_repr
116
123
116
116
d8e7c3c4dd6e784a74c902761a6536c50b282197
bigcode/the-stack
train
6ca91826a71091168c9f99c2
train
function
def _type1_item_repr(key, value): psstring = "" access = _accessstrings[value.access] if access: access = access + ' ' if key == 'CharStrings': psstring = psstring + "/%s %s def\n" % (key, _type1_CharString_repr(value.value)) elif key == 'Encoding': psstring = psstring + _type1_Encoding_repr(value, access) ...
def _type1_item_repr(key, value):
psstring = "" access = _accessstrings[value.access] if access: access = access + ' ' if key == 'CharStrings': psstring = psstring + "/%s %s def\n" % (key, _type1_CharString_repr(value.value)) elif key == 'Encoding': psstring = psstring + _type1_Encoding_repr(value, access) else: psstring = psstring + "/%s...
Weight", "ItalicAngle", "isFixedPitch", "UnderlinePosition", "UnderlineThickness" ] _type1_post_eexec_order = [ "Private", "CharStrings", "FID" ] def _type1_item_repr(key, value):
64
64
126
10
54
anntzer/fonttools
Lib/fontTools/misc/psOperators.py
Python
_type1_item_repr
_type1_item_repr
103
114
103
103
e0a18e1f268cd52899b8230ca5208c3d37a655fa
bigcode/the-stack
train
814e1ce79813805b54d81955
train
class
class ps_null(ps_object): def __init__(self): self.type = self.__class__.__name__[3:] + "type"
class ps_null(ps_object):
def __init__(self): self.type = self.__class__.__name__[3:] + "type"
.value = 'mark' self.type = self.__class__.__name__[3:] + "type" class ps_procmark(ps_object): def __init__(self): self.value = 'procmark' self.type = self.__class__.__name__[3:] + "type" class ps_null(ps_object):
64
64
28
6
58
anntzer/fonttools
Lib/fontTools/misc/psOperators.py
Python
ps_null
ps_null
182
184
182
182
683e1479f5a676b903050820d84117d65eae819c
bigcode/the-stack
train
1ffe4501392ac161c7847ddb
train
function
def _type1_CharString_repr(charstrings): items = sorted(charstrings.items()) return 'xxx'
def _type1_CharString_repr(charstrings):
items = sorted(charstrings.items()) return 'xxx'
range(256): name = encoding[i].value if name != '.notdef': psstring = psstring + "dup %d /%s put\n" % (i, name) return psstring + access + "def\n" def _type1_CharString_repr(charstrings):
64
64
22
11
53
anntzer/fonttools
Lib/fontTools/misc/psOperators.py
Python
_type1_CharString_repr
_type1_CharString_repr
125
127
125
125
28c7bc662d4c3bfd51d4ec5870dce931c703c3b8
bigcode/the-stack
train
36d7a249da4d359ca8361c04
train
class
class ps_name(ps_object): literal = 0 def __str__(self): if self.literal: return '/' + self.value else: return self.value
class ps_name(ps_object):
literal = 0 def __str__(self): if self.literal: return '/' + self.value else: return self.value
self): psstring = '{' for i in range(len(self.value)): if i: psstring = psstring + ' ' + str(self.value[i]) else: psstring = psstring + str(self.value[i]) return psstring + '}' class ps_name(ps_object):
64
64
38
6
58
anntzer/fonttools
Lib/fontTools/misc/psOperators.py
Python
ps_name
ps_name
44
50
44
44
e4f6b6f210f399b87a5e537be5433dce272275f9
bigcode/the-stack
train
c404f94916cdeebe0b13d53e
train
class
class ps_procedure(ps_object): literal = 0 def __repr__(self): return "<procedure>" def __str__(self): psstring = '{' for i in range(len(self.value)): if i: psstring = psstring + ' ' + str(self.value[i]) else: psstring = psstring + str(self.value[i]) return psstring + '}'
class ps_procedure(ps_object):
literal = 0 def __repr__(self): return "<procedure>" def __str__(self): psstring = '{' for i in range(len(self.value)): if i: psstring = psstring + ' ' + str(self.value[i]) else: psstring = psstring + str(self.value[i]) return psstring + '}'
0 def __init__(self, name, function): self.name = name self.function = function self.type = self.__class__.__name__[3:] + "type" def __repr__(self): return "<operator %s>" % self.name class ps_procedure(ps_object):
64
64
86
7
56
anntzer/fonttools
Lib/fontTools/misc/psOperators.py
Python
ps_procedure
ps_procedure
31
42
31
31
18949351018376482c1bd5d5368b8e66490b7c9a
bigcode/the-stack
train
4e1bfd56b1560c4bcad58b5c
train
class
class ps_font(ps_object): def __str__(self): psstring = "%d dict dup begin\n" % len(self.value) for key in _type1_pre_eexec_order: try: value = self.value[key] except KeyError: pass else: psstring = psstring + _type1_item_repr(key, value) items = sorted(self.value.items()) for key, value i...
class ps_font(ps_object):
def __str__(self): psstring = "%d dict dup begin\n" % len(self.value) for key in _type1_pre_eexec_order: try: value = self.value[key] except KeyError: pass else: psstring = psstring + _type1_item_repr(key, value) items = sorted(self.value.items()) for key, value in items: if key not in ...
): name = encoding[i].value if name != '.notdef': psstring = psstring + "dup %d /%s put\n" % (i, name) return psstring + access + "def\n" def _type1_CharString_repr(charstrings): items = sorted(charstrings.items()) return 'xxx' class ps_font(ps_object):
78
78
260
6
72
anntzer/fonttools
Lib/fontTools/misc/psOperators.py
Python
ps_font
ps_font
129
154
129
129
cf4fcb1d17bde704634697e281d71c106743b996
bigcode/the-stack
train
50ae1741358b81cf3c13d535
train
class
class ps_operator(ps_object): literal = 0 def __init__(self, name, function): self.name = name self.function = function self.type = self.__class__.__name__[3:] + "type" def __repr__(self): return "<operator %s>" % self.name
class ps_operator(ps_object):
literal = 0 def __init__(self, name, function): self.name = name self.function = function self.type = self.__class__.__name__[3:] + "type" def __repr__(self): return "<operator %s>" % self.name
def __init__(self, value): self.value = value self.type = self.__class__.__name__[3:] + "type" def __repr__(self): return "<%s %s>" % (self.__class__.__name__[3:], repr(self.value)) class ps_operator(ps_object):
64
64
67
6
58
anntzer/fonttools
Lib/fontTools/misc/psOperators.py
Python
ps_operator
ps_operator
20
29
20
21
6ef26c8937c1e023607b761c5315abbab8829979
bigcode/the-stack
train
eadeea2ee4e74013eb04de43
train
class
class ps_integer(ps_object): def __str__(self): return repr(self.value)
class ps_integer(ps_object):
def __str__(self): return repr(self.value)
" class ps_boolean(ps_object): def __str__(self): if self.value: return 'true' else: return 'false' class ps_string(ps_object): def __str__(self): return "(%s)" % repr(self.value)[1:-1] class ps_integer(ps_object):
64
64
18
6
58
anntzer/fonttools
Lib/fontTools/misc/psOperators.py
Python
ps_integer
ps_integer
197
199
197
197
72c66a4043fc6a7564dc7a80fa5aa4392ac35446
bigcode/the-stack
train