index
int64
0
50.7k
project_path
stringclasses
279 values
completion_path
stringlengths
57
199
signature_postion
stringlengths
3
11
class_position
stringlengths
3
11
function_name
stringlengths
1
62
class_name
stringlengths
0
55
body_position
stringlengths
3
11
body_position_with_comments
stringlengths
3
11
masked_class
stringlengths
14
8.32k
masked_class_with_comment
stringlengths
14
8.32k
func_body
stringlengths
9
6.72k
func_body_with_comment
stringlengths
9
6.72k
len_func_body
int64
1
643
len_input
int64
10
2.02k
len_output
int64
4
1.9k
total
int64
20
2.05k
file_code
stringlengths
14
442k
file_code_with_comment
stringlengths
14
442k
36,418
/home/hieuvd/dung_repo/raw/stars_02/google_rekall/rekall
/home/hieuvd/dung_repo/raw/stars_02/google_rekall/rekall/tools/layout_expert/layout_expert/preprocessing_visitors/macro_expression_evaluator_visitor.py
39,40
13,61
visit_c_function_call
MacroExpressionEvaluatorVisitor
40,49
40,49
class MacroExpressionEvaluatorVisitor(object): """A class for evaluating macros given as AST tree.""" _C_IDENTIFIER_OR_LITERAL_PATTERN = re.compile('^[a-zA-Z0-9_]+$') _C_INT_PATTERN = re.compile( '^(?P<number>(0x)?[0-9]+)(u|U)?(l|ll|L|LL)?$', ) def __init__(self, macros): self.macr...
class MacroExpressionEvaluatorVisitor(object): """A class for evaluating macros given as AST tree.""" _C_IDENTIFIER_OR_LITERAL_PATTERN = re.compile('^[a-zA-Z0-9_]+$') _C_INT_PATTERN = re.compile( '^(?P<number>(0x)?[0-9]+)(u|U)?(l|ll|L|LL)?$', ) def __init__(self, macros): self.macr...
# Macros should have been handled by the macro expander. function = self.macros.functions.get(function_call.function_name) if function is None: raise c_ast.IrreducibleFunction( "Function %s not known." % function_call.function_name) # Call arithmetic function...
# Macros should have been handled by the macro expander. function = self.macros.functions.get(function_call.function_name) if function is None: raise c_ast.IrreducibleFunction( "Function %s not known." % function_call.function_name) # Call arithmetic function...
32
456
108
564
"""A module containing a class for evaluating macros given as AST tree.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import re from layout_expert.c_ast import c_ast class MacroExpressionEvaluatorVisitor(objec...
"""A module containing a class for evaluating macros given as AST tree.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import re from layout_expert.c_ast import c_ast class MacroExpressionEvaluatorVisitor(objec...
36,419
/home/hieuvd/dung_repo/raw/stars_02/google_rekall/rekall
/home/hieuvd/dung_repo/raw/stars_02/google_rekall/rekall/tools/layout_expert/layout_expert/preprocessing_visitors/preprocessing_visitor.py
68,69
35,123
visit_error
PreprocessingVisitor
69,71
69,71
class PreprocessingVisitor(object): """A class representing a Preprocessing Visitor for Pre-AST trees. Run this visitor on the PreAST to populate the Macros() manager and expand the TEXT nodes. """ def __init__(self, macros, progress_cb=None): self.progress_cb = progress_cb or (lambda *_: ...
class PreprocessingVisitor(object): """A class representing a Preprocessing Visitor for Pre-AST trees. Run this visitor on the PreAST to populate the Macros() manager and expand the TEXT nodes. """ def __init__(self, macros, progress_cb=None): self.progress_cb = progress_cb or (lambda *_: ...
raise PreprocessingException(error)
raise PreprocessingException(error)
2
927
12
939
# -*- coding: utf-8 -*- # Copyright (C) 2016 Google Inc. All Rights Reserved. # # Authors: # Arkadiusz Socała <as277575@mimuw.edu.pl> # Michael Cohen <scudette@google.com> # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obt...
# -*- coding: utf-8 -*- # Copyright (C) 2016 Google Inc. All Rights Reserved. # # Authors: # Arkadiusz Socała <as277575@mimuw.edu.pl> # Michael Cohen <scudette@google.com> # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obt...
36,420
/home/hieuvd/dung_repo/raw/stars_02/google_rekall/rekall
/home/hieuvd/dung_repo/raw/stars_02/google_rekall/rekall/tools/layout_expert/layout_expert/preprocessing_visitors/to_string_visitor.py
53,54
34,60
visit_composite_block
ToStringVisitor
54,58
54,58
class ToStringVisitor(object): """A visitor class that transforms a simple Pre-AST to string. Works on already prepared Pre-AST so it can only contain a reduced set of nodes. This is used to convert the preprocessed AST (Which should only contain TextBlock nodes) to the flat pre-processed C file. ...
class ToStringVisitor(object): """A visitor class that transforms a simple Pre-AST to string. Works on already prepared Pre-AST so it can only contain a reduced set of nodes. This is used to convert the preprocessed AST (Which should only contain TextBlock nodes) to the flat pre-processed C file. ...
for element in composite_block.content: if element is not None: self.to_string(element, parts)
for element in composite_block.content: if element is not None: self.to_string(element, parts)
11
220
36
256
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2016 Google Inc. All Rights Reserved. # # Authors: # Arkadiusz Socała <as277575@mimuw.edu.pl> # Michael Cohen <scudette@google.com> # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2016 Google Inc. All Rights Reserved. # # Authors: # Arkadiusz Socała <as277575@mimuw.edu.pl> # Michael Cohen <scudette@google.com> # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the...
36,421
/home/hieuvd/dung_repo/raw/stars_02/google_rekall/rekall
/home/hieuvd/dung_repo/raw/stars_02/google_rekall/rekall/tools/layout_expert/layout_expert/serialization/json_serialization_test.py
89,90
41,162
test_serialize_mock_subclass_without_permission_for_superclass
TestJsonSerialization
90,97
90,97
class TestJsonSerialization(unittest.TestCase): def setUp(self): self.encoder = json_serialization.create_encoder() self.decoder = json_serialization.create_decoder() json_serialization.DataContainerObjectRenderer.set_safe_constructors( data_container.DataContainer, MockSubclass...
class TestJsonSerialization(unittest.TestCase): def setUp(self): self.encoder = json_serialization.create_encoder() self.decoder = json_serialization.create_decoder() json_serialization.DataContainerObjectRenderer.set_safe_constructors( data_container.DataContainer, MockSubclass...
json_serialization.DataContainerObjectRenderer.set_safe_constructors( MockSubclass, exclusive=True) original = MockSubclass('some_other_value', field3=24) encoded = self.encoder.Encode(original) decoded = self.decoder.Decode(encoded) self.assertEqual(decoded, original...
json_serialization.DataContainerObjectRenderer.set_safe_constructors( MockSubclass, exclusive=True) original = MockSubclass('some_other_value', field3=24) encoded = self.encoder.Encode(original) decoded = self.decoder.Decode(encoded) self.assertEqual(decoded, original...
15
1,497
98
1,595
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2016 Google Inc. All Rights Reserved. # # Authors: # Arkadiusz Socała <as277575@mimuw.edu.pl> # Michael Cohen <scudette@google.com> # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2016 Google Inc. All Rights Reserved. # # Authors: # Arkadiusz Socała <as277575@mimuw.edu.pl> # Michael Cohen <scudette@google.com> # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the...
36,422
/home/hieuvd/dung_repo/raw/stars_02/google_rekall/rekall
/home/hieuvd/dung_repo/raw/stars_02/google_rekall/rekall/tools/layout_expert/layout_expert/visitors/expression_evaluator_visitor.py
63,64
41,82
visit_c_variable
ExpressionEvaluatorVisitor
64,73
64,73
class ExpressionEvaluatorVisitor(object): """A class for evaluating expressions given as AST tree.""" def __init__(self, type_manager=None): self.type_manager = type_manager def evaluate(self, expression): if isinstance(expression, visitor_mixin.VisitorMixin): return expression...
class ExpressionEvaluatorVisitor(object): """A class for evaluating expressions given as AST tree.""" def __init__(self, type_manager=None): self.type_manager = type_manager def evaluate(self, expression): if isinstance(expression, visitor_mixin.VisitorMixin): return expression...
name = variable.name result = self.type_manager.variables.get(name) if result is None: raise c_ast.IrreducibleFunction( "Unable to evaluate expression since %s has no value." % name) # Continue to resolve the variable AST. return result.accept(self)
name = variable.name result = self.type_manager.variables.get(name) if result is None: raise c_ast.IrreducibleFunction( "Unable to evaluate expression since %s has no value." % name) # Continue to resolve the variable AST. return result.accept(self)
32
322
92
414
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2016 Google Inc. All Rights Reserved. # # Authors: # Arkadiusz Socała <as277575@mimuw.edu.pl> # Michael Cohen <scudette@google.com> # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2016 Google Inc. All Rights Reserved. # # Authors: # Arkadiusz Socała <as277575@mimuw.edu.pl> # Michael Cohen <scudette@google.com> # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the...
36,423
/home/hieuvd/dung_repo/raw/stars_02/google_rekall/rekall
/home/hieuvd/dung_repo/raw/stars_02/google_rekall/rekall/tools/layout_expert/layout_expert/visitors/expression_evaluator_visitor_test.py
102,103
34,108
test_visit_literal
TestExpressionEvaluatorVisitor
103,108
103,108
class TestExpressionEvaluatorVisitor(unittest.TestCase): def f1(self, evaluator, x, y, **_): _ = evaluator self.x.append(x) self.y.append(y) return 33 def f2(self, evaluator, z, **_): _ = evaluator self.z.append(z) return 42 def setUp(self): ...
class TestExpressionEvaluatorVisitor(unittest.TestCase): def f1(self, evaluator, x, y, **_): _ = evaluator self.x.append(x) self.y.append(y) return 33 def f2(self, evaluator, z, **_): _ = evaluator self.z.append(z) return 42 def setUp(self): ...
literal = c_ast.CLiteral('value') actual = self.expression_evaluator.evaluate(literal) self.assertEqual(actual, 'value')
literal = c_ast.CLiteral('value') actual = self.expression_evaluator.evaluate(literal) self.assertEqual(actual, 'value')
8
647
49
696
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2016 Google Inc. All Rights Reserved. # # Authors: # Arkadiusz Socała <as277575@mimuw.edu.pl> # Michael Cohen <scudette@google.com> # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2016 Google Inc. All Rights Reserved. # # Authors: # Arkadiusz Socała <as277575@mimuw.edu.pl> # Michael Cohen <scudette@google.com> # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the...
36,425
/home/hieuvd/dung_repo/raw/stars_02/google_rekall/rekall
/home/hieuvd/dung_repo/raw/stars_02/google_rekall/rekall/tools/layout_expert/layout_expert/visitors/type_collecting_visitor.py
41,42
31,66
get_dependencies
DependencyVisitor
43,46
42,46
class DependencyVisitor(visitor_mixin.CASTVisitorWalker): """Recursively collect the dependent types. This calls back into the type manager to discover types that are not already known. """ def __init__(self, type_manager): self.type_manager = type_manager def get_dependencies(self, n...
class DependencyVisitor(visitor_mixin.CASTVisitorWalker): """Recursively collect the dependent types. This calls back into the type manager to discover types that are not already known. """ def __init__(self, type_manager): self.type_manager = type_manager def get_dependencies(self, n...
self.dependencies = set() return self.visit(node)
"""Collects all the type names that are used by node.""" self.dependencies = set() return self.visit(node)
5
343
23
366
# -*- coding: utf-8 -*- # Copyright (C) 2016 Google Inc. All Rights Reserved. # # Authors: # Arkadiusz Socała <as277575@mimuw.edu.pl> # Michael Cohen <scudette@google.com> # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obt...
# -*- coding: utf-8 -*- # Copyright (C) 2016 Google Inc. All Rights Reserved. # # Authors: # Arkadiusz Socała <as277575@mimuw.edu.pl> # Michael Cohen <scudette@google.com> # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obt...
36,426
/home/hieuvd/dung_repo/raw/stars_02/google_rekall/rekall
/home/hieuvd/dung_repo/raw/stars_02/google_rekall/rekall/tools/windows/winpmem/build_winpmem.py
151,152
1,178
BuildTestSignedBinaries
152,175
152,175
#!/usr/bin/python """Build script for winpmem. This script builds the drivers and then the userspace application which embeds them. To have it run, you will need to install the following components on a windows system: 1) .Net framework: http://www.microsoft.com/en-us/download/details.aspx?id=17851 2) Microsoft W...
#!/usr/bin/python """Build script for winpmem. This script builds the drivers and then the userspace application which embeds them. To have it run, you will need to install the following components on a windows system: 1) .Net framework: http://www.microsoft.com/en-us/download/details.aspx?id=17851 2) Microsoft W...
# Test signed binaries are built with write support. data = open("winpmem.h").read() if re.search("PMEM_WRITE_ENABLED [01]", data): new_data = re.sub( "PMEM_WRITE_ENABLED [01]", "PMEM_WRITE_ENABLED 1", data) try: with open("winpmem.h", "wb") as fd: fd...
# Test signed binaries are built with write support. data = open("winpmem.h").read() if re.search("PMEM_WRITE_ENABLED [01]", data): new_data = re.sub( "PMEM_WRITE_ENABLED [01]", "PMEM_WRITE_ENABLED 1", data) try: with open("winpmem.h", "wb") as fd: fd...
57
1,702
262
1,964
#!/usr/bin/python """Build script for winpmem. This script builds the drivers and then the userspace application which embeds them. To have it run, you will need to install the following components on a windows system: 1) .Net framework: http://www.microsoft.com/en-us/download/details.aspx?id=17851 2) Microsoft W...
#!/usr/bin/python """Build script for winpmem. This script builds the drivers and then the userspace application which embeds them. To have it run, you will need to install the following components on a windows system: 1) .Net framework: http://www.microsoft.com/en-us/download/details.aspx?id=17851 2) Microsoft W...
36,427
/home/hieuvd/dung_repo/raw/stars_02/google_rekall/rekall
/home/hieuvd/dung_repo/raw/stars_02/google_rekall/rekall/tools/windows/winpmem/obfuscator.py
20,21
1,27
interpolate_file
21,26
21,26
import random class Interpolator(object): def __init__(self): self.key = [random.randint(1, 255) for _ in range(50)] def __getitem__(self, item): if item == "key": return "".join(["\\x%02X" % x for x in self.key]) # Add a NULL terminator item += "\x00" # ...
import random class Interpolator(object): def __init__(self): self.key = [random.randint(1, 255) for _ in range(50)] def __getitem__(self, item): if item == "key": return "".join(["\\x%02X" % x for x in self.key]) # Add a NULL terminator item += "\x00" # ...
data = open(filename + ".in", "rb").read() with open(filename, "wb") as fd: fd.write(data % Interpolator())
data = open(filename + ".in", "rb").read() with open(filename, "wb") as fd: fd.write(data % Interpolator())
14
192
51
243
import random class Interpolator(object): def __init__(self): self.key = [random.randint(1, 255) for _ in range(50)] def __getitem__(self, item): if item == "key": return "".join(["\\x%02X" % x for x in self.key]) # Add a NULL terminator item += "\x00" # ...
import random class Interpolator(object): def __init__(self): self.key = [random.randint(1, 255) for _ in range(50)] def __getitem__(self, item): if item == "key": return "".join(["\\x%02X" % x for x in self.key]) # Add a NULL terminator item += "\x00" # ...
36,449
/home/hieuvd/dung_repo/raw/stars_02/guofei9987_blind_watermark/blind_watermark
/home/hieuvd/dung_repo/raw/stars_02/guofei9987_blind_watermark/blind_watermark/blind_watermark/cli_tools.py
19,20
1,54
main
20,45
20,45
from optparse import OptionParser from .blind_watermark import WaterMark usage1 = 'blind_watermark --embed --pwd 1234 image.jpg "watermark text" embed.png' usage2 = 'blind_watermark --extract --pwd 1234 --wm_shape 111 embed.png' optParser = OptionParser(usage=usage1 + '\n' + usage2) optParser.add_option('--embed', de...
from optparse import OptionParser from .blind_watermark import WaterMark usage1 = 'blind_watermark --embed --pwd 1234 image.jpg "watermark text" embed.png' usage2 = 'blind_watermark --extract --pwd 1234 --wm_shape 111 embed.png' optParser = OptionParser(usage=usage1 + '\n' + usage2) optParser.add_option('--embed', de...
bwm1 = WaterMark(password_img=int(opts.password)) if opts.work_mode == 'embed': if not len(args) == 3: print('Error! Usage: ') print(usage1) return else: bwm1.read_img(args[0]) bwm1.read_wm(args[1], mode='str') bwm1.embed(ar...
bwm1 = WaterMark(password_img=int(opts.password)) if opts.work_mode == 'embed': if not len(args) == 3: print('Error! Usage: ') print(usage1) return else: bwm1.read_img(args[0]) bwm1.read_wm(args[1], mode='str') bwm1.embed(ar...
58
464
296
760
from optparse import OptionParser from .blind_watermark import WaterMark usage1 = 'blind_watermark --embed --pwd 1234 image.jpg "watermark text" embed.png' usage2 = 'blind_watermark --extract --pwd 1234 --wm_shape 111 embed.png' optParser = OptionParser(usage=usage1 + '\n' + usage2) optParser.add_option('--embed', de...
from optparse import OptionParser from .blind_watermark import WaterMark usage1 = 'blind_watermark --embed --pwd 1234 image.jpg "watermark text" embed.png' usage2 = 'blind_watermark --extract --pwd 1234 --wm_shape 111 embed.png' optParser = OptionParser(usage=usage1 + '\n' + usage2) optParser.add_option('--embed', de...
36,450
/home/hieuvd/dung_repo/raw/stars_02/guofei9987_blind_watermark/blind_watermark
/home/hieuvd/dung_repo/raw/stars_02/guofei9987_blind_watermark/blind_watermark/blind_watermark/pool.py
37,38
14,39
map
AutoPool
38,39
38,39
class AutoPool(object): def __init__(self, mode, processes): if mode == 'multiprocessing' and sys.platform == 'win32': warnings.warn('multiprocessing not support in windows, turning to multithreading') mode = 'multithreading' self.mode = mode self.processes = proces...
class AutoPool(object): def __init__(self, mode, processes): if mode == 'multiprocessing' and sys.platform == 'win32': warnings.warn('multiprocessing not support in windows, turning to multithreading') mode = 'multithreading' self.mode = mode self.processes = proces...
return self.pool.map(func, args)
return self.pool.map(func, args)
3
227
14
241
import sys import multiprocessing import warnings if sys.platform != 'win32': multiprocessing.set_start_method('fork') class CommonPool(object): def map(self, func, args): return list(map(func, args)) class AutoPool(object): def __init__(self, mode, processes): if mode == 'multiprocess...
import sys import multiprocessing import warnings if sys.platform != 'win32': multiprocessing.set_start_method('fork') class CommonPool(object): def map(self, func, args): return list(map(func, args)) class AutoPool(object): def __init__(self, mode, processes): if mode == 'multiprocess...
36,451
/home/hieuvd/dung_repo/raw/stars_02/guofei9987_blind_watermark/blind_watermark
/home/hieuvd/dung_repo/raw/stars_02/guofei9987_blind_watermark/blind_watermark/blind_watermark/pool.py
10,11
9,14
map
CommonPool
11,14
11,14
class CommonPool(object): def map(self, func, args): FILL_FUNC_BODY
class CommonPool(object): def map(self, func, args): FILL_FUNC_BODY
return list(map(func, args))
return list(map(func, args))
3
28
16
44
import sys import multiprocessing import warnings if sys.platform != 'win32': multiprocessing.set_start_method('fork') class CommonPool(object): def map(self, func, args): FILL_FUNC_BODYclass AutoPool(object): def __init__(self, mode, processes): if mode == 'multiprocessing' and sys.platform == ...
import sys import multiprocessing import warnings if sys.platform != 'win32': multiprocessing.set_start_method('fork') class CommonPool(object): def map(self, func, args): FILL_FUNC_BODYclass AutoPool(object): def __init__(self, mode, processes): if mode == 'multiprocessing' and sys.platform == ...
36,452
/home/hieuvd/dung_repo/raw/stars_02/guofei9987_blind_watermark/blind_watermark
/home/hieuvd/dung_repo/raw/stars_02/guofei9987_blind_watermark/blind_watermark/blind_watermark/version.py
18,19
4,22
close
Notes
19,22
19,22
class Notes: def __init__(self): self.show = True def print_notes(self): if self.show: print(f''' Welcome to use blind-watermark, version = {__version__} Make sure the version is the same when encode and decode Your star means a lot: https://github.com/guofei9987/blind_watermark Thi...
class Notes: def __init__(self): self.show = True def print_notes(self): if self.show: print(f''' Welcome to use blind-watermark, version = {__version__} Make sure the version is the same when encode and decode Your star means a lot: https://github.com/guofei9987/blind_watermark Thi...
self.show = False
self.show = False
3
152
12
164
__version__ = '0.4.4' class Notes: def __init__(self): self.show = True def print_notes(self): if self.show: print(f''' Welcome to use blind-watermark, version = {__version__} Make sure the version is the same when encode and decode Your star means a lot: https://github.com/guofei...
__version__ = '0.4.4' class Notes: def __init__(self): self.show = True def print_notes(self): if self.show: print(f''' Welcome to use blind-watermark, version = {__version__} Make sure the version is the same when encode and decode Your star means a lot: https://github.com/guofei...
36,453
/home/hieuvd/dung_repo/raw/stars_02/guofei9987_blind_watermark/blind_watermark
/home/hieuvd/dung_repo/raw/stars_02/guofei9987_blind_watermark/blind_watermark/docs/make_doc.py
52,53
1,105
make_doc
53,82
53,82
# 不想用 Sphinx,也不像弄一堆静态html文件,所以自己写个咯 ''' 需要从readme中解析出: 1. "-> Demo code: [examples/demo_pso.py](examples/demo_pso.py)" 2. 三个```python为开头,三个 ``` 为结尾 3. 从py文件中读出文本,并替换 4. 前几行是求star,只在readme中出现 需要从py文件中解析出: 1. # %% 做断点后赋予index值,然后插入readme ''' import os import sys import re def search_code(py_file_name, section_idx)...
# 不想用 Sphinx,也不像弄一堆静态html文件,所以自己写个咯 ''' 需要从readme中解析出: 1. "-> Demo code: [examples/demo_pso.py](examples/demo_pso.py)" 2. 三个```python为开头,三个 ``` 为结尾 3. 从py文件中读出文本,并替换 4. 前几行是求star,只在readme中出现 需要从py文件中解析出: 1. # %% 做断点后赋予index值,然后插入readme ''' import os import sys import re def search_code(py_file_name, section_idx)...
with open(origin_file, encoding='utf-8', mode="r") as f_readme: readme = f_readme.readlines() regex = re.compile('\[examples/[\w#.]+\]') readme_idx = 0 readme_new = [] while readme_idx < len(readme): readme_line = readme[readme_idx] if readme_line.startswith('-> Demo code: [...
with open(origin_file, encoding='utf-8', mode="r") as f_readme: readme = f_readme.readlines() regex = re.compile('\[examples/[\w#.]+\]') readme_idx = 0 readme_new = [] while readme_idx < len(readme): readme_line = readme[readme_idx] if readme_line.startswith('-> Demo code: [...
73
955
380
1,335
# 不想用 Sphinx,也不像弄一堆静态html文件,所以自己写个咯 ''' 需要从readme中解析出: 1. "-> Demo code: [examples/demo_pso.py](examples/demo_pso.py)" 2. 三个```python为开头,三个 ``` 为结尾 3. 从py文件中读出文本,并替换 4. 前几行是求star,只在readme中出现 需要从py文件中解析出: 1. # %% 做断点后赋予index值,然后插入readme ''' import os import sys import re def search_code(py_file_name, section_idx)...
# 不想用 Sphinx,也不像弄一堆静态html文件,所以自己写个咯 ''' 需要从readme中解析出: 1. "-> Demo code: [examples/demo_pso.py](examples/demo_pso.py)" 2. 三个```python为开头,三个 ``` 为结尾 3. 从py文件中读出文本,并替换 4. 前几行是求star,只在readme中出现 需要从py文件中解析出: 1. # %% 做断点后赋予index值,然后插入readme ''' import os import sys import re def search_code(py_file_name, section_idx)...
36,454
/home/hieuvd/dung_repo/raw/stars_02/guofei9987_blind_watermark/blind_watermark
/home/hieuvd/dung_repo/raw/stars_02/guofei9987_blind_watermark/blind_watermark/setup.py
16,17
1,40
read_requirements
17,21
17,21
from setuptools import setup, find_packages from os import path as os_path import blind_watermark this_directory = os_path.abspath(os_path.dirname(__file__)) # 读取文件内容 def read_file(filename): with open(os_path.join(this_directory, filename), encoding='utf-8') as f: long_description = f.read() return ...
from setuptools import setup, find_packages from os import path as os_path import blind_watermark this_directory = os_path.abspath(os_path.dirname(__file__)) # 读取文件内容 def read_file(filename): with open(os_path.join(this_directory, filename), encoding='utf-8') as f: long_description = f.read() return ...
return [line.strip() for line in read_file(filename).splitlines() if not line.startswith('#')]
return [line.strip() for line in read_file(filename).splitlines() if not line.startswith('#')]
9
381
38
419
from setuptools import setup, find_packages from os import path as os_path import blind_watermark this_directory = os_path.abspath(os_path.dirname(__file__)) # 读取文件内容 def read_file(filename): with open(os_path.join(this_directory, filename), encoding='utf-8') as f: long_description = f.read() return ...
from setuptools import setup, find_packages from os import path as os_path import blind_watermark this_directory = os_path.abspath(os_path.dirname(__file__)) # 读取文件内容 def read_file(filename): with open(os_path.join(this_directory, filename), encoding='utf-8') as f: long_description = f.read() return ...
36,486
/home/hieuvd/dung_repo/raw/stars_02/help-iq2_telethon/telethon
/home/hieuvd/dung_repo/raw/stars_02/help-iq2_telethon/telethon/setup/updater.py
8,9
1,53
lines_differnce
9,26
9,26
import asyncio import difflib import shlex from typing import Tuple import sys # if any requirements are cahnged then install that requirement async def lines_differnce(file1, file2): FILL_FUNC_BODYasync def runcmd(cmd: str) -> Tuple[str, str, int, int]: args = shlex.split(cmd) process = await asyncio.create_s...
import asyncio import difflib import shlex from typing import Tuple import sys # if any requirements are cahnged then install that requirement async def lines_differnce(file1, file2): FILL_FUNC_BODYasync def runcmd(cmd: str) -> Tuple[str, str, int, int]: args = shlex.split(cmd) process = await asyncio.create_s...
with open(file1) as f1: lines1 = f1.readlines() lines1 = [line.rstrip("\n") for line in lines1] with open(file2) as f2: lines2 = f2.readlines() lines2 = [line.rstrip("\n") for line in lines2] diff = difflib.unified_diff( lines1, lines2, fromfile=file1, tofile=file2, l...
with open(file1) as f1: lines1 = f1.readlines() lines1 = [line.rstrip("\n") for line in lines1] with open(file2) as f2: lines2 = f2.readlines() lines2 = [line.rstrip("\n") for line in lines2] diff = difflib.unified_diff( lines1, lines2, fromfile=file1, tofile=file2, l...
90
393
242
635
import asyncio import difflib import shlex from typing import Tuple import sys # if any requirements are cahnged then install that requirement async def lines_differnce(file1, file2): FILL_FUNC_BODYasync def runcmd(cmd: str) -> Tuple[str, str, int, int]: args = shlex.split(cmd) process = await asyncio.create_s...
import asyncio import difflib import shlex from typing import Tuple import sys # if any requirements are cahnged then install that requirement async def lines_differnce(file1, file2): FILL_FUNC_BODYasync def runcmd(cmd: str) -> Tuple[str, str, int, int]: args = shlex.split(cmd) process = await asyncio.create_s...
36,488
/home/hieuvd/dung_repo/raw/stars_02/huashengdun_webssh/webssh
/home/hieuvd/dung_repo/raw/stars_02/huashengdun_webssh/webssh/webssh/handler.py
287,288
186,306
get_real_client_addr
MixinHandler
288,306
288,306
class MixinHandler(object): custom_headers = { 'Server': 'TornadoServer' } html = ('<html><head><title>{code} {reason}</title></head><body>{code} ' '{reason}</body></html>') def initialize(self, loop=None): self.check_request() self.loop = loop self.origin_...
class MixinHandler(object): custom_headers = { 'Server': 'TornadoServer' } html = ('<html><head><title>{code} {reason}</title></head><body>{code} ' '{reason}</body></html>') def initialize(self, loop=None): self.check_request() self.loop = loop self.origin_...
ip = self.request.remote_ip if ip == self.request.headers.get('X-Real-Ip'): port = self.request.headers.get('X-Real-Port') elif ip in self.request.headers.get('X-Forwarded-For', ''): port = self.request.headers.get('X-Forwarded-Port') else: # not runn...
ip = self.request.remote_ip if ip == self.request.headers.get('X-Real-Ip'): port = self.request.headers.get('X-Real-Port') elif ip in self.request.headers.get('X-Forwarded-For', ''): port = self.request.headers.get('X-Forwarded-Port') else: # not runn...
46
957
182
1,139
import io import json import logging import socket import struct import traceback import weakref import paramiko import tornado.web from concurrent.futures import ThreadPoolExecutor from tornado.ioloop import IOLoop from tornado.options import options from tornado.process import cpu_count from webssh.utils import ( ...
import io import json import logging import socket import struct import traceback import weakref import paramiko import tornado.web from concurrent.futures import ThreadPoolExecutor from tornado.ioloop import IOLoop from tornado.options import options from tornado.process import cpu_count from webssh.utils import ( ...
36,489
/home/hieuvd/dung_repo/raw/stars_02/huashengdun_webssh/webssh
/home/hieuvd/dung_repo/raw/stars_02/huashengdun_webssh/webssh/webssh/handler.py
311,312
306,315
prepare
NotFoundHandler
312,315
312,315
class NotFoundHandler(MixinHandler, tornado.web.ErrorHandler): def initialize(self): super(NotFoundHandler, self).initialize() def prepare(self): FILL_FUNC_BODY
class NotFoundHandler(MixinHandler, tornado.web.ErrorHandler): def initialize(self): super(NotFoundHandler, self).initialize() def prepare(self): FILL_FUNC_BODY
raise tornado.web.HTTPError(404)
raise tornado.web.HTTPError(404)
2
56
20
76
import io import json import logging import socket import struct import traceback import weakref import paramiko import tornado.web from concurrent.futures import ThreadPoolExecutor from tornado.ioloop import IOLoop from tornado.options import options from tornado.process import cpu_count from webssh.utils import ( ...
import io import json import logging import socket import struct import traceback import weakref import paramiko import tornado.web from concurrent.futures import ThreadPoolExecutor from tornado.ioloop import IOLoop from tornado.options import options from tornado.process import cpu_count from webssh.utils import ( ...
36,490
/home/hieuvd/dung_repo/raw/stars_02/huashengdun_webssh/webssh
/home/hieuvd/dung_repo/raw/stars_02/huashengdun_webssh/webssh/webssh/handler.py
159,160
103,186
get_pkey_obj
PrivateKey
160,186
160,186
class PrivateKey(object): max_length = 16384 # rough number tag_to_name = { 'RSA': 'RSA', 'DSA': 'DSS', 'EC': 'ECDSA', 'OPENSSH': 'Ed25519' } def __init__(self, privatekey, password=None, filename=''): self.privatekey = privatekey self.filename = filen...
class PrivateKey(object): max_length = 16384 # rough number tag_to_name = { 'RSA': 'RSA', 'DSA': 'DSS', 'EC': 'ECDSA', 'OPENSSH': 'Ed25519' } def __init__(self, privatekey, password=None, filename=''): self.privatekey = privatekey self.filename = filen...
logging.info('Parsing private key {!r}'.format(self.filename)) name, length = self.parse_name(self.iostr, self.tag_to_name) if not name: raise InvalidValueError('Invalid key {}.'.format(self.filename)) offset = self.iostr.tell() - length password = to_bytes(self.pass...
logging.info('Parsing private key {!r}'.format(self.filename)) name, length = self.parse_name(self.iostr, self.tag_to_name) if not name: raise InvalidValueError('Invalid key {}.'.format(self.filename)) offset = self.iostr.tell() - length password = to_bytes(self.pass...
79
555
298
853
import io import json import logging import socket import struct import traceback import weakref import paramiko import tornado.web from concurrent.futures import ThreadPoolExecutor from tornado.ioloop import IOLoop from tornado.options import options from tornado.process import cpu_count from webssh.utils import ( ...
import io import json import logging import socket import struct import traceback import weakref import paramiko import tornado.web from concurrent.futures import ThreadPoolExecutor from tornado.ioloop import IOLoop from tornado.options import options from tornado.process import cpu_count from webssh.utils import ( ...
36,491
/home/hieuvd/dung_repo/raw/stars_02/huashengdun_webssh/webssh
/home/hieuvd/dung_repo/raw/stars_02/huashengdun_webssh/webssh/webssh/handler.py
62,63
43,103
_auth
SSHClient
63,103
63,103
class SSHClient(paramiko.SSHClient): def handler(self, title, instructions, prompt_list): answers = [] for prompt_, _ in prompt_list: prompt = prompt_.strip().lower() if prompt.startswith('password'): answers.append(self.password) elif prompt.star...
class SSHClient(paramiko.SSHClient): def handler(self, title, instructions, prompt_list): answers = [] for prompt_, _ in prompt_list: prompt = prompt_.strip().lower() if prompt.startswith('password'): answers.append(self.password) elif prompt.star...
self.password = password saved_exception = None two_factor = False allowed_types = set() two_factor_types = {'keyboard-interactive', 'password'} if pkey is not None: logging.info('Trying publickey authentication') try: allowed_type...
self.password = password saved_exception = None two_factor = False allowed_types = set() two_factor_types = {'keyboard-interactive', 'password'} if pkey is not None: logging.info('Trying publickey authentication') try: allowed_type...
99
210
375
585
import io import json import logging import socket import struct import traceback import weakref import paramiko import tornado.web from concurrent.futures import ThreadPoolExecutor from tornado.ioloop import IOLoop from tornado.options import options from tornado.process import cpu_count from webssh.utils import ( ...
import io import json import logging import socket import struct import traceback import weakref import paramiko import tornado.web from concurrent.futures import ThreadPoolExecutor from tornado.ioloop import IOLoop from tornado.options import options from tornado.process import cpu_count from webssh.utils import ( ...
36,492
/home/hieuvd/dung_repo/raw/stars_02/huashengdun_webssh/webssh
/home/hieuvd/dung_repo/raw/stars_02/huashengdun_webssh/webssh/webssh/handler.py
559,560
529,604
on_message
WsockHandler
560,596
560,596
class WsockHandler(MixinHandler, tornado.websocket.WebSocketHandler): def initialize(self, loop): super(WsockHandler, self).initialize(loop) self.worker_ref = None def open(self): self.src_addr = self.get_client_addr() logging.info('Connected from {}:{}'.format(*self.src_addr))...
class WsockHandler(MixinHandler, tornado.websocket.WebSocketHandler): def initialize(self, loop): super(WsockHandler, self).initialize(loop) self.worker_ref = None def open(self): self.src_addr = self.get_client_addr() logging.info('Connected from {}:{}'.format(*self.src_addr))...
logging.debug('{!r} from {}:{}'.format(message, *self.src_addr)) worker = self.worker_ref() if not worker: # The worker has likely been closed. Do not process. logging.debug( "received message to closed worker from {}:{}".format( *self....
logging.debug('{!r} from {}:{}'.format(message, *self.src_addr)) worker = self.worker_ref() if not worker: # The worker has likely been closed. Do not process. logging.debug( "received message to closed worker from {}:{}".format( *self....
78
419
319
738
import io import json import logging import socket import struct import traceback import weakref import paramiko import tornado.web from concurrent.futures import ThreadPoolExecutor from tornado.ioloop import IOLoop from tornado.options import options from tornado.process import cpu_count from webssh.utils import ( ...
import io import json import logging import socket import struct import traceback import weakref import paramiko import tornado.web from concurrent.futures import ThreadPoolExecutor from tornado.ioloop import IOLoop from tornado.options import options from tornado.process import cpu_count from webssh.utils import ( ...
36,493
/home/hieuvd/dung_repo/raw/stars_02/huashengdun_webssh/webssh
/home/hieuvd/dung_repo/raw/stars_02/huashengdun_webssh/webssh/webssh/main.py
31,32
1,59
app_listen
32,43
32,43
import logging import tornado.web import tornado.ioloop from tornado.options import options from webssh import handler from webssh.handler import IndexHandler, WsockHandler, NotFoundHandler from webssh.settings import ( get_app_settings, get_host_keys_settings, get_policy_setting, get_ssl_context, get_server_...
import logging import tornado.web import tornado.ioloop from tornado.options import options from webssh import handler from webssh.handler import IndexHandler, WsockHandler, NotFoundHandler from webssh.settings import ( get_app_settings, get_host_keys_settings, get_policy_setting, get_ssl_context, get_server_...
app.listen(port, address, **server_settings) if not server_settings.get('ssl_options'): server_type = 'http' else: server_type = 'https' handler.redirecting = True if options.redirect else False logging.info( 'Listening on {}:{} ({})'.format(address, port, server_type) ...
app.listen(port, address, **server_settings) if not server_settings.get('ssl_options'): server_type = 'http' else: server_type = 'https' handler.redirecting = True if options.redirect else False logging.info( 'Listening on {}:{} ({})'.format(address, port, server_type) ...
28
476
113
589
import logging import tornado.web import tornado.ioloop from tornado.options import options from webssh import handler from webssh.handler import IndexHandler, WsockHandler, NotFoundHandler from webssh.settings import ( get_app_settings, get_host_keys_settings, get_policy_setting, get_ssl_context, get_server_...
import logging import tornado.web import tornado.ioloop from tornado.options import options from webssh import handler from webssh.handler import IndexHandler, WsockHandler, NotFoundHandler from webssh.settings import ( get_app_settings, get_host_keys_settings, get_policy_setting, get_ssl_context, get_server_...
36,494
/home/hieuvd/dung_repo/raw/stars_02/huashengdun_webssh/webssh
/home/hieuvd/dung_repo/raw/stars_02/huashengdun_webssh/webssh/webssh/policy.py
38,39
1,87
check_policy_setting
39,52
39,52
import logging import os.path import threading import paramiko def load_host_keys(path): if os.path.exists(path) and os.path.isfile(path): return paramiko.hostkeys.HostKeys(filename=path) return paramiko.hostkeys.HostKeys() def get_policy_dictionary(): dic = { k.lower(): v for k, v in var...
import logging import os.path import threading import paramiko def load_host_keys(path): if os.path.exists(path) and os.path.isfile(path): return paramiko.hostkeys.HostKeys(filename=path) return paramiko.hostkeys.HostKeys() def get_policy_dictionary(): dic = { k.lower(): v for k, v in var...
host_keys = host_keys_settings['host_keys'] host_keys_filename = host_keys_settings['host_keys_filename'] system_host_keys = host_keys_settings['system_host_keys'] if policy_class is paramiko.client.AutoAddPolicy: host_keys.save(host_keys_filename) # for permission test elif policy_class i...
host_keys = host_keys_settings['host_keys'] host_keys_filename = host_keys_settings['host_keys_filename'] system_host_keys = host_keys_settings['system_host_keys'] if policy_class is paramiko.client.AutoAddPolicy: host_keys.save(host_keys_filename) # for permission test elif policy_class i...
40
669
163
832
import logging import os.path import threading import paramiko def load_host_keys(path): if os.path.exists(path) and os.path.isfile(path): return paramiko.hostkeys.HostKeys(filename=path) return paramiko.hostkeys.HostKeys() def get_policy_dictionary(): dic = { k.lower(): v for k, v in var...
import logging import os.path import threading import paramiko def load_host_keys(path): if os.path.exists(path) and os.path.isfile(path): return paramiko.hostkeys.HostKeys(filename=path) return paramiko.hostkeys.HostKeys() def get_policy_dictionary(): dic = { k.lower(): v for k, v in var...
36,495
/home/hieuvd/dung_repo/raw/stars_02/huashengdun_webssh/webssh
/home/hieuvd/dung_repo/raw/stars_02/huashengdun_webssh/webssh/webssh/policy.py
69,70
52,86
missing_host_key
AutoAddPolicy
70,86
70,86
class AutoAddPolicy(paramiko.client.MissingHostKeyPolicy): """ thread-safe AutoAddPolicy """ lock = threading.Lock() def is_missing_host_key(self, client, hostname, key): k = client._system_host_keys.lookup(hostname) or \ client._host_keys.lookup(hostname) if k is No...
class AutoAddPolicy(paramiko.client.MissingHostKeyPolicy): """ thread-safe AutoAddPolicy """ lock = threading.Lock() def is_missing_host_key(self, client, hostname, key): k = client._system_host_keys.lookup(hostname) or \ client._host_keys.lookup(hostname) if k is No...
with self.lock: if self.is_missing_host_key(client, hostname, key): keytype = key.get_name() logging.info( 'Adding {} host key for {}'.format(keytype, hostname) ) client._host_keys._entries.append( ...
with self.lock: if self.is_missing_host_key(client, hostname, key): keytype = key.get_name() logging.info( 'Adding {} host key for {}'.format(keytype, hostname) ) client._host_keys._entries.append( ...
34
198
173
371
import logging import os.path import threading import paramiko def load_host_keys(path): if os.path.exists(path) and os.path.isfile(path): return paramiko.hostkeys.HostKeys(filename=path) return paramiko.hostkeys.HostKeys() def get_policy_dictionary(): dic = { k.lower(): v for k, v in var...
import logging import os.path import threading import paramiko def load_host_keys(path): if os.path.exists(path) and os.path.isfile(path): return paramiko.hostkeys.HostKeys(filename=path) return paramiko.hostkeys.HostKeys() def get_policy_dictionary(): dic = { k.lower(): v for k, v in var...
36,496
/home/hieuvd/dung_repo/raw/stars_02/huashengdun_webssh/webssh
/home/hieuvd/dung_repo/raw/stars_02/huashengdun_webssh/webssh/webssh/settings.py
102,103
1,199
get_host_keys_settings
103,123
103,123
import logging import os.path import ssl import sys from tornado.options import define from webssh.policy import ( load_host_keys, get_policy_class, check_policy_setting ) from webssh.utils import ( to_ip_address, parse_origin_from_url, is_valid_encoding ) from webssh._version import __version__ def print_ve...
import logging import os.path import ssl import sys from tornado.options import define from webssh.policy import ( load_host_keys, get_policy_class, check_policy_setting ) from webssh.utils import ( to_ip_address, parse_origin_from_url, is_valid_encoding ) from webssh._version import __version__ def print_ve...
if not options.hostfile: host_keys_filename = os.path.join(base_dir, 'known_hosts') else: host_keys_filename = options.hostfile host_keys = load_host_keys(host_keys_filename) if not options.syshostfile: filename = os.path.expanduser('~/.ssh/known_hosts') else: filena...
if not options.hostfile: host_keys_filename = os.path.join(base_dir, 'known_hosts') else: host_keys_filename = options.hostfile host_keys = load_host_keys(host_keys_filename) if not options.syshostfile: filename = os.path.expanduser('~/.ssh/known_hosts') else: filena...
36
1,846
200
2,046
import logging import os.path import ssl import sys from tornado.options import define from webssh.policy import ( load_host_keys, get_policy_class, check_policy_setting ) from webssh.utils import ( to_ip_address, parse_origin_from_url, is_valid_encoding ) from webssh._version import __version__ def print_ve...
import logging import os.path import ssl import sys from tornado.options import define from webssh.policy import ( load_host_keys, get_policy_class, check_policy_setting ) from webssh.utils import ( to_ip_address, parse_origin_from_url, is_valid_encoding ) from webssh._version import __version__ def print_ve...
36,497
/home/hieuvd/dung_repo/raw/stars_02/huashengdun_webssh/webssh
/home/hieuvd/dung_repo/raw/stars_02/huashengdun_webssh/webssh/webssh/settings.py
72,73
63,76
get_url
Font
73,76
73,76
class Font(object): def __init__(self, filename, dirs): self.family = self.get_family(filename) self.url = self.get_url(filename, dirs) def get_family(self, filename): return filename.split('.')[0] def get_url(self, filename, dirs): FILL_FUNC_BODY
class Font(object): def __init__(self, filename, dirs): self.family = self.get_family(filename) self.url = self.get_url(filename, dirs) def get_family(self, filename): return filename.split('.')[0] def get_url(self, filename, dirs): FILL_FUNC_BODY
return '/'.join(dirs + [filename])
return '/'.join(dirs + [filename])
4
99
18
117
import logging import os.path import ssl import sys from tornado.options import define from webssh.policy import ( load_host_keys, get_policy_class, check_policy_setting ) from webssh.utils import ( to_ip_address, parse_origin_from_url, is_valid_encoding ) from webssh._version import __version__ def print_ve...
import logging import os.path import ssl import sys from tornado.options import define from webssh.policy import ( load_host_keys, get_policy_class, check_policy_setting ) from webssh.utils import ( to_ip_address, parse_origin_from_url, is_valid_encoding ) from webssh._version import __version__ def print_ve...
36,498
/home/hieuvd/dung_repo/raw/stars_02/huashengdun_webssh/webssh
/home/hieuvd/dung_repo/raw/stars_02/huashengdun_webssh/webssh/webssh/utils.py
124,125
1,148
parse_origin_from_url
125,148
125,148
import ipaddress import re try: from types import UnicodeType except ImportError: UnicodeType = str try: from urllib.parse import urlparse except ImportError: from urlparse import urlparse numeric = re.compile(r'[0-9]+$') allowed = re.compile(r'(?!-)[a-z0-9-]{1,63}(?<!-)$', re.IGNORECASE) def to_s...
import ipaddress import re try: from types import UnicodeType except ImportError: UnicodeType = str try: from urllib.parse import urlparse except ImportError: from urlparse import urlparse numeric = re.compile(r'[0-9]+$') allowed = re.compile(r'(?!-)[a-z0-9-]{1,63}(?<!-)$', re.IGNORECASE) def to_s...
url = url.strip() if not url: return if not (url.startswith('http://') or url.startswith('https://') or url.startswith('//')): url = '//' + url parsed = urlparse(url) port = parsed.port scheme = parsed.scheme if scheme == '': scheme = 'https' if port ==...
url = url.strip() if not url: return if not (url.startswith('http://') or url.startswith('https://') or url.startswith('//')): url = '//' + url parsed = urlparse(url) port = parsed.port scheme = parsed.scheme if scheme == '': scheme = 'https' if port ==...
72
836
229
1,065
import ipaddress import re try: from types import UnicodeType except ImportError: UnicodeType = str try: from urllib.parse import urlparse except ImportError: from urlparse import urlparse numeric = re.compile(r'[0-9]+$') allowed = re.compile(r'(?!-)[a-z0-9-]{1,63}(?<!-)$', re.IGNORECASE) def to_s...
import ipaddress import re try: from types import UnicodeType except ImportError: UnicodeType = str try: from urllib.parse import urlparse except ImportError: from urlparse import urlparse numeric = re.compile(r'[0-9]+$') allowed = re.compile(r'(?!-)[a-z0-9-]{1,63}(?<!-)$', re.IGNORECASE) def to_s...
36,499
/home/hieuvd/dung_repo/raw/stars_02/huashengdun_webssh/webssh
/home/hieuvd/dung_repo/raw/stars_02/huashengdun_webssh/webssh/webssh/worker.py
18,19
1,135
clear_worker
19,30
19,30
import logging try: import secrets except ImportError: secrets = None import tornado.websocket from uuid import uuid4 from tornado.ioloop import IOLoop from tornado.iostream import _ERRNO_CONNRESET from tornado.util import errno_from_exception BUF_SIZE = 32 * 1024 clients = {} # {ip: {id: worker}} def cle...
import logging try: import secrets except ImportError: secrets = None import tornado.websocket from uuid import uuid4 from tornado.ioloop import IOLoop from tornado.iostream import _ERRNO_CONNRESET from tornado.util import errno_from_exception BUF_SIZE = 32 * 1024 clients = {} # {ip: {id: worker}} def cle...
ip = worker.src_addr[0] workers = clients.get(ip) assert worker.id in workers workers.pop(worker.id) if not workers: clients.pop(ip) if not clients: clients.clear()
ip = worker.src_addr[0] workers = clients.get(ip) assert worker.id in workers workers.pop(worker.id) if not workers: clients.pop(ip) if not clients: clients.clear()
19
1,202
80
1,282
import logging try: import secrets except ImportError: secrets = None import tornado.websocket from uuid import uuid4 from tornado.ioloop import IOLoop from tornado.iostream import _ERRNO_CONNRESET from tornado.util import errno_from_exception BUF_SIZE = 32 * 1024 clients = {} # {ip: {id: worker}} def cle...
import logging try: import secrets except ImportError: secrets = None import tornado.websocket from uuid import uuid4 from tornado.ioloop import IOLoop from tornado.iostream import _ERRNO_CONNRESET from tornado.util import errno_from_exception BUF_SIZE = 32 * 1024 clients = {} # {ip: {id: worker}} def cle...
36,500
/home/hieuvd/dung_repo/raw/stars_02/huashengdun_webssh/webssh
/home/hieuvd/dung_repo/raw/stars_02/huashengdun_webssh/webssh/webssh/worker.py
93,94
37,135
on_write
Worker
94,118
94,118
class Worker(object): def __init__(self, loop, ssh, chan, dst_addr): self.loop = loop self.ssh = ssh self.chan = chan self.dst_addr = dst_addr self.fd = chan.fileno() self.id = self.gen_id() self.data_to_dst = [] self.handler = None self.mode =...
class Worker(object): def __init__(self, loop, ssh, chan, dst_addr): self.loop = loop self.ssh = ssh self.chan = chan self.dst_addr = dst_addr self.fd = chan.fileno() self.id = self.gen_id() self.data_to_dst = [] self.handler = None self.mode =...
logging.debug('worker {} on write'.format(self.id)) if not self.data_to_dst: return data = ''.join(self.data_to_dst) logging.debug('{!r} to {}:{}'.format(data, *self.dst_addr)) try: sent = self.chan.send(data) except (OSError, IOError) as e: ...
logging.debug('worker {} on write'.format(self.id)) if not self.data_to_dst: return data = ''.join(self.data_to_dst) logging.debug('{!r} to {}:{}'.format(data, *self.dst_addr)) try: sent = self.chan.send(data) except (OSError, IOError) as e: ...
50
768
283
1,051
import logging try: import secrets except ImportError: secrets = None import tornado.websocket from uuid import uuid4 from tornado.ioloop import IOLoop from tornado.iostream import _ERRNO_CONNRESET from tornado.util import errno_from_exception BUF_SIZE = 32 * 1024 clients = {} # {ip: {id: worker}} def cle...
import logging try: import secrets except ImportError: secrets = None import tornado.websocket from uuid import uuid4 from tornado.ioloop import IOLoop from tornado.iostream import _ERRNO_CONNRESET from tornado.util import errno_from_exception BUF_SIZE = 32 * 1024 clients = {} # {ip: {id: worker}} def cle...
36,534
/home/hieuvd/dung_repo/raw/stars_02/ihmily_DouyinLiveRecorder/DouyinLiveRecorder
/home/hieuvd/dung_repo/raw/stars_02/ihmily_DouyinLiveRecorder/DouyinLiveRecorder/msg_push.py
21,23
1,87
dingtalk
23,42
23,42
# -*- coding: utf-8 -*- """ Author: Hmily GitHub: https://github.com/ihmily Date: 2023-09-03 19:18:36 Update: 2024-01-16 02:31:36 Copyright (c) 2023 by Hmily, All Rights Reserved. """ from typing import Dict, Any, Optional import json import urllib.request from utils import trace_error_decorator no_proxy_handler = u...
# -*- coding: utf-8 -*- """ Author: Hmily GitHub: https://github.com/ihmily Date: 2023-09-03 19:18:36 Update: 2024-01-16 02:31:36 Copyright (c) 2023 by Hmily, All Rights Reserved. """ from typing import Dict, Any, Optional import json import urllib.request from utils import trace_error_decorator no_proxy_handler = u...
json_data = { 'msgtype': 'text', 'text': { 'content': '直播间状态更新:\n' + content, }, "at": { "atMobiles": [ phone_number # 添加这个手机号,可以被@通知(必须要在群里) ], }, } data = json.dumps(json_data).encode('utf-8') req = urllib.req...
json_data = { 'msgtype': 'text', 'text': { 'content': '直播间状态更新:\n' + content, }, "at": { "atMobiles": [ phone_number # 添加这个手机号,可以被@通知(必须要在群里) ], }, } data = json.dumps(json_data).encode('utf-8') req = urllib.req...
42
919
208
1,127
# -*- coding: utf-8 -*- """ Author: Hmily GitHub: https://github.com/ihmily Date: 2023-09-03 19:18:36 Update: 2024-01-16 02:31:36 Copyright (c) 2023 by Hmily, All Rights Reserved. """ from typing import Dict, Any, Optional import json import urllib.request from utils import trace_error_decorator no_proxy_handler = u...
# -*- coding: utf-8 -*- """ Author: Hmily GitHub: https://github.com/ihmily Date: 2023-09-03 19:18:36 Update: 2024-01-16 02:31:36 Copyright (c) 2023 by Hmily, All Rights Reserved. """ from typing import Dict, Any, Optional import json import urllib.request from utils import trace_error_decorator no_proxy_handler = u...
36,536
/home/hieuvd/dung_repo/raw/stars_02/ihmily_DouyinLiveRecorder/DouyinLiveRecorder
/home/hieuvd/dung_repo/raw/stars_02/ihmily_DouyinLiveRecorder/DouyinLiveRecorder/utils.py
10,11
1,101
trace_error_decorator
11,24
11,24
# -*- coding: utf-8 -*- import functools import hashlib import traceback from logger import logger import configparser def trace_error_decorator(func): FILL_FUNC_BODYdef check_md5(file_path): """ 计算文件的md5值 """ with open(file_path, 'rb') as fp: file_md5 = hashlib.md5(fp.read()).hexdigest() ...
# -*- coding: utf-8 -*- import functools import hashlib import traceback from logger import logger import configparser def trace_error_decorator(func): FILL_FUNC_BODYdef check_md5(file_path): """ 计算文件的md5值 """ with open(file_path, 'rb') as fp: file_md5 = hashlib.md5(fp.read()).hexdigest() ...
@functools.wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except Exception as e: error_line = traceback.extract_tb(e.__traceback__)[-1].lineno error_info = f"错误信息: type: {type(e).__name__}, {str(e)} in function {func.__name__} at l...
@functools.wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except Exception as e: error_line = traceback.extract_tb(e.__traceback__)[-1].lineno error_info = f"错误信息: type: {type(e).__name__}, {str(e)} in function {func.__name__} at l...
32
743
144
887
# -*- coding: utf-8 -*- import functools import hashlib import traceback from logger import logger import configparser def trace_error_decorator(func): FILL_FUNC_BODYdef check_md5(file_path): """ 计算文件的md5值 """ with open(file_path, 'rb') as fp: file_md5 = hashlib.md5(fp.read()).hexdigest() ...
# -*- coding: utf-8 -*- import functools import hashlib import traceback from logger import logger import configparser def trace_error_decorator(func): FILL_FUNC_BODYdef check_md5(file_path): """ 计算文件的md5值 """ with open(file_path, 'rb') as fp: file_md5 = hashlib.md5(fp.read()).hexdigest() ...
36,537
/home/hieuvd/dung_repo/raw/stars_02/ihmily_DouyinLiveRecorder/DouyinLiveRecorder
/home/hieuvd/dung_repo/raw/stars_02/ihmily_DouyinLiveRecorder/DouyinLiveRecorder/web_rid.py
53,54
1,80
get_live_room_id
54,73
54,73
# -*- encoding: utf-8 -*- """ Author: Hmily Github:https://github.com/ihmily Date: 2023-07-17 23:52:05 Update: 2024-03-06 23:35:00 Copyright (c) 2023 by Hmily, All Rights Reserved. """ import json import re import urllib.parse from typing import Union import execjs # pip install PyExecJS import requests import urllib...
# -*- encoding: utf-8 -*- """ Author: Hmily Github:https://github.com/ihmily Date: 2023-07-17 23:52:05 Update: 2024-03-06 23:35:00 Copyright (c) 2023 by Hmily, All Rights Reserved. """ import json import re import urllib.parse from typing import Union import execjs # pip install PyExecJS import requests import urllib...
url = f'https://webcast.amemv.com/webcast/room/reflow/info/?verifyFp=verify_lk07kv74_QZYCUApD_xhiB_405x_Ax51_GYO9bUIyZQVf&type_id=0&live_id=1&room_id={room_id}&sec_user_id={sec_user_id}&app_id=1128&msToken=wrqzbEaTlsxt52-vxyZo_mIoL0RjNi1ZdDe7gzEGMUTVh_HvmbLLkQrA_1HKVOa2C6gkxb6IiY6TY2z8enAkPEwGq--gM-me3Yudck2ailla5Q...
url = f'https://webcast.amemv.com/webcast/room/reflow/info/?verifyFp=verify_lk07kv74_QZYCUApD_xhiB_405x_Ax51_GYO9bUIyZQVf&type_id=0&live_id=1&room_id={room_id}&sec_user_id={sec_user_id}&app_id=1128&msToken=wrqzbEaTlsxt52-vxyZo_mIoL0RjNi1ZdDe7gzEGMUTVh_HvmbLLkQrA_1HKVOa2C6gkxb6IiY6TY2z8enAkPEwGq--gM-me3Yudck2ailla5Q...
51
901
455
1,356
# -*- encoding: utf-8 -*- """ Author: Hmily Github:https://github.com/ihmily Date: 2023-07-17 23:52:05 Update: 2024-03-06 23:35:00 Copyright (c) 2023 by Hmily, All Rights Reserved. """ import json import re import urllib.parse from typing import Union import execjs # pip install PyExecJS import requests import urllib...
# -*- encoding: utf-8 -*- """ Author: Hmily Github:https://github.com/ihmily Date: 2023-07-17 23:52:05 Update: 2024-03-06 23:35:00 Copyright (c) 2023 by Hmily, All Rights Reserved. """ import json import re import urllib.parse from typing import Union import execjs # pip install PyExecJS import requests import urllib...
36,623
/home/hieuvd/dung_repo/raw/stars_02/jdepoix_youtube-transcript-api/youtube-transcript-api
/home/hieuvd/dung_repo/raw/stars_02/jdepoix_youtube-transcript-api/youtube-transcript-api/setup.py
16,17
1,60
get_test_suite
17,25
17,25
import os import unittest import setuptools def _get_file_content(file_name): with open(file_name, 'r') as file_handler: return file_handler.read() def get_long_description(): return _get_file_content('README.md') def get_test_suite(): FILL_FUNC_BODYsetuptools.setup( name="youtube_transcript_...
import os import unittest import setuptools def _get_file_content(file_name): with open(file_name, 'r') as file_handler: return file_handler.read() def get_long_description(): return _get_file_content('README.md') def get_test_suite(): FILL_FUNC_BODYsetuptools.setup( name="youtube_transcript_...
test_loader = unittest.TestLoader() test_suite = test_loader.discover( 'test', pattern='test_*.py', top_level_dir='{dirname}/youtube_transcript_api'.format(dirname=os.path.dirname(__file__)) ) return test_suite
test_loader = unittest.TestLoader() test_suite = test_loader.discover( 'test', pattern='test_*.py', top_level_dir='{dirname}/youtube_transcript_api'.format(dirname=os.path.dirname(__file__)) ) return test_suite
12
527
96
623
import os import unittest import setuptools def _get_file_content(file_name): with open(file_name, 'r') as file_handler: return file_handler.read() def get_long_description(): return _get_file_content('README.md') def get_test_suite(): FILL_FUNC_BODYsetuptools.setup( name="youtube_transcript_...
import os import unittest import setuptools def _get_file_content(file_name): with open(file_name, 'r') as file_handler: return file_handler.read() def get_long_description(): return _get_file_content('README.md') def get_test_suite(): FILL_FUNC_BODYsetuptools.setup( name="youtube_transcript_...
36,624
/home/hieuvd/dung_repo/raw/stars_02/jdepoix_youtube-transcript-api/youtube-transcript-api
/home/hieuvd/dung_repo/raw/stars_02/jdepoix_youtube-transcript-api/youtube-transcript-api/youtube_transcript_api/__main__.py
8,9
1,16
main
9,14
9,14
import sys import logging from ._cli import YouTubeTranscriptCli def main(): FILL_FUNC_BODYif __name__ == '__main__': main()
import sys import logging from ._cli import YouTubeTranscriptCli def main(): FILL_FUNC_BODYif __name__ == '__main__': main()
logging.basicConfig() print(YouTubeTranscriptCli(sys.argv[1:]).run())
logging.basicConfig() print(YouTubeTranscriptCli(sys.argv[1:]).run())
2
50
36
86
import sys import logging from ._cli import YouTubeTranscriptCli def main(): FILL_FUNC_BODYif __name__ == '__main__': main()
import sys import logging from ._cli import YouTubeTranscriptCli def main(): FILL_FUNC_BODYif __name__ == '__main__': main()
36,625
/home/hieuvd/dung_repo/raw/stars_02/jdepoix_youtube-transcript-api/youtube-transcript-api
/home/hieuvd/dung_repo/raw/stars_02/jdepoix_youtube-transcript-api/youtube-transcript-api/youtube_transcript_api/_api.py
73,76
17,149
get_transcripts
YouTubeTranscriptApi
98,114
76,114
class YouTubeTranscriptApi(object): @classmethod def list_transcripts(cls, video_id, proxies=None, cookies=None): """ Retrieves the list of transcripts which are available for a given video. It returns a `TranscriptList` object which is iterable and provides methods to filter the list of...
class YouTubeTranscriptApi(object): @classmethod def list_transcripts(cls, video_id, proxies=None, cookies=None): """ Retrieves the list of transcripts which are available for a given video. It returns a `TranscriptList` object which is iterable and provides methods to filter the list of...
assert isinstance(video_ids, list), "`video_ids` must be a list of strings" data = {} unretrievable_videos = [] for video_id in video_ids: try: data[video_id] = cls.get_transcript(video_id, languages, proxies, cookies, preserve_formatting) except...
""" Retrieves the transcripts for a list of videos. :param video_ids: a list of youtube video ids :type video_ids: list[str] :param languages: A list of language codes in a descending priority. For example, if this is set to ['de', 'en'] it will first try to fetch the ge...
41
1,641
160
1,801
import requests try: # pragma: no cover import http.cookiejar as cookiejar CookieLoadError = (FileNotFoundError, cookiejar.LoadError) except ImportError: # pragma: no cover import cookielib as cookiejar CookieLoadError = IOError from ._transcripts import TranscriptListFetcher from ._errors import ( ...
import requests try: # pragma: no cover import http.cookiejar as cookiejar CookieLoadError = (FileNotFoundError, cookiejar.LoadError) except ImportError: # pragma: no cover import cookielib as cookiejar CookieLoadError = IOError from ._transcripts import TranscriptListFetcher from ._errors import ( ...
36,626
/home/hieuvd/dung_repo/raw/stars_02/jdepoix_youtube-transcript-api/youtube-transcript-api
/home/hieuvd/dung_repo/raw/stars_02/jdepoix_youtube-transcript-api/youtube-transcript-api/youtube_transcript_api/_cli.py
56,57
8,136
_parse_args
YouTubeTranscriptCli
57,133
57,133
class YouTubeTranscriptCli(object): def __init__(self, args): self._args = args def run(self): parsed_args = self._parse_args() if parsed_args.exclude_manually_created and parsed_args.exclude_generated: return '' proxies = None if parsed_args.http_proxy != ...
class YouTubeTranscriptCli(object): def __init__(self, args): self._args = args def run(self): parsed_args = self._parse_args() if parsed_args.exclude_manually_created and parsed_args.exclude_generated: return '' proxies = None if parsed_args.http_proxy != ...
parser = argparse.ArgumentParser( description=( 'This is an python API which allows you to get the transcripts/subtitles for a given YouTube video. ' 'It also works for automatically generated subtitles and it does not require a headless browser, like ' ...
parser = argparse.ArgumentParser( description=( 'This is an python API which allows you to get the transcripts/subtitles for a given YouTube video. ' 'It also works for automatically generated subtitles and it does not require a headless browser, like ' ...
286
587
839
1,426
import argparse from ._api import YouTubeTranscriptApi from .formatters import FormatterLoader class YouTubeTranscriptCli(object): def __init__(self, args): self._args = args def run(self): parsed_args = self._parse_args() if parsed_args.exclude_manually_created and parsed_args.exc...
import argparse from ._api import YouTubeTranscriptApi from .formatters import FormatterLoader class YouTubeTranscriptCli(object): def __init__(self, args): self._args = args def run(self): parsed_args = self._parse_args() if parsed_args.exclude_manually_created and parsed_args.exc...
36,627
/home/hieuvd/dung_repo/raw/stars_02/jdepoix_youtube-transcript-api/youtube-transcript-api
/home/hieuvd/dung_repo/raw/stars_02/jdepoix_youtube-transcript-api/youtube-transcript-api/youtube_transcript_api/_errors.py
24,25
4,38
_build_error_message
CouldNotRetrieveTranscript
25,33
25,33
class CouldNotRetrieveTranscript(Exception): """ Raised if a transcript could not be retrieved. """ ERROR_MESSAGE = '\nCould not retrieve a transcript for the video {video_url}!' CAUSE_MESSAGE_INTRO = ' This is most likely caused by:\n\n{cause}' CAUSE_MESSAGE = '' GITHUB_REFERRAL = ( ...
class CouldNotRetrieveTranscript(Exception): """ Raised if a transcript could not be retrieved. """ ERROR_MESSAGE = '\nCould not retrieve a transcript for the video {video_url}!' CAUSE_MESSAGE_INTRO = ' This is most likely caused by:\n\n{cause}' CAUSE_MESSAGE = '' GITHUB_REFERRAL = ( ...
cause = self.cause error_message = self.ERROR_MESSAGE.format(video_url=WATCH_URL.format(video_id=self.video_id)) if cause: error_message += self.CAUSE_MESSAGE_INTRO.format(cause=cause) + self.GITHUB_REFERRAL return error_message
cause = self.cause error_message = self.ERROR_MESSAGE.format(video_url=WATCH_URL.format(video_id=self.video_id)) if cause: error_message += self.CAUSE_MESSAGE_INTRO.format(cause=cause) + self.GITHUB_REFERRAL return error_message
15
318
100
418
from ._settings import WATCH_URL class CouldNotRetrieveTranscript(Exception): """ Raised if a transcript could not be retrieved. """ ERROR_MESSAGE = '\nCould not retrieve a transcript for the video {video_url}!' CAUSE_MESSAGE_INTRO = ' This is most likely caused by:\n\n{cause}' CAUSE_MESSAGE =...
from ._settings import WATCH_URL class CouldNotRetrieveTranscript(Exception): """ Raised if a transcript could not be retrieved. """ ERROR_MESSAGE = '\nCould not retrieve a transcript for the video {video_url}!' CAUSE_MESSAGE_INTRO = ' This is most likely caused by:\n\n{cause}' CAUSE_MESSAGE =...
36,628
/home/hieuvd/dung_repo/raw/stars_02/jdepoix_youtube-transcript-api/youtube-transcript-api
/home/hieuvd/dung_repo/raw/stars_02/jdepoix_youtube-transcript-api/youtube-transcript-api/youtube_transcript_api/_errors.py
115,117
104,121
cause
NoTranscriptFound
117,121
117,121
class NoTranscriptFound(CouldNotRetrieveTranscript): CAUSE_MESSAGE = ( 'No transcripts were found for any of the requested language codes: {requested_language_codes}\n\n' '{transcript_data}' ) def __init__(self, video_id, requested_language_codes, transcript_data): self._requested_l...
class NoTranscriptFound(CouldNotRetrieveTranscript): CAUSE_MESSAGE = ( 'No transcripts were found for any of the requested language codes: {requested_language_codes}\n\n' '{transcript_data}' ) def __init__(self, video_id, requested_language_codes, transcript_data): self._requested_l...
return self.CAUSE_MESSAGE.format( requested_language_codes=self._requested_language_codes, transcript_data=str(self._transcript_data), )
return self.CAUSE_MESSAGE.format( requested_language_codes=self._requested_language_codes, transcript_data=str(self._transcript_data), )
5
162
56
218
from ._settings import WATCH_URL class CouldNotRetrieveTranscript(Exception): """ Raised if a transcript could not be retrieved. """ ERROR_MESSAGE = '\nCould not retrieve a transcript for the video {video_url}!' CAUSE_MESSAGE_INTRO = ' This is most likely caused by:\n\n{cause}' CAUSE_MESSAGE =...
from ._settings import WATCH_URL class CouldNotRetrieveTranscript(Exception): """ Raised if a transcript could not be retrieved. """ ERROR_MESSAGE = '\nCould not retrieve a transcript for the video {video_url}!' CAUSE_MESSAGE_INTRO = ' This is most likely caused by:\n\n{cause}' CAUSE_MESSAGE =...
36,629
/home/hieuvd/dung_repo/raw/stars_02/jdepoix_youtube-transcript-api/youtube-transcript-api
/home/hieuvd/dung_repo/raw/stars_02/jdepoix_youtube-transcript-api/youtube-transcript-api/youtube_transcript_api/_errors.py
45,47
38,52
cause
YouTubeRequestFailed
47,52
47,52
class YouTubeRequestFailed(CouldNotRetrieveTranscript): CAUSE_MESSAGE = 'Request to YouTube failed: {reason}' def __init__(self, video_id, http_error): self.reason = str(http_error) super(YouTubeRequestFailed, self).__init__(video_id) @property def cause(self): FILL_FUNC_BODY
class YouTubeRequestFailed(CouldNotRetrieveTranscript): CAUSE_MESSAGE = 'Request to YouTube failed: {reason}' def __init__(self, video_id, http_error): self.reason = str(http_error) super(YouTubeRequestFailed, self).__init__(video_id) @property def cause(self): FILL_FUNC_BODY
return self.CAUSE_MESSAGE.format( reason=self.reason, )
return self.CAUSE_MESSAGE.format( reason=self.reason, )
4
100
32
132
from ._settings import WATCH_URL class CouldNotRetrieveTranscript(Exception): """ Raised if a transcript could not be retrieved. """ ERROR_MESSAGE = '\nCould not retrieve a transcript for the video {video_url}!' CAUSE_MESSAGE_INTRO = ' This is most likely caused by:\n\n{cause}' CAUSE_MESSAGE =...
from ._settings import WATCH_URL class CouldNotRetrieveTranscript(Exception): """ Raised if a transcript could not be retrieved. """ ERROR_MESSAGE = '\nCould not retrieve a transcript for the video {video_url}!' CAUSE_MESSAGE_INTRO = ' This is most likely caused by:\n\n{cause}' CAUSE_MESSAGE =...
36,630
/home/hieuvd/dung_repo/raw/stars_02/jdepoix_youtube-transcript-api/youtube-transcript-api
/home/hieuvd/dung_repo/raw/stars_02/jdepoix_youtube-transcript-api/youtube-transcript-api/youtube_transcript_api/formatters.py
14,15
6,23
format_transcript
Formatter
15,18
15,18
class Formatter(object): """Formatter should be used as an abstract base class. Formatter classes should inherit from this class and implement their own .format() method which should return a string. A transcript is represented by a List of Dictionary items. """ def format_transcript(self, tra...
class Formatter(object): """Formatter should be used as an abstract base class. Formatter classes should inherit from this class and implement their own .format() method which should return a string. A transcript is represented by a List of Dictionary items. """ def format_transcript(self, tra...
raise NotImplementedError('A subclass of Formatter must implement ' \ 'their own .format_transcript() method.')
raise NotImplementedError('A subclass of Formatter must implement ' \ 'their own .format_transcript() method.')
13
146
37
183
import json import pprint class Formatter(object): """Formatter should be used as an abstract base class. Formatter classes should inherit from this class and implement their own .format() method which should return a string. A transcript is represented by a List of Dictionary items. """ de...
import json import pprint class Formatter(object): """Formatter should be used as an abstract base class. Formatter classes should inherit from this class and implement their own .format() method which should return a string. A transcript is represented by a List of Dictionary items. """ de...
36,631
/home/hieuvd/dung_repo/raw/stars_02/jdepoix_youtube-transcript-api/youtube-transcript-api
/home/hieuvd/dung_repo/raw/stars_02/jdepoix_youtube-transcript-api/youtube-transcript-api/youtube_transcript_api/formatters.py
179,180
160,189
load
FormatterLoader
186,189
180,189
class FormatterLoader(object): TYPES = { 'json': JSONFormatter, 'pretty': PrettyPrintFormatter, 'text': TextFormatter, 'webvtt': WebVTTFormatter, 'srt' : SRTFormatter, } class UnknownFormatterType(Exception): def __init__(self, formatter_type): su...
class FormatterLoader(object): TYPES = { 'json': JSONFormatter, 'pretty': PrettyPrintFormatter, 'text': TextFormatter, 'webvtt': WebVTTFormatter, 'srt' : SRTFormatter, } class UnknownFormatterType(Exception): def __init__(self, formatter_type): su...
if formatter_type not in FormatterLoader.TYPES.keys(): raise FormatterLoader.UnknownFormatterType(formatter_type) return FormatterLoader.TYPES[formatter_type]()
""" Loads the Formatter for the given formatter type. :param formatter_type: :return: Formatter object """ if formatter_type not in FormatterLoader.TYPES.keys(): raise FormatterLoader.UnknownFormatterType(formatter_type) return FormatterLoader.TYPES[f...
9
261
56
317
import json import pprint class Formatter(object): """Formatter should be used as an abstract base class. Formatter classes should inherit from this class and implement their own .format() method which should return a string. A transcript is represented by a List of Dictionary items. """ de...
import json import pprint class Formatter(object): """Formatter should be used as an abstract base class. Formatter classes should inherit from this class and implement their own .format() method which should return a string. A transcript is represented by a List of Dictionary items. """ de...
36,632
/home/hieuvd/dung_repo/raw/stars_02/jdepoix_youtube-transcript-api/youtube-transcript-api
/home/hieuvd/dung_repo/raw/stars_02/jdepoix_youtube-transcript-api/youtube-transcript-api/youtube_transcript_api/formatters.py
44,45
43,63
format_transcript
JSONFormatter
51,53
45,53
class JSONFormatter(Formatter): def format_transcript(self, transcript, **kwargs): FILL_FUNC_BODY def format_transcripts(self, transcripts, **kwargs): """Converts a list of transcripts into a JSON string. :param transcripts: :return: A JSON string representation of the transcript.' ...
class JSONFormatter(Formatter): def format_transcript(self, transcript, **kwargs): """Converts a transcript into a JSON string. :param transcript: :return: A JSON string representation of the transcript.' :rtype str """ FILL_FUNC_BODY def format_transcripts(self, transcri...
return json.dumps(transcript, **kwargs)
"""Converts a transcript into a JSON string. :param transcript: :return: A JSON string representation of the transcript.' :rtype str """ return json.dumps(transcript, **kwargs)
3
166
17
183
import json import pprint class Formatter(object): """Formatter should be used as an abstract base class. Formatter classes should inherit from this class and implement their own .format() method which should return a string. A transcript is represented by a List of Dictionary items. """ de...
import json import pprint class Formatter(object): """Formatter should be used as an abstract base class. Formatter classes should inherit from this class and implement their own .format() method which should return a string. A transcript is represented by a List of Dictionary items. """ de...
36,633
/home/hieuvd/dung_repo/raw/stars_02/jdepoix_youtube-transcript-api/youtube-transcript-api
/home/hieuvd/dung_repo/raw/stars_02/jdepoix_youtube-transcript-api/youtube-transcript-api/youtube_transcript_api/formatters.py
33,34
23,43
format_transcripts
PrettyPrintFormatter
40,43
34,43
class PrettyPrintFormatter(Formatter): def format_transcript(self, transcript, **kwargs): """Pretty prints a transcript. :param transcript: :return: A pretty printed string representation of the transcript.' :rtype str """ return pprint.pformat(transcript, **kwargs) ...
class PrettyPrintFormatter(Formatter): def format_transcript(self, transcript, **kwargs): """Pretty prints a transcript. :param transcript: :return: A pretty printed string representation of the transcript.' :rtype str """ return pprint.pformat(transcript, **kwargs) ...
return self.format_transcript(transcripts, **kwargs)
"""Pretty prints a list of transcripts. :param transcripts: :return: A pretty printed string representation of the transcripts.' :rtype str """ return self.format_transcript(transcripts, **kwargs)
3
160
22
182
import json import pprint class Formatter(object): """Formatter should be used as an abstract base class. Formatter classes should inherit from this class and implement their own .format() method which should return a string. A transcript is represented by a List of Dictionary items. """ de...
import json import pprint class Formatter(object): """Formatter should be used as an abstract base class. Formatter classes should inherit from this class and implement their own .format() method which should return a string. A transcript is represented by a List of Dictionary items. """ de...
36,634
/home/hieuvd/dung_repo/raw/stars_02/jdepoix_youtube-transcript-api/youtube-transcript-api
/home/hieuvd/dung_repo/raw/stars_02/jdepoix_youtube-transcript-api/youtube-transcript-api/youtube_transcript_api/formatters.py
139,140
138,149
_format_timestamp
SRTFormatter
140,142
140,142
class SRTFormatter(_TextBasedFormatter): def _format_timestamp(self, hours, mins, secs, ms): FILL_FUNC_BODY def _format_transcript_header(self, lines): return "\n\n".join(lines) + "\n" def _format_transcript_helper(self, i, time_text, line): return "{}\n{}\n{}".format(i + 1, time_text, line[...
class SRTFormatter(_TextBasedFormatter): def _format_timestamp(self, hours, mins, secs, ms): FILL_FUNC_BODY def _format_transcript_header(self, lines): return "\n\n".join(lines) + "\n" def _format_transcript_helper(self, i, time_text, line): return "{}\n{}\n{}".format(i + 1, time_text, line[...
return "{:02d}:{:02d}:{:02d},{:03d}".format(hours, mins, secs, ms)
return "{:02d}:{:02d}:{:02d},{:03d}".format(hours, mins, secs, ms)
5
123
45
168
import json import pprint class Formatter(object): """Formatter should be used as an abstract base class. Formatter classes should inherit from this class and implement their own .format() method which should return a string. A transcript is represented by a List of Dictionary items. """ de...
import json import pprint class Formatter(object): """Formatter should be used as an abstract base class. Formatter classes should inherit from this class and implement their own .format() method which should return a string. A transcript is represented by a List of Dictionary items. """ de...
36,635
/home/hieuvd/dung_repo/raw/stars_02/jdepoix_youtube-transcript-api/youtube-transcript-api
/home/hieuvd/dung_repo/raw/stars_02/jdepoix_youtube-transcript-api/youtube-transcript-api/youtube_transcript_api/formatters.py
73,74
63,82
format_transcripts
TextFormatter
80,82
74,82
class TextFormatter(Formatter): def format_transcript(self, transcript, **kwargs): """Converts a transcript into plain text with no timestamps. :param transcript: :return: all transcript text lines separated by newline breaks.' :rtype str """ return '\n'.join(line['t...
class TextFormatter(Formatter): def format_transcript(self, transcript, **kwargs): """Converts a transcript into plain text with no timestamps. :param transcript: :return: all transcript text lines separated by newline breaks.' :rtype str """ return '\n'.join(line['t...
return '\n\n\n'.join([self.format_transcript(transcript, **kwargs) for transcript in transcripts])
"""Converts a list of transcripts into plain text with no timestamps. :param transcripts: :return: all transcript text lines separated by newline breaks.' :rtype str """ return '\n\n\n'.join([self.format_transcript(transcript, **kwargs) for transcript in transcripts])
7
178
36
214
import json import pprint class Formatter(object): """Formatter should be used as an abstract base class. Formatter classes should inherit from this class and implement their own .format() method which should return a string. A transcript is represented by a List of Dictionary items. """ de...
import json import pprint class Formatter(object): """Formatter should be used as an abstract base class. Formatter classes should inherit from this class and implement their own .format() method which should return a string. A transcript is represented by a List of Dictionary items. """ de...
36,636
/home/hieuvd/dung_repo/raw/stars_02/jdepoix_youtube-transcript-api/youtube-transcript-api
/home/hieuvd/dung_repo/raw/stars_02/jdepoix_youtube-transcript-api/youtube-transcript-api/youtube_transcript_api/formatters.py
153,154
149,160
_format_transcript_header
WebVTTFormatter
154,156
154,156
class WebVTTFormatter(_TextBasedFormatter): def _format_timestamp(self, hours, mins, secs, ms): return "{:02d}:{:02d}:{:02d}.{:03d}".format(hours, mins, secs, ms) def _format_transcript_header(self, lines): FILL_FUNC_BODY def _format_transcript_helper(self, i, time_text, line): return "{}\n{...
class WebVTTFormatter(_TextBasedFormatter): def _format_timestamp(self, hours, mins, secs, ms): return "{:02d}:{:02d}:{:02d}.{:03d}".format(hours, mins, secs, ms) def _format_transcript_header(self, lines): FILL_FUNC_BODY def _format_transcript_helper(self, i, time_text, line): return "{}\n{...
return "WEBVTT\n\n" + "\n\n".join(lines) + "\n"
return "WEBVTT\n\n" + "\n\n".join(lines) + "\n"
6
142
30
172
import json import pprint class Formatter(object): """Formatter should be used as an abstract base class. Formatter classes should inherit from this class and implement their own .format() method which should return a string. A transcript is represented by a List of Dictionary items. """ de...
import json import pprint class Formatter(object): """Formatter should be used as an abstract base class. Formatter classes should inherit from this class and implement their own .format() method which should return a string. A transcript is represented by a List of Dictionary items. """ de...
36,637
/home/hieuvd/dung_repo/raw/stars_02/jdepoix_youtube-transcript-api/youtube-transcript-api
/home/hieuvd/dung_repo/raw/stars_02/jdepoix_youtube-transcript-api/youtube-transcript-api/youtube_transcript_api/formatters.py
95,96
82,138
_seconds_to_timestamp
_TextBasedFormatter
108,115
96,115
class _TextBasedFormatter(TextFormatter): def _format_timestamp(self, hours, mins, secs, ms): raise NotImplementedError('A subclass of _TextBasedFormatter must implement ' \ 'their own .format_timestamp() method.') def _format_transcript_header(self, lines): raise NotImplementedErro...
class _TextBasedFormatter(TextFormatter): def _format_timestamp(self, hours, mins, secs, ms): raise NotImplementedError('A subclass of _TextBasedFormatter must implement ' \ 'their own .format_timestamp() method.') def _format_transcript_header(self, lines): raise NotImplementedErro...
time = float(time) hours_float, remainder = divmod(time, 3600) mins_float, secs_float = divmod(remainder, 60) hours, mins, secs = int(hours_float), int(mins_float), int(secs_float) ms = int(round((time - int(time))*1000, 2)) return self._format_timestamp(hours, mins, secs...
"""Helper that converts `time` into a transcript cue timestamp. :reference: https://www.w3.org/TR/webvtt1/#webvtt-timestamp :param time: a float representing time in seconds. :type time: float :return: a string formatted as a cue timestamp, 'HH:MM:SS.MS' :rtype str ...
31
593
130
723
import json import pprint class Formatter(object): """Formatter should be used as an abstract base class. Formatter classes should inherit from this class and implement their own .format() method which should return a string. A transcript is represented by a List of Dictionary items. """ de...
import json import pprint class Formatter(object): """Formatter should be used as an abstract base class. Formatter classes should inherit from this class and implement their own .format() method which should return a string. A transcript is represented by a List of Dictionary items. """ de...
36,638
/home/hieuvd/dung_repo/raw/stars_02/jendrikseipp_vulture/vulture
/home/hieuvd/dung_repo/raw/stars_02/jendrikseipp_vulture/vulture/dev/make-release-notes.py
30,31
1,43
check
31,39
31,39
#! /usr/bin/env python3 import re import sys _, VERSION, CHANGELOG, LIST = sys.argv HEADER_REGEX = rf"# {VERSION} \(\d\d\d\d-\d\d-\d\d\)\n" notes_list = [] with open(CHANGELOG) as f: first_line = next(f) if not re.match(HEADER_REGEX, first_line): sys.exit( f'First changelog line "{first...
#! /usr/bin/env python3 import re import sys _, VERSION, CHANGELOG, LIST = sys.argv HEADER_REGEX = rf"# {VERSION} \(\d\d\d\d-\d\d-\d\d\)\n" notes_list = [] with open(CHANGELOG) as f: first_line = next(f) if not re.match(HEADER_REGEX, first_line): sys.exit( f'First changelog line "{first...
print("*" * 60) print(text) print("*" * 60) response = input("Accept this %s (Y/n)? " % name).strip().lower() if response and response != "y": sys.exit(1)
print("*" * 60) print(text) print("*" * 60) response = input("Accept this %s (Y/n)? " % name).strip().lower() if response and response != "y": sys.exit(1)
23
314
78
392
#! /usr/bin/env python3 import re import sys _, VERSION, CHANGELOG, LIST = sys.argv HEADER_REGEX = rf"# {VERSION} \(\d\d\d\d-\d\d-\d\d\)\n" notes_list = [] with open(CHANGELOG) as f: first_line = next(f) if not re.match(HEADER_REGEX, first_line): sys.exit( f'First changelog line "{first...
#! /usr/bin/env python3 import re import sys _, VERSION, CHANGELOG, LIST = sys.argv HEADER_REGEX = rf"# {VERSION} \(\d\d\d\d-\d\d-\d\d\)\n" notes_list = [] with open(CHANGELOG) as f: first_line = next(f) if not re.match(HEADER_REGEX, first_line): sys.exit( f'First changelog line "{first...
36,639
/home/hieuvd/dung_repo/raw/stars_02/jendrikseipp_vulture/vulture
/home/hieuvd/dung_repo/raw/stars_02/jendrikseipp_vulture/vulture/setup.py
9,10
1,59
find_version
10,20
10,20
#! /usr/bin/env python import pathlib import re import setuptools def find_version(*parts): FILL_FUNC_BODYwith open("README.md") as f1, open("CHANGELOG.md") as f2: long_description = f1.read() + "\n\n" + f2.read() with open("requirements.txt") as f: install_requires = f.read().splitlines() setuptools.setu...
#! /usr/bin/env python import pathlib import re import setuptools def find_version(*parts): FILL_FUNC_BODYwith open("README.md") as f1, open("CHANGELOG.md") as f2: long_description = f1.read() + "\n\n" + f2.read() with open("requirements.txt") as f: install_requires = f.read().splitlines() setuptools.setu...
here = pathlib.Path(__file__).parent version_file = here.joinpath(*parts).read_text() version_match = re.search( r"^__version__ = ['\"]([^'\"]*)['\"]$", version_file, re.M ) if version_match: return version_match.group(1) raise RuntimeError("Unable to find version string.")
here = pathlib.Path(__file__).parent version_file = here.joinpath(*parts).read_text() version_match = re.search( r"^__version__ = ['\"]([^'\"]*)['\"]$", version_file, re.M ) if version_match: return version_match.group(1) raise RuntimeError("Unable to find version string.")
25
533
115
648
#! /usr/bin/env python import pathlib import re import setuptools def find_version(*parts): FILL_FUNC_BODYwith open("README.md") as f1, open("CHANGELOG.md") as f2: long_description = f1.read() + "\n\n" + f2.read() with open("requirements.txt") as f: install_requires = f.read().splitlines() setuptools.setu...
#! /usr/bin/env python import pathlib import re import setuptools def find_version(*parts): FILL_FUNC_BODYwith open("README.md") as f1, open("CHANGELOG.md") as f2: long_description = f1.read() + "\n\n" + f2.read() with open("requirements.txt") as f: install_requires = f.read().splitlines() setuptools.setu...
36,642
/home/hieuvd/dung_repo/raw/stars_02/jendrikseipp_vulture/vulture
/home/hieuvd/dung_repo/raw/stars_02/jendrikseipp_vulture/vulture/vulture/core.py
169,170
117,194
get_whitelist_string
Item
170,181
170,181
class Item: """ Hold the name, type and location of defined code. """ __slots__ = ( "name", "typ", "filename", "first_lineno", "last_lineno", "message", "confidence", ) def __init__( self, name, typ, filena...
class Item: """ Hold the name, type and location of defined code. """ __slots__ = ( "name", "typ", "filename", "first_lineno", "last_lineno", "message", "confidence", ) def __init__( self, name, typ, filena...
filename = utils.format_path(self.filename) if self.typ == "unreachable_code": return f"# {self.message} ({filename}:{self.first_lineno})" else: prefix = "" if self.typ in ["attribute", "method", "property"]: prefix = "_." return "{...
filename = utils.format_path(self.filename) if self.typ == "unreachable_code": return f"# {self.message} ({filename}:{self.first_lineno})" else: prefix = "" if self.typ in ["attribute", "method", "property"]: prefix = "_." return "{...
36
512
139
651
import ast from fnmatch import fnmatch, fnmatchcase from pathlib import Path import pkgutil import re import string import sys from vulture import lines from vulture import noqa from vulture import utils from vulture.config import InputError, make_config from vulture.utils import ExitCode DEFAULT_CONFIDENCE = 60 IG...
import ast from fnmatch import fnmatch, fnmatchcase from pathlib import Path import pkgutil import re import string import sys from vulture import lines from vulture import noqa from vulture import utils from vulture.config import InputError, make_config from vulture.utils import ExitCode DEFAULT_CONFIDENCE = 60 IG...
36,644
/home/hieuvd/dung_repo/raw/stars_02/jendrikseipp_vulture/vulture
/home/hieuvd/dung_repo/raw/stars_02/jendrikseipp_vulture/vulture/vulture/lines.py
1,2
1,19
get_last_line_number
2,5
2,5
def get_last_line_number(node): FILL_FUNC_BODYdef get_first_line_number(node): """ From Python 3.8 onwards, lineno for decorated objects is the line at which the object definition starts, which is different from what Python < 3.8 reported -- the lineno of the first decorator. To preserve this behaviour ...
def get_last_line_number(node): FILL_FUNC_BODYdef get_first_line_number(node): """ From Python 3.8 onwards, lineno for decorated objects is the line at which the object definition starts, which is different from what Python < 3.8 reported -- the lineno of the first decorator. To preserve this behaviour ...
return node.end_lineno
return node.end_lineno
2
201
14
215
def get_last_line_number(node): FILL_FUNC_BODYdef get_first_line_number(node): """ From Python 3.8 onwards, lineno for decorated objects is the line at which the object definition starts, which is different from what Python < 3.8 reported -- the lineno of the first decorator. To preserve this behaviour ...
def get_last_line_number(node): FILL_FUNC_BODYdef get_first_line_number(node): """ From Python 3.8 onwards, lineno for decorated objects is the line at which the object definition starts, which is different from what Python < 3.8 reported -- the lineno of the first decorator. To preserve this behaviour ...
36,645
/home/hieuvd/dung_repo/raw/stars_02/jendrikseipp_vulture/vulture
/home/hieuvd/dung_repo/raw/stars_02/jendrikseipp_vulture/vulture/vulture/noqa.py
31,32
1,45
parse_noqa
32,42
32,42
from collections import defaultdict import re NOQA_REGEXP = re.compile( # Use the same regex as flake8 does. # https://github.com/pycqa/flake8/blob/main/src/flake8/defaults.py # We're looking for items that look like this: # `# noqa` # `# noqa: E123` # `# noqa: E123,W451,F921` # `# NoQA: E1...
from collections import defaultdict import re NOQA_REGEXP = re.compile( # Use the same regex as flake8 does. # https://github.com/pycqa/flake8/blob/main/src/flake8/defaults.py # We're looking for items that look like this: # `# noqa` # `# noqa: E123` # `# noqa: E123,W451,F921` # `# NoQA: E1...
noqa_lines = defaultdict(set) for lineno, line in enumerate(code, start=1): match = NOQA_REGEXP.search(line) if match: for error_code in _parse_error_codes(match): error_code = NOQA_CODE_MAP.get(error_code, error_code) noqa_lines[error_code].add(lineno...
noqa_lines = defaultdict(set) for lineno, line in enumerate(code, start=1): match = NOQA_REGEXP.search(line) if match: for error_code in _parse_error_codes(match): error_code = NOQA_CODE_MAP.get(error_code, error_code) noqa_lines[error_code].add(lineno...
25
442
129
571
from collections import defaultdict import re NOQA_REGEXP = re.compile( # Use the same regex as flake8 does. # https://github.com/pycqa/flake8/blob/main/src/flake8/defaults.py # We're looking for items that look like this: # `# noqa` # `# noqa: E123` # `# noqa: E123,W451,F921` # `# NoQA: E1...
from collections import defaultdict import re NOQA_REGEXP = re.compile( # Use the same regex as flake8 does. # https://github.com/pycqa/flake8/blob/main/src/flake8/defaults.py # We're looking for items that look like this: # `# noqa` # `# noqa: E123` # `# noqa: E123,W451,F921` # `# NoQA: E1...
36,646
/home/hieuvd/dung_repo/raw/stars_02/jorgebastida_awslogs/awslogs
/home/hieuvd/dung_repo/raw/stars_02/jorgebastida_awslogs/awslogs/awslogs/exceptions.py
5,6
1,9
hint
BaseAWSLogsException
6,9
6,9
class BaseAWSLogsException(Exception): code = 1 def hint(self): FILL_FUNC_BODY
class BaseAWSLogsException(Exception): code = 1 def hint(self): FILL_FUNC_BODY
return "Unknown Error."
return "Unknown Error."
3
35
12
47
class BaseAWSLogsException(Exception): code = 1 def hint(self): FILL_FUNC_BODYclass UnknownDateError(BaseAWSLogsException): code = 3 def hint(self): return f"awslogs doesn't understand '{self.args[0]}' as a date." class TooManyStreamsFilteredError(BaseAWSLogsException): code = 6 ...
class BaseAWSLogsException(Exception): code = 1 def hint(self): FILL_FUNC_BODYclass UnknownDateError(BaseAWSLogsException): code = 3 def hint(self): return f"awslogs doesn't understand '{self.args[0]}' as a date." class TooManyStreamsFilteredError(BaseAWSLogsException): code = 6 ...
36,647
/home/hieuvd/dung_repo/raw/stars_02/jorgebastida_awslogs/awslogs
/home/hieuvd/dung_repo/raw/stars_02/jorgebastida_awslogs/awslogs/awslogs/exceptions.py
34,35
30,38
hint
NoStreamsFilteredError
35,38
35,38
class NoStreamsFilteredError(BaseAWSLogsException): code = 7 def hint(self): FILL_FUNC_BODY
class NoStreamsFilteredError(BaseAWSLogsException): code = 7 def hint(self): FILL_FUNC_BODY
return ( f"No streams match your pattern '{self.args[0]}' for the given time period." )
return ( f"No streams match your pattern '{self.args[0]}' for the given time period." )
14
40
34
74
class BaseAWSLogsException(Exception): code = 1 def hint(self): return "Unknown Error." class UnknownDateError(BaseAWSLogsException): code = 3 def hint(self): return f"awslogs doesn't understand '{self.args[0]}' as a date." class TooManyStreamsFilteredError(BaseAWSLogsException):...
class BaseAWSLogsException(Exception): code = 1 def hint(self): return "Unknown Error." class UnknownDateError(BaseAWSLogsException): code = 3 def hint(self): return f"awslogs doesn't understand '{self.args[0]}' as a date." class TooManyStreamsFilteredError(BaseAWSLogsException):...
36,648
/home/hieuvd/dung_repo/raw/stars_02/jorgebastida_awslogs/awslogs
/home/hieuvd/dung_repo/raw/stars_02/jorgebastida_awslogs/awslogs/awslogs/exceptions.py
21,22
17,30
hint
TooManyStreamsFilteredError
22,30
22,30
class TooManyStreamsFilteredError(BaseAWSLogsException): code = 6 def hint(self): FILL_FUNC_BODY
class TooManyStreamsFilteredError(BaseAWSLogsException): code = 6 def hint(self): FILL_FUNC_BODY
return ( f"The number of streams that match your pattern '{self.args[0]}' is '{self.args[1]}'. " f"AWS API limits the number of streams you can filter by to {self.args[2]}." "It might be helpful to you to not filter streams by any " "pattern and filter the output ...
return ( f"The number of streams that match your pattern '{self.args[0]}' is '{self.args[1]}'. " f"AWS API limits the number of streams you can filter by to {self.args[2]}." "It might be helpful to you to not filter streams by any " "pattern and filter the output ...
48
41
104
145
class BaseAWSLogsException(Exception): code = 1 def hint(self): return "Unknown Error." class UnknownDateError(BaseAWSLogsException): code = 3 def hint(self): return f"awslogs doesn't understand '{self.args[0]}' as a date." class TooManyStreamsFilteredError(BaseAWSLogsException):...
class BaseAWSLogsException(Exception): code = 1 def hint(self): return "Unknown Error." class UnknownDateError(BaseAWSLogsException): code = 3 def hint(self): return f"awslogs doesn't understand '{self.args[0]}' as a date." class TooManyStreamsFilteredError(BaseAWSLogsException):...
36,649
/home/hieuvd/dung_repo/raw/stars_02/jorgebastida_awslogs/awslogs
/home/hieuvd/dung_repo/raw/stars_02/jorgebastida_awslogs/awslogs/awslogs/exceptions.py
13,14
9,17
hint
UnknownDateError
14,17
14,17
class UnknownDateError(BaseAWSLogsException): code = 3 def hint(self): FILL_FUNC_BODY
class UnknownDateError(BaseAWSLogsException): code = 3 def hint(self): FILL_FUNC_BODY
return f"awslogs doesn't understand '{self.args[0]}' as a date."
return f"awslogs doesn't understand '{self.args[0]}' as a date."
8
37
30
67
class BaseAWSLogsException(Exception): code = 1 def hint(self): return "Unknown Error." class UnknownDateError(BaseAWSLogsException): code = 3 def hint(self): FILL_FUNC_BODYclass TooManyStreamsFilteredError(BaseAWSLogsException): code = 6 def hint(self): return ( ...
class BaseAWSLogsException(Exception): code = 1 def hint(self): return "Unknown Error." class UnknownDateError(BaseAWSLogsException): code = 3 def hint(self): FILL_FUNC_BODYclass TooManyStreamsFilteredError(BaseAWSLogsException): code = 6 def hint(self): return ( ...
36,650
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/examples/scripts/ecomerce_reviews_bert.py
83,84
67,93
forward
CustomBertModel
84,88
84,88
class CustomBertModel(nn.Module): def __init__( self, model_name: str = "distilbert-base-uncased", freeze_bert: bool = False, ): super(CustomBertModel, self).__init__() self.bert = DistilBertModel.from_pretrained( model_name, ) if freeze_bert...
class CustomBertModel(nn.Module): def __init__( self, model_name: str = "distilbert-base-uncased", freeze_bert: bool = False, ): super(CustomBertModel, self).__init__() self.bert = DistilBertModel.from_pretrained( model_name, ) if freeze_bert...
attn_mask = (X_inp != 0).type(torch.int8) outputs = self.bert(input_ids=X_inp, attention_mask=attn_mask) return outputs[0][:, 0, :]
attn_mask = (X_inp != 0).type(torch.int8) outputs = self.bert(input_ids=X_inp, attention_mask=attn_mask) return outputs[0][:, 0, :]
13
181
69
250
import numpy as np import torch import pandas as pd from torch import Tensor, nn from transformers import DistilBertModel, DistilBertTokenizer from sklearn.metrics import ( f1_score, recall_score, accuracy_score, precision_score, confusion_matrix, ) from sklearn.model_selection import train_test_spl...
import numpy as np import torch import pandas as pd from torch import Tensor, nn from transformers import DistilBertModel, DistilBertTokenizer from sklearn.metrics import ( f1_score, recall_score, accuracy_score, precision_score, confusion_matrix, ) from sklearn.model_selection import train_test_spl...
36,651
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/examples/scripts/ecomerce_reviews_bert.py
45,46
26,67
transform
Tokenizer
46,59
46,59
class Tokenizer(object): def __init__( self, pretrained_tokenizer="distilbert-base-uncased", do_lower_case=True, max_length=90, ): super(Tokenizer, self).__init__() self.pretrained_tokenizer = pretrained_tokenizer self.do_lower_case = do_lower_case ...
class Tokenizer(object): def __init__( self, pretrained_tokenizer="distilbert-base-uncased", do_lower_case=True, max_length=90, ): super(Tokenizer, self).__init__() self.pretrained_tokenizer = pretrained_tokenizer self.do_lower_case = do_lower_case ...
input_ids = [] for text in texts: encoded_sent = self.tokenizer.encode_plus( text=self._pre_rules(text), add_special_tokens=True, max_length=self.max_length, padding="max_length", truncation=True, ) ...
input_ids = [] for text in texts: encoded_sent = self.tokenizer.encode_plus( text=self._pre_rules(text), add_special_tokens=True, max_length=self.max_length, padding="max_length", truncation=True, ) ...
19
261
128
389
import numpy as np import torch import pandas as pd from torch import Tensor, nn from transformers import DistilBertModel, DistilBertTokenizer from sklearn.metrics import ( f1_score, recall_score, accuracy_score, precision_score, confusion_matrix, ) from sklearn.model_selection import train_test_spl...
import numpy as np import torch import pandas as pd from torch import Tensor, nn from transformers import DistilBertModel, DistilBertTokenizer from sklearn.metrics import ( f1_score, recall_score, accuracy_score, precision_score, confusion_matrix, ) from sklearn.model_selection import train_test_spl...
36,653
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/examples/scripts/wide_deep_for_recsys/pytorch_wide_deep_pt1.py
146,148
129,152
output_dim
SimpleEmbed
148,152
148,152
class SimpleEmbed(nn.Module): def __init__(self, vocab_size: int, embed_dim: int, pad_idx: int): super().__init__() self.vocab_size = vocab_size self.embed_dim = embed_dim self.pad_idx = pad_idx # The sequences of movies watched are simply embedded in the Kaggle # n...
class SimpleEmbed(nn.Module): def __init__(self, vocab_size: int, embed_dim: int, pad_idx: int): super().__init__() self.vocab_size = vocab_size self.embed_dim = embed_dim self.pad_idx = pad_idx # The sequences of movies watched are simply embedded in the Kaggle # n...
return self.embed_dim # In the notebook the author uses simply embeddings
return self.embed_dim # In the notebook the author uses simply embeddings
11
219
26
245
# In this script I illustrate how one coould use our library to reproduce # almost exactly the same model used in the Kaggle Notebook from pathlib import Path import numpy as np import torch import pandas as pd from torch import nn from scipy.sparse import coo_matrix from pytorch_widedeep import Trainer from pytorch...
# In this script I illustrate how one coould use our library to reproduce # almost exactly the same model used in the Kaggle Notebook from pathlib import Path import numpy as np import torch import pandas as pd from torch import nn from scipy.sparse import coo_matrix from pytorch_widedeep import Trainer from pytorch...
36,654
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/examples/scripts/wide_deep_for_recsys/pytorch_wide_deep_pt1.py
121,122
108,126
forward
Wide
122,126
122,126
class Wide(nn.Module): def __init__(self, input_dim: int, pred_dim: int): super().__init__() self.input_dim = input_dim self.pred_dim = pred_dim # The way I coded the library I never though that someone would ever # wanted to code their own wide component. However, if you d...
class Wide(nn.Module): def __init__(self, input_dim: int, pred_dim: int): super().__init__() self.input_dim = input_dim self.pred_dim = pred_dim # The way I coded the library I never though that someone would ever # wanted to code their own wide component. However, if you d...
out = self.wide_linear(X.type(torch.float32)) return out
out = self.wide_linear(X.type(torch.float32)) return out
5
170
31
201
# In this script I illustrate how one coould use our library to reproduce # almost exactly the same model used in the Kaggle Notebook from pathlib import Path import numpy as np import torch import pandas as pd from torch import nn from scipy.sparse import coo_matrix from pytorch_widedeep import Trainer from pytorch...
# In this script I illustrate how one coould use our library to reproduce # almost exactly the same model used in the Kaggle Notebook from pathlib import Path import numpy as np import torch import pandas as pd from torch import nn from scipy.sparse import coo_matrix from pytorch_widedeep import Trainer from pytorch...
36,655
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/bayesian_models/_base_bayesian_model.py
29,37
16,47
sample_elbo
BaseBayesianModel
37,47
37,47
class BaseBayesianModel(nn.Module): r"""Base model containing the two methods common to all Bayesian models""" def init(self): super().__init__() def _kl_divergence(self): kld = 0 for module in self.modules(): if isinstance(module, BayesianModule): kld +...
class BaseBayesianModel(nn.Module): r"""Base model containing the two methods common to all Bayesian models""" def init(self): super().__init__() def _kl_divergence(self): kld = 0 for module in self.modules(): if isinstance(module, BayesianModule): kld +...
outputs_l = [] kld = 0.0 for _ in range(n_samples): outputs_l.append(self(input)) kld += self._kl_divergence() outputs = torch.stack(outputs_l) complexity_cost = kld / n_batches likelihood_cost = loss_fn(outputs.mean(0), target) return out...
outputs_l = [] kld = 0.0 for _ in range(n_samples): outputs_l.append(self(input)) kld += self._kl_divergence() outputs = torch.stack(outputs_l) complexity_cost = kld / n_batches likelihood_cost = loss_fn(outputs.mean(0), target) return out...
31
189
121
310
import torch from torch import nn from pytorch_widedeep.wdtypes import Tuple, Tensor class BayesianModule(nn.Module): r"""Simply a 'hack' to facilitate the computation of the KL divergence for all Bayesian models """ def init(self): super().__init__() class BaseBayesianModel(nn.Module): ...
import torch from torch import nn from pytorch_widedeep.wdtypes import Tuple, Tensor class BayesianModule(nn.Module): r"""Simply a 'hack' to facilitate the computation of the KL divergence for all Bayesian models """ def init(self): super().__init__() class BaseBayesianModel(nn.Module): ...
36,656
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/bayesian_models/_base_bayesian_model.py
12,13
7,16
init
BayesianModule
13,16
13,16
class BayesianModule(nn.Module): r"""Simply a 'hack' to facilitate the computation of the KL divergence for all Bayesian models """ def init(self): FILL_FUNC_BODY
class BayesianModule(nn.Module): r"""Simply a 'hack' to facilitate the computation of the KL divergence for all Bayesian models """ def init(self): FILL_FUNC_BODY
super().__init__()
super().__init__()
1
59
13
72
import torch from torch import nn from pytorch_widedeep.wdtypes import Tuple, Tensor class BayesianModule(nn.Module): r"""Simply a 'hack' to facilitate the computation of the KL divergence for all Bayesian models """ def init(self): FILL_FUNC_BODYclass BaseBayesianModel(nn.Module): r"""Base mode...
import torch from torch import nn from pytorch_widedeep.wdtypes import Tuple, Tensor class BayesianModule(nn.Module): r"""Simply a 'hack' to facilitate the computation of the KL divergence for all Bayesian models """ def init(self): FILL_FUNC_BODYclass BaseBayesianModel(nn.Module): r"""Base mode...
36,657
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/bayesian_models/_weight_sampler.py
52,53
33,58
log_posterior
GaussianPosterior
53,58
53,58
class GaussianPosterior(object): r"""Defines the Gaussian variational posterior as proposed in Weight Uncertainty in Neural Networks """ def __init__(self, param_mu: Tensor, param_rho: Tensor): super().__init__() self.param_mu = param_mu self.param_rho = param_rho self.n...
class GaussianPosterior(object): r"""Defines the Gaussian variational posterior as proposed in Weight Uncertainty in Neural Networks """ def __init__(self, param_mu: Tensor, param_rho: Tensor): super().__init__() self.param_mu = param_mu self.param_rho = param_rho self.n...
return ( -math.log(math.sqrt(2 * math.pi)) - torch.log(self.sigma) - ((input - self.param_mu) ** 2) / (2 * self.sigma**2) ).sum()
return ( -math.log(math.sqrt(2 * math.pi)) - torch.log(self.sigma) - ((input - self.param_mu) ** 2) / (2 * self.sigma**2) ).sum()
18
230
69
299
""" The code here is greatly insipired by the code at the Blitz package: https://github.com/piEsposito/blitz-bayesian-deep-learning """ import math import torch from pytorch_widedeep.wdtypes import Tensor class ScaleMixtureGaussianPrior(object): r"""Defines the Scale Mixture Prior as proposed in Weight Uncert...
""" The code here is greatly insipired by the code at the Blitz package: https://github.com/piEsposito/blitz-bayesian-deep-learning """ import math import torch from pytorch_widedeep.wdtypes import Tensor class ScaleMixtureGaussianPrior(object): r"""Defines the Scale Mixture Prior as proposed in Weight Uncert...
36,658
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/bayesian_models/_weight_sampler.py
27,28
14,33
log_prior
ScaleMixtureGaussianPrior
28,33
28,33
class ScaleMixtureGaussianPrior(object): r"""Defines the Scale Mixture Prior as proposed in Weight Uncertainty in Neural Networks (Eq 7 in the original publication) """ def __init__(self, pi: float, sigma1: float, sigma2: float): super().__init__() self.pi = pi self.sigma1 = sig...
class ScaleMixtureGaussianPrior(object): r"""Defines the Scale Mixture Prior as proposed in Weight Uncertainty in Neural Networks (Eq 7 in the original publication) """ def __init__(self, pi: float, sigma1: float, sigma2: float): super().__init__() self.pi = pi self.sigma1 = sig...
prob1 = torch.exp(self.gaussian1.log_prob(input)) prob2 = torch.exp(self.gaussian2.log_prob(input)) return (torch.log(self.pi * prob1 + (1 - self.pi) * prob2)).sum()
prob1 = torch.exp(self.gaussian1.log_prob(input)) prob2 = torch.exp(self.gaussian2.log_prob(input)) return (torch.log(self.pi * prob1 + (1 - self.pi) * prob2)).sum()
16
184
80
264
""" The code here is greatly insipired by the code at the Blitz package: https://github.com/piEsposito/blitz-bayesian-deep-learning """ import math import torch from pytorch_widedeep.wdtypes import Tensor class ScaleMixtureGaussianPrior(object): r"""Defines the Scale Mixture Prior as proposed in Weight Uncert...
""" The code here is greatly insipired by the code at the Blitz package: https://github.com/piEsposito/blitz-bayesian-deep-learning """ import math import torch from pytorch_widedeep.wdtypes import Tensor class ScaleMixtureGaussianPrior(object): r"""Defines the Scale Mixture Prior as proposed in Weight Uncert...
36,660
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/bayesian_models/bayesian_nn/modules/bayesian_linear.py
141,142
25,179
forward
BayesianLinear
142,164
142,164
class BayesianLinear(BayesianModule): r"""Applies a linear transformation to the incoming data as proposed in Weight Uncertainity on Neural Networks Parameters ---------- in_features: int size of each input sample out_features: int size of each output sample use_bias: bool,...
class BayesianLinear(BayesianModule): r"""Applies a linear transformation to the incoming data as proposed in Weight Uncertainity on Neural Networks Parameters ---------- in_features: int size of each input sample out_features: int size of each output sample use_bias: bool,...
if not self.training: return F.linear(X, self.weight_mu, self.bias_mu) weight = self.weight_sampler.sample() if self.use_bias: bias = self.bias_sampler.sample() bias_log_posterior: Union[Tensor, float] = self.bias_sampler.log_posterior( bias ...
if not self.training: return F.linear(X, self.weight_mu, self.bias_mu) weight = self.weight_sampler.sample() if self.use_bias: bias = self.bias_sampler.sample() bias_log_posterior: Union[Tensor, float] = self.bias_sampler.log_posterior( bias ...
53
1,561
273
1,834
""" The code here is greatly insipired by a couple of sources: the Blitz package: https://github.com/piEsposito/blitz-bayesian-deep-learning and Weight Uncertainty in Neural Networks post by Nitarshan Rajkumar: https://www.nitarshan.com/bayes-by-backprop/ and references therein """ import torch import torch.nn.func...
""" The code here is greatly insipired by a couple of sources: the Blitz package: https://github.com/piEsposito/blitz-bayesian-deep-learning and Weight Uncertainty in Neural Networks post by Nitarshan Rajkumar: https://www.nitarshan.com/bayes-by-backprop/ and references therein """ import torch import torch.nn.func...
36,661
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/bayesian_models/tabular/bayesian_embeddings_layers.py
77,78
19,113
forward
BayesianContEmbeddings
78,108
78,108
class BayesianContEmbeddings(BayesianModule): def __init__( self, n_cont_cols: int, embed_dim: int, prior_sigma_1: float, prior_sigma_2: float, prior_pi: float, posterior_mu_init: float, posterior_rho_init: float, use_bias: bool = False, ...
class BayesianContEmbeddings(BayesianModule): def __init__( self, n_cont_cols: int, embed_dim: int, prior_sigma_1: float, prior_sigma_2: float, prior_pi: float, posterior_mu_init: float, posterior_rho_init: float, use_bias: bool = False, ...
if not self.training: x = self.weight_mu.unsqueeze(0) * X.unsqueeze(2) if self.bias_mu is not None: x + self.bias_mu.unsqueeze(0) return x weight = self.weight_sampler.sample() if self.use_bias: bias = self.bias_sampler.sample() ...
if not self.training: x = self.weight_mu.unsqueeze(0) * X.unsqueeze(2) if self.bias_mu is not None: x + self.bias_mu.unsqueeze(0) return x weight = self.weight_sampler.sample() if self.use_bias: bias = self.bias_sampler.sample() ...
80
730
376
1,106
import numpy as np import torch from torch import nn from pytorch_widedeep.wdtypes import Dict, List, Tuple, Union, Tensor, Optional from pytorch_widedeep.bayesian_models import bayesian_nn as bnn from pytorch_widedeep.models._get_activation_fn import get_activation_fn from pytorch_widedeep.bayesian_models._weight_sam...
import numpy as np import torch from torch import nn from pytorch_widedeep.wdtypes import Dict, List, Tuple, Union, Tensor, Optional from pytorch_widedeep.bayesian_models import bayesian_nn as bnn from pytorch_widedeep.models._get_activation_fn import get_activation_fn from pytorch_widedeep.bayesian_models._weight_sam...
36,662
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/bayesian_models/tabular/bayesian_embeddings_layers.py
154,155
113,165
forward
BayesianDiffSizeCatEmbeddings
155,165
155,165
class BayesianDiffSizeCatEmbeddings(nn.Module): def __init__( self, column_idx: Dict[str, int], embed_input: List[Tuple[str, int, int]], prior_sigma_1: float, prior_sigma_2: float, prior_pi: float, posterior_mu_init: float, posterior_rho_init: float, ...
class BayesianDiffSizeCatEmbeddings(nn.Module): def __init__( self, column_idx: Dict[str, int], embed_input: List[Tuple[str, int, int]], prior_sigma_1: float, prior_sigma_2: float, prior_pi: float, posterior_mu_init: float, posterior_rho_init: float, ...
embed = [ self.embed_layers["emb_layer_" + col](X[:, self.column_idx[col]].long()) for col, _, _ in self.embed_input ] x = torch.cat(embed, 1) if self.activation_fn is not None: x = self.activation_fn(x) return x
embed = [ self.embed_layers["emb_layer_" + col](X[:, self.column_idx[col]].long()) for col, _, _ in self.embed_input ] x = torch.cat(embed, 1) if self.activation_fn is not None: x = self.activation_fn(x) return x
28
436
106
542
import numpy as np import torch from torch import nn from pytorch_widedeep.wdtypes import Dict, List, Tuple, Union, Tensor, Optional from pytorch_widedeep.bayesian_models import bayesian_nn as bnn from pytorch_widedeep.models._get_activation_fn import get_activation_fn from pytorch_widedeep.bayesian_models._weight_sam...
import numpy as np import torch from torch import nn from pytorch_widedeep.wdtypes import Dict, List, Tuple, Union, Tensor, Optional from pytorch_widedeep.bayesian_models import bayesian_nn as bnn from pytorch_widedeep.models._get_activation_fn import get_activation_fn from pytorch_widedeep.bayesian_models._weight_sam...
36,663
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/bayesian_models/tabular/bayesian_linear/bayesian_wide.py
107,108
11,110
forward
BayesianWide
108,110
108,110
class BayesianWide(BaseBayesianModel): r"""Defines a `Wide` model. This is a linear model where the non-linearlities are captured via crossed-columns Parameters ---------- input_dim: int size of the Embedding layer. `input_dim` is the summation of all the individual values for all t...
class BayesianWide(BaseBayesianModel): r"""Defines a `Wide` model. This is a linear model where the non-linearlities are captured via crossed-columns Parameters ---------- input_dim: int size of the Embedding layer. `input_dim` is the summation of all the individual values for all t...
out = self.bayesian_wide_linear(X.long()).sum(dim=1) + self.bias return out
out = self.bayesian_wide_linear(X.long()).sum(dim=1) + self.bias return out
7
1,119
34
1,153
import torch from torch import nn from pytorch_widedeep.wdtypes import Tensor from pytorch_widedeep.bayesian_models import bayesian_nn as bnn from pytorch_widedeep.bayesian_models._base_bayesian_model import ( BaseBayesianModel, ) class BayesianWide(BaseBayesianModel): r"""Defines a `Wide` model. This is a l...
import torch from torch import nn from pytorch_widedeep.wdtypes import Tensor from pytorch_widedeep.bayesian_models import bayesian_nn as bnn from pytorch_widedeep.bayesian_models._base_bayesian_model import ( BaseBayesianModel, ) class BayesianWide(BaseBayesianModel): r"""Defines a `Wide` model. This is a l...
36,664
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/bayesian_models/tabular/bayesian_mlp/_layers.py
49,50
8,51
forward
BayesianMLP
50,51
50,51
class BayesianMLP(nn.Module): def __init__( self, d_hidden: List[int], activation: str, use_bias: bool = True, prior_sigma_1: float = 1.0, prior_sigma_2: float = 0.002, prior_pi: float = 0.8, posterior_mu_init: float = 0.0, posterior_rho_init: ...
class BayesianMLP(nn.Module): def __init__( self, d_hidden: List[int], activation: str, use_bias: bool = True, prior_sigma_1: float = 1.0, prior_sigma_2: float = 0.002, prior_pi: float = 0.8, posterior_mu_init: float = 0.0, posterior_rho_init: ...
return self.bayesian_mlp(X)
return self.bayesian_mlp(X)
2
432
14
446
from torch import nn from pytorch_widedeep.wdtypes import List, Tensor from pytorch_widedeep.bayesian_models import bayesian_nn as bnn from pytorch_widedeep.models._get_activation_fn import get_activation_fn class BayesianMLP(nn.Module): def __init__( self, d_hidden: List[int], activation...
from torch import nn from pytorch_widedeep.wdtypes import List, Tensor from pytorch_widedeep.bayesian_models import bayesian_nn as bnn from pytorch_widedeep.models._get_activation_fn import get_activation_fn class BayesianMLP(nn.Module): def __init__( self, d_hidden: List[int], activation...
36,667
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/callbacks.py
119,120
105,147
set_trainer
Callback
120,122
120,122
class Callback(object): """ Base class used to build new callbacks. """ def __init__(self): pass def set_params(self, params): self.params = params def set_model(self, model: Any): self.model = model def set_trainer(self, trainer: Any): FILL_FUNC_BODY def on_ep...
class Callback(object): """ Base class used to build new callbacks. """ def __init__(self): pass def set_params(self, params): self.params = params def set_model(self, model: Any): self.model = model def set_trainer(self, trainer: Any): FILL_FUNC_BODY def on_ep...
self.trainer = trainer
self.trainer = trainer
3
324
12
336
""" Code here is mostly based on the code from the torchsample and Keras packages CREDIT TO THE TORCHSAMPLE AND KERAS TEAMS """ import os import copy import datetime import warnings import numpy as np import torch from torch.optim.lr_scheduler import ReduceLROnPlateau from pytorch_widedeep.metrics import MultipleMe...
""" Code here is mostly based on the code from the torchsample and Keras packages CREDIT TO THE TORCHSAMPLE AND KERAS TEAMS """ import os import copy import datetime import warnings import numpy as np import torch from torch.optim.lr_scheduler import ReduceLROnPlateau from pytorch_widedeep.metrics import MultipleMe...
36,668
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/callbacks.py
79,80
32,105
on_batch_end
CallbackContainer
80,84
80,84
class CallbackContainer(object): """ Container holding a list of callbacks. """ def __init__(self, callbacks: Optional[List] = None, queue_length: int = 10): instantiated_callbacks = [] if callbacks is not None: for callback in callbacks: if isinstance(callba...
class CallbackContainer(object): """ Container holding a list of callbacks. """ def __init__(self, callbacks: Optional[List] = None, queue_length: int = 10): instantiated_callbacks = [] if callbacks is not None: for callback in callbacks: if isinstance(callba...
logs = logs or {} for callback in self.callbacks: callback.on_batch_end(batch, logs)
logs = logs or {} for callback in self.callbacks: callback.on_batch_end(batch, logs)
11
747
36
783
""" Code here is mostly based on the code from the torchsample and Keras packages CREDIT TO THE TORCHSAMPLE AND KERAS TEAMS """ import os import copy import datetime import warnings import numpy as np import torch from torch.optim.lr_scheduler import ReduceLROnPlateau from pytorch_widedeep.metrics import MultipleMe...
""" Code here is mostly based on the code from the torchsample and Keras packages CREDIT TO THE TORCHSAMPLE AND KERAS TEAMS """ import os import copy import datetime import warnings import numpy as np import torch from torch.optim.lr_scheduler import ReduceLROnPlateau from pytorch_widedeep.metrics import MultipleMe...
36,669
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/callbacks.py
678,679
535,696
get_monitor_value
EarlyStopping
679,689
679,689
class EarlyStopping(Callback): r"""Stop training when a monitored quantity has stopped improving. This class is almost identical to the corresponding keras class. Therefore, **credit** to the Keras Team. Callbacks are passed as input parameters to the `Trainer` class. See `pytorch_widedeep.trainer...
class EarlyStopping(Callback): r"""Stop training when a monitored quantity has stopped improving. This class is almost identical to the corresponding keras class. Therefore, **credit** to the Keras Team. Callbacks are passed as input parameters to the `Trainer` class. See `pytorch_widedeep.trainer...
monitor_value = logs.get(self.monitor) if monitor_value is None: warnings.warn( "Early stopping conditioned on metric `%s` " "which is not available. Available metrics are: %s" % (self.monitor, ",".join(list(logs.keys()))), Runt...
monitor_value = logs.get(self.monitor) if monitor_value is None: warnings.warn( "Early stopping conditioned on metric `%s` " "which is not available. Available metrics are: %s" % (self.monitor, ",".join(list(logs.keys()))), Runt...
30
1,684
105
1,789
""" Code here is mostly based on the code from the torchsample and Keras packages CREDIT TO THE TORCHSAMPLE AND KERAS TEAMS """ import os import copy import datetime import warnings import numpy as np import torch from torch.optim.lr_scheduler import ReduceLROnPlateau from pytorch_widedeep.metrics import MultipleMe...
""" Code here is mostly based on the code from the torchsample and Keras packages CREDIT TO THE TORCHSAMPLE AND KERAS TEAMS """ import os import copy import datetime import warnings import numpy as np import torch from torch.optim.lr_scheduler import ReduceLROnPlateau from pytorch_widedeep.metrics import MultipleMe...
36,670
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/callbacks.py
157,160
147,171
on_epoch_end
History
160,171
160,171
class History(Callback): r"""Saves the metrics in the `history` attribute of the `Trainer`. This callback runs by default within `Trainer`, therefore, should not be passed to the `Trainer`. It is included here just for completion. """ def on_train_begin(self, logs: Optional[Dict] = None): ...
class History(Callback): r"""Saves the metrics in the `history` attribute of the `Trainer`. This callback runs by default within `Trainer`, therefore, should not be passed to the `Trainer`. It is included here just for completion. """ def on_train_begin(self, logs: Optional[Dict] = None): ...
logs = logs or {} for k, v in logs.items(): if isinstance(v, np.ndarray): v = v.tolist() if isinstance(v, list) and len(v) > 1: for i in range(len(v)): self.trainer.history.setdefault(k + "_" + str(i), []).append(v[i]) ...
logs = logs or {} for k, v in logs.items(): if isinstance(v, np.ndarray): v = v.tolist() if isinstance(v, list) and len(v) > 1: for i in range(len(v)): self.trainer.history.setdefault(k + "_" + str(i), []).append(v[i]) ...
36
153
137
290
""" Code here is mostly based on the code from the torchsample and Keras packages CREDIT TO THE TORCHSAMPLE AND KERAS TEAMS """ import os import copy import datetime import warnings import numpy as np import torch from torch.optim.lr_scheduler import ReduceLROnPlateau from pytorch_widedeep.metrics import MultipleMe...
""" Code here is mostly based on the code from the torchsample and Keras packages CREDIT TO THE TORCHSAMPLE AND KERAS TEAMS """ import os import copy import datetime import warnings import numpy as np import torch from torch.optim.lr_scheduler import ReduceLROnPlateau from pytorch_widedeep.metrics import MultipleMe...
36,671
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/callbacks.py
288,291
243,332
on_epoch_end
LRHistory
291,297
291,297
class LRHistory(Callback): r"""Saves the learning rates during training in the `lr_history` attribute of the `Trainer`. Callbacks are passed as input parameters to the `Trainer` class. See `pytorch_widedeep.trainer.Trainer` Parameters ---------- n_epochs: int number of training epo...
class LRHistory(Callback): r"""Saves the learning rates during training in the `lr_history` attribute of the `Trainer`. Callbacks are passed as input parameters to the `Trainer` class. See `pytorch_widedeep.trainer.Trainer` Parameters ---------- n_epochs: int number of training epo...
if epoch != (self.n_epochs - 1) and self.trainer.lr_scheduler is not None: if self._multiple_scheduler(): self._save_group_lr_mulitple_scheduler(step_location="on_epoch_end") elif not self.trainer.cyclic_lr: self._save_group_lr(self.trainer.optimizer)
if epoch != (self.n_epochs - 1) and self.trainer.lr_scheduler is not None: if self._multiple_scheduler(): self._save_group_lr_mulitple_scheduler(step_location="on_epoch_end") elif not self.trainer.cyclic_lr: self._save_group_lr(self.trainer.optimizer)
18
1,179
117
1,296
""" Code here is mostly based on the code from the torchsample and Keras packages CREDIT TO THE TORCHSAMPLE AND KERAS TEAMS """ import os import copy import datetime import warnings import numpy as np import torch from torch.optim.lr_scheduler import ReduceLROnPlateau from pytorch_widedeep.metrics import MultipleMe...
""" Code here is mostly based on the code from the torchsample and Keras packages CREDIT TO THE TORCHSAMPLE AND KERAS TEAMS """ import os import copy import datetime import warnings import numpy as np import torch from torch.optim.lr_scheduler import ReduceLROnPlateau from pytorch_widedeep.metrics import MultipleMe...
36,672
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/callbacks.py
213,214
171,226
_is_cyclic
LRShedulerCallback
214,222
214,222
class LRShedulerCallback(Callback): r"""Callback for the learning rate schedulers to take a step This callback runs by default within `Trainer`, therefore, should not be passed to the `Trainer`. It is included here just for completion. """ def on_batch_end(self, batch: int, logs: Optional[Dict] = ...
class LRShedulerCallback(Callback): r"""Callback for the learning rate schedulers to take a step This callback runs by default within `Trainer`, therefore, should not be passed to the `Trainer`. It is included here just for completion. """ def on_batch_end(self, batch: int, logs: Optional[Dict] = ...
return ( self._has_scheduler(model_name) and "cycl" in self.trainer.lr_scheduler._schedulers[ model_name ].__class__.__name__.lower() )
return ( self._has_scheduler(model_name) and "cycl" in self.trainer.lr_scheduler._schedulers[ model_name ].__class__.__name__.lower() )
10
557
72
629
""" Code here is mostly based on the code from the torchsample and Keras packages CREDIT TO THE TORCHSAMPLE AND KERAS TEAMS """ import os import copy import datetime import warnings import numpy as np import torch from torch.optim.lr_scheduler import ReduceLROnPlateau from pytorch_widedeep.metrics import MultipleMe...
""" Code here is mostly based on the code from the torchsample and Keras packages CREDIT TO THE TORCHSAMPLE AND KERAS TEAMS """ import os import copy import datetime import warnings import numpy as np import torch from torch.optim.lr_scheduler import ReduceLROnPlateau from pytorch_widedeep.metrics import MultipleMe...
36,673
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/callbacks.py
236,237
226,243
on_epoch_begin
MetricCallback
237,239
237,239
class MetricCallback(Callback): r"""Callback that resets the metrics (if any metric is used) This callback runs by default within `Trainer`, therefore, should not be passed to the `Trainer`. It is included here just for completion. """ def __init__(self, container: MultipleMetrics): self.c...
class MetricCallback(Callback): r"""Callback that resets the metrics (if any metric is used) This callback runs by default within `Trainer`, therefore, should not be passed to the `Trainer`. It is included here just for completion. """ def __init__(self, container: MultipleMetrics): self.c...
self.container.reset()
self.container.reset()
1
157
11
168
""" Code here is mostly based on the code from the torchsample and Keras packages CREDIT TO THE TORCHSAMPLE AND KERAS TEAMS """ import os import copy import datetime import warnings import numpy as np import torch from torch.optim.lr_scheduler import ReduceLROnPlateau from pytorch_widedeep.metrics import MultipleMe...
""" Code here is mostly based on the code from the torchsample and Keras packages CREDIT TO THE TORCHSAMPLE AND KERAS TEAMS """ import os import copy import datetime import warnings import numpy as np import torch from torch.optim.lr_scheduler import ReduceLROnPlateau from pytorch_widedeep.metrics import MultipleMe...
36,675
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/dataloaders.py
9,10
1,103
get_class_weights
34,40
10,40
from typing import Tuple import numpy as np from torch.utils.data import DataLoader, WeightedRandomSampler from pytorch_widedeep.training._wd_dataset import WideDeepDataset def get_class_weights(dataset: WideDeepDataset) -> Tuple[np.ndarray, int, int]: FILL_FUNC_BODYclass DataLoaderDefault(DataLoader): def __in...
from typing import Tuple import numpy as np from torch.utils.data import DataLoader, WeightedRandomSampler from pytorch_widedeep.training._wd_dataset import WideDeepDataset def get_class_weights(dataset: WideDeepDataset) -> Tuple[np.ndarray, int, int]: """Helper function to get weights of classes in the imbalan...
weights = 1 / np.unique(dataset.Y, return_counts=True)[1] minor_class_count = min(np.unique(dataset.Y, return_counts=True)[1]) num_classes = len(np.unique(dataset.Y)) return weights, minor_class_count, num_classes
"""Helper function to get weights of classes in the imbalanced dataset. Parameters ---------- dataset: `WideDeepDataset` dataset containing target classes in dataset.Y Returns ---------- weights: array numpy array with weights minor_class_count: int count of sam...
17
1,064
88
1,152
from typing import Tuple import numpy as np from torch.utils.data import DataLoader, WeightedRandomSampler from pytorch_widedeep.training._wd_dataset import WideDeepDataset def get_class_weights(dataset: WideDeepDataset) -> Tuple[np.ndarray, int, int]: FILL_FUNC_BODYclass DataLoaderDefault(DataLoader): def __in...
from typing import Tuple import numpy as np from torch.utils.data import DataLoader, WeightedRandomSampler from pytorch_widedeep.training._wd_dataset import WideDeepDataset def get_class_weights(dataset: WideDeepDataset) -> Tuple[np.ndarray, int, int]: """Helper function to get weights of classes in the imbalan...
36,677
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/initializers.py
28,29
15,39
apply
MultipleInitializer
29,39
29,39
class MultipleInitializer(object): def __init__( self, initializers: Dict[str, Union[Initializer, object]], verbose=True ): self.verbose = verbose instantiated_initializers = {} for model_name, initializer in initializers.items(): if isinstance(initializer, type): ...
class MultipleInitializer(object): def __init__( self, initializers: Dict[str, Union[Initializer, object]], verbose=True ): self.verbose = verbose instantiated_initializers = {} for model_name, initializer in initializers.items(): if isinstance(initializer, type): ...
for name, child in submodel.named_children(): try: self._initializers[name](child) except KeyError: if self.verbose: warnings.warn( "No initializer found for {}".format(name), UserWarning )
for name, child in submodel.named_children(): try: self._initializers[name](child) except KeyError: if self.verbose: warnings.warn( "No initializer found for {}".format(name), UserWarning )
19
160
80
240
import re import warnings from typing import Dict, Union from torch import nn warnings.filterwarnings("default") class Initializer(object): def __call__(self, submodel: nn.Module): raise NotImplementedError("Initializer must implement this method") class MultipleInitializer(object): def __init__( ...
import re import warnings from typing import Dict, Union from torch import nn warnings.filterwarnings("default") class Initializer(object): def __call__(self, submodel: nn.Module): raise NotImplementedError("Initializer must implement this method") class MultipleInitializer(object): def __init__( ...
36,678
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/load_from_folder/tabular/tabular_from_folder.py
105,108
19,202
get_item
TabFromFolder
108,141
108,141
class TabFromFolder: """ This class is used to load tabular data from disk. The current constrains are: 1. The only file format supported right now is csv 2. The csv file must contain headers For examples, please, see the examples folder in the repo. Parameters ---------- fname: str ...
class TabFromFolder: """ This class is used to load tabular data from disk. The current constrains are: 1. The only file format supported right now is csv 2. The csv file must contain headers For examples, please, see the examples folder in the repo. Parameters ---------- fname: str ...
path = os.path.join(self.directory, self.fname) try: if not hasattr(self, "colnames"): self.colnames = pd.read_csv(path, nrows=0).columns.tolist() # TO DO: we need to look into this as the treatment is different # whether the csv contains headers or ...
path = os.path.join(self.directory, self.fname) try: if not hasattr(self, "colnames"): self.colnames = pd.read_csv(path, nrows=0).columns.tolist() # TO DO: we need to look into this as the treatment is different # whether the csv contains headers or ...
119
1,543
395
1,938
import os from typing import Any, List, Tuple, Union, Optional import numpy as np import pandas as pd from pytorch_widedeep.preprocessing import ( TabPreprocessor, WidePreprocessor, ChunkTabPreprocessor, ChunkWidePreprocessor, ) TabularPreprocessor = Union[ TabPreprocessor, WidePreprocessor, Chun...
import os from typing import Any, List, Tuple, Union, Optional import numpy as np import pandas as pd from pytorch_widedeep.preprocessing import ( TabPreprocessor, WidePreprocessor, ChunkTabPreprocessor, ChunkWidePreprocessor, ) TabularPreprocessor = Union[ TabPreprocessor, WidePreprocessor, Chun...
36,679
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/load_from_folder/text/text_from_folder.py
43,44
16,61
get_item
TextFromFolder
44,59
44,59
class TextFromFolder: """ This class is used to load the text dataset (i.e. the text files) from a folder, or to retrieve the text given a texts column specified within the preprocessor object. For examples, please, see the examples folder in the repo. Parameters ---------- preprocesso...
class TextFromFolder: """ This class is used to load the text dataset (i.e. the text files) from a folder, or to retrieve the text given a texts column specified within the preprocessor object. For examples, please, see the examples folder in the repo. Parameters ---------- preprocesso...
if ( isinstance(self.preprocessor, ChunkTextPreprocessor) and self.preprocessor.root_dir is not None ): path = os.path.join(self.preprocessor.root_dir, text) with open(path, "r") as f: sample = f.read().replace("\n", "") else: ...
if ( isinstance(self.preprocessor, ChunkTextPreprocessor) and self.preprocessor.root_dir is not None ): path = os.path.join(self.preprocessor.root_dir, text) with open(path, "r") as f: sample = f.read().replace("\n", "") else: ...
32
284
137
421
import os from typing import Union import numpy as np from pytorch_widedeep.preprocessing.hf_preprocessor import ( HFPreprocessor, ChunkHFPreprocessor, ) from pytorch_widedeep.preprocessing.text_preprocessor import ( TextPreprocessor, ChunkTextPreprocessor, ) class TextFromFolder: """ This c...
import os from typing import Union import numpy as np from pytorch_widedeep.preprocessing.hf_preprocessor import ( HFPreprocessor, ChunkHFPreprocessor, ) from pytorch_widedeep.preprocessing.text_preprocessor import ( TextPreprocessor, ChunkTextPreprocessor, ) class TextFromFolder: """ This c...
36,680
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/metrics.py
83,84
47,106
reset
Accuracy
87,90
84,90
class Accuracy(Metric): r"""Class to calculate the accuracy for both binary and categorical problems Parameters ---------- top_k: int, default = 1 Accuracy will be computed using the top k most likely classes in multiclass problems Examples -------- >>> import torch >>>...
class Accuracy(Metric): r"""Class to calculate the accuracy for both binary and categorical problems Parameters ---------- top_k: int, default = 1 Accuracy will be computed using the top k most likely classes in multiclass problems Examples -------- >>> import torch >>>...
self.correct_count = 0 self.total_count = 0
""" resets counters to 0 """ self.correct_count = 0 self.total_count = 0
6
648
22
670
import numpy as np import torch from torchmetrics import Metric as TorchMetric from pytorch_widedeep.wdtypes import Dict, List, Union, Tensor class Metric(object): def __init__(self): self._name = "" def reset(self): raise NotImplementedError("Custom Metrics must implement this function") ...
import numpy as np import torch from torchmetrics import Metric as TorchMetric from pytorch_widedeep.wdtypes import Dict, List, Union, Tensor class Metric(object): def __init__(self): self._name = "" def reset(self): raise NotImplementedError("Custom Metrics must implement this function") ...
36,681
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/metrics.py
337,338
302,347
reset
F1Score
341,343
338,343
class F1Score(Metric): r"""Class to calculate the f1 score for both binary and categorical problems Parameters ---------- average: bool, default = True This applies only to multiclass problems. if ``True`` calculate f1 for each label, and find their unweighted mean. Examples --...
class F1Score(Metric): r"""Class to calculate the f1 score for both binary and categorical problems Parameters ---------- average: bool, default = True This applies only to multiclass problems. if ``True`` calculate f1 for each label, and find their unweighted mean. Examples --...
self.f1.reset()
""" resets counters to 0 """ self.f1.reset()
1
495
12
507
import numpy as np import torch from torchmetrics import Metric as TorchMetric from pytorch_widedeep.wdtypes import Dict, List, Union, Tensor class Metric(object): def __init__(self): self._name = "" def reset(self): raise NotImplementedError("Custom Metrics must implement this function") ...
import numpy as np import torch from torchmetrics import Metric as TorchMetric from pytorch_widedeep.wdtypes import Dict, List, Union, Tensor class Metric(object): def __init__(self): self._name = "" def reset(self): raise NotImplementedError("Custom Metrics must implement this function") ...
36,682
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/metrics.py
282,283
238,302
reset
FBetaScore
286,289
283,289
class FBetaScore(Metric): r"""Class to calculate the fbeta score for both binary and categorical problems $$ F_{\beta} = ((1 + {\beta}^2) * \frac{(precision * recall)}{({\beta}^2 * precision + recall)} $$ Parameters ---------- beta: int Coefficient to control the balance between pr...
class FBetaScore(Metric): r"""Class to calculate the fbeta score for both binary and categorical problems $$ F_{\beta} = ((1 + {\beta}^2) * \frac{(precision * recall)}{({\beta}^2 * precision + recall)} $$ Parameters ---------- beta: int Coefficient to control the balance between pr...
self.precision.reset() self.recall.reset()
""" resets precision and recall """ self.precision.reset() self.recall.reset()
2
702
22
724
import numpy as np import torch from torchmetrics import Metric as TorchMetric from pytorch_widedeep.wdtypes import Dict, List, Union, Tensor class Metric(object): def __init__(self): self._name = "" def reset(self): raise NotImplementedError("Custom Metrics must implement this function") ...
import numpy as np import torch from torchmetrics import Metric as TorchMetric from pytorch_widedeep.wdtypes import Dict, List, Union, Tensor class Metric(object): def __init__(self): self._name = "" def reset(self): raise NotImplementedError("Custom Metrics must implement this function") ...
36,683
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/metrics.py
12,13
8,19
reset
Metric
13,15
13,15
class Metric(object): def __init__(self): self._name = "" def reset(self): FILL_FUNC_BODY def __call__(self, y_pred: Tensor, y_true: Tensor): raise NotImplementedError("Custom Metrics must implement this function")
class Metric(object): def __init__(self): self._name = "" def reset(self): FILL_FUNC_BODY def __call__(self, y_pred: Tensor, y_true: Tensor): raise NotImplementedError("Custom Metrics must implement this function")
raise NotImplementedError("Custom Metrics must implement this function")
raise NotImplementedError("Custom Metrics must implement this function")
7
81
20
101
import numpy as np import torch from torchmetrics import Metric as TorchMetric from pytorch_widedeep.wdtypes import Dict, List, Union, Tensor class Metric(object): def __init__(self): self._name = "" def reset(self): FILL_FUNC_BODY def __call__(self, y_pred: Tensor, y_true: Tensor): raise...
import numpy as np import torch from torchmetrics import Metric as TorchMetric from pytorch_widedeep.wdtypes import Dict, List, Union, Tensor class Metric(object): def __init__(self): self._name = "" def reset(self): FILL_FUNC_BODY def __call__(self, y_pred: Tensor, y_true: Tensor): raise...
36,684
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/metrics.py
30,31
19,47
reset
MultipleMetrics
31,34
31,34
class MultipleMetrics(object): def __init__(self, metrics: List[Union[Metric, object]], prefix: str = ""): instantiated_metrics = [] for metric in metrics: if isinstance(metric, type): instantiated_metrics.append(metric()) else: instantiated_me...
class MultipleMetrics(object): def __init__(self, metrics: List[Union[Metric, object]], prefix: str = ""): instantiated_metrics = [] for metric in metrics: if isinstance(metric, type): instantiated_metrics.append(metric()) else: instantiated_me...
for metric in self._metrics: metric.reset()
for metric in self._metrics: metric.reset()
5
283
20
303
import numpy as np import torch from torchmetrics import Metric as TorchMetric from pytorch_widedeep.wdtypes import Dict, List, Union, Tensor class Metric(object): def __init__(self): self._name = "" def reset(self): raise NotImplementedError("Custom Metrics must implement this function") ...
import numpy as np import torch from torchmetrics import Metric as TorchMetric from pytorch_widedeep.wdtypes import Dict, List, Union, Tensor class Metric(object): def __init__(self): self._name = "" def reset(self): raise NotImplementedError("Custom Metrics must implement this function") ...
36,685
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/metrics.py
143,144
106,172
reset
Precision
147,150
144,150
class Precision(Metric): r"""Class to calculate the precision for both binary and categorical problems Parameters ---------- average: bool, default = True This applies only to multiclass problems. if ``True`` calculate precision for each label, and finds their unweighted mean. Exam...
class Precision(Metric): r"""Class to calculate the precision for both binary and categorical problems Parameters ---------- average: bool, default = True This applies only to multiclass problems. if ``True`` calculate precision for each label, and finds their unweighted mean. Exam...
self.true_positives = 0 self.all_positives = 0
""" resets counters to 0 """ self.true_positives = 0 self.all_positives = 0
6
743
24
767
import numpy as np import torch from torchmetrics import Metric as TorchMetric from pytorch_widedeep.wdtypes import Dict, List, Union, Tensor class Metric(object): def __init__(self): self._name = "" def reset(self): raise NotImplementedError("Custom Metrics must implement this function") ...
import numpy as np import torch from torchmetrics import Metric as TorchMetric from pytorch_widedeep.wdtypes import Dict, List, Union, Tensor class Metric(object): def __init__(self): self._name = "" def reset(self): raise NotImplementedError("Custom Metrics must implement this function") ...
36,686
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/metrics.py
380,381
347,397
reset
R2Score
384,389
381,389
class R2Score(Metric): r""" Calculates R-Squared, the [coefficient of determination](https://en.wikipedia.org/wiki/Coefficient_of_determination>): $$ R^2 = 1 - \frac{\sum_{j=1}^n(y_j - \hat{y_j})^2}{\sum_{j=1}^n(y_j - \bar{y})^2} $$ where $\hat{y_j}$ is the ground truth, $y_j$ is the predi...
class R2Score(Metric): r""" Calculates R-Squared, the [coefficient of determination](https://en.wikipedia.org/wiki/Coefficient_of_determination>): $$ R^2 = 1 - \frac{\sum_{j=1}^n(y_j - \hat{y_j})^2}{\sum_{j=1}^n(y_j - \bar{y})^2} $$ where $\hat{y_j}$ is the ground truth, $y_j$ is the predi...
self.numerator = 0 self.denominator = 0 self.num_examples = 0 self.y_true_sum = 0
""" resets counters to 0 """ self.numerator = 0 self.denominator = 0 self.num_examples = 0 self.y_true_sum = 0
12
557
43
600
import numpy as np import torch from torchmetrics import Metric as TorchMetric from pytorch_widedeep.wdtypes import Dict, List, Union, Tensor class Metric(object): def __init__(self): self._name = "" def reset(self): raise NotImplementedError("Custom Metrics must implement this function") ...
import numpy as np import torch from torchmetrics import Metric as TorchMetric from pytorch_widedeep.wdtypes import Dict, List, Union, Tensor class Metric(object): def __init__(self): self._name = "" def reset(self): raise NotImplementedError("Custom Metrics must implement this function") ...
36,687
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/metrics.py
209,210
172,238
reset
Recall
213,216
210,216
class Recall(Metric): r"""Class to calculate the recall for both binary and categorical problems Parameters ---------- average: bool, default = True This applies only to multiclass problems. if ``True`` calculate recall for each label, and finds their unweighted mean. Examples ...
class Recall(Metric): r"""Class to calculate the recall for both binary and categorical problems Parameters ---------- average: bool, default = True This applies only to multiclass problems. if ``True`` calculate recall for each label, and finds their unweighted mean. Examples ...
self.true_positives = 0 self.actual_positives = 0
""" resets counters to 0 """ self.true_positives = 0 self.actual_positives = 0
6
742
24
766
import numpy as np import torch from torchmetrics import Metric as TorchMetric from pytorch_widedeep.wdtypes import Dict, List, Union, Tensor class Metric(object): def __init__(self): self._name = "" def reset(self): raise NotImplementedError("Custom Metrics must implement this function") ...
import numpy as np import torch from torchmetrics import Metric as TorchMetric from pytorch_widedeep.wdtypes import Dict, List, Union, Tensor class Metric(object): def __init__(self): self._name = "" def reset(self): raise NotImplementedError("Custom Metrics must implement this function") ...
36,688
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/_base_wd_model_component.py
5,7
4,13
output_dim
BaseWDModelComponent
7,13
7,13
class BaseWDModelComponent(nn.Module): @property def output_dim(self) -> int: FILL_FUNC_BODY
class BaseWDModelComponent(nn.Module): @property def output_dim(self) -> int: FILL_FUNC_BODY
return NotImplementedError( # type: ignore[return-value] "All models passed to the WideDeep class must contain an 'output_dim' " "property or attribute. This is the dimension of the output tensor coming " "from the backbone model that will be connected to the final predictio...
return NotImplementedError( # type: ignore[return-value] "All models passed to the WideDeep class must contain an 'output_dim' " "property or attribute. This is the dimension of the output tensor coming " "from the backbone model that will be connected to the final predictio...
49
38
93
131
from torch import nn class BaseWDModelComponent(nn.Module): @property def output_dim(self) -> int: FILL_FUNC_BODY
from torch import nn class BaseWDModelComponent(nn.Module): @property def output_dim(self) -> int: FILL_FUNC_BODY
36,689
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/_get_activation_fn.py
26,27
1,49
get_activation_fn
27,49
27,49
import torch.nn.functional as F from torch import nn allowed_activations = [ "relu", "leaky_relu", "tanh", "gelu", "geglu", "reglu", ] class GEGLU(nn.Module): def forward(self, x): x, gates = x.chunk(2, dim=-1) return x * F.gelu(gates) class REGLU(nn.Module): def for...
import torch.nn.functional as F from torch import nn allowed_activations = [ "relu", "leaky_relu", "tanh", "gelu", "geglu", "reglu", ] class GEGLU(nn.Module): def forward(self, x): x, gates = x.chunk(2, dim=-1) return x * F.gelu(gates) class REGLU(nn.Module): def for...
if activation == "relu": return nn.ReLU(inplace=True) elif activation == "leaky_relu": return nn.LeakyReLU(inplace=True) elif activation == "tanh": return nn.Tanh() elif activation == "gelu": return nn.GELU() elif activation == "geglu": return GEGLU() elif...
if activation == "relu": return nn.ReLU(inplace=True) elif activation == "leaky_relu": return nn.LeakyReLU(inplace=True) elif activation == "tanh": return nn.Tanh() elif activation == "gelu": return nn.GELU() elif activation == "geglu": return GEGLU() elif...
72
199
239
438
import torch.nn.functional as F from torch import nn allowed_activations = [ "relu", "leaky_relu", "tanh", "gelu", "geglu", "reglu", ] class GEGLU(nn.Module): def forward(self, x): x, gates = x.chunk(2, dim=-1) return x * F.gelu(gates) class REGLU(nn.Module): def for...
import torch.nn.functional as F from torch import nn allowed_activations = [ "relu", "leaky_relu", "tanh", "gelu", "geglu", "reglu", ] class GEGLU(nn.Module): def forward(self, x): x, gates = x.chunk(2, dim=-1) return x * F.gelu(gates) class REGLU(nn.Module): def for...
36,690
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/_get_activation_fn.py
15,16
14,20
forward
GEGLU
16,20
16,20
class GEGLU(nn.Module): def forward(self, x): FILL_FUNC_BODY
class GEGLU(nn.Module): def forward(self, x): FILL_FUNC_BODY
x, gates = x.chunk(2, dim=-1) return x * F.gelu(gates)
x, gates = x.chunk(2, dim=-1) return x * F.gelu(gates)
9
29
38
67
import torch.nn.functional as F from torch import nn allowed_activations = [ "relu", "leaky_relu", "tanh", "gelu", "geglu", "reglu", ] class GEGLU(nn.Module): def forward(self, x): FILL_FUNC_BODYclass REGLU(nn.Module): def forward(self, x): x, gates = x.chunk(2, dim=-1) ...
import torch.nn.functional as F from torch import nn allowed_activations = [ "relu", "leaky_relu", "tanh", "gelu", "geglu", "reglu", ] class GEGLU(nn.Module): def forward(self, x): FILL_FUNC_BODYclass REGLU(nn.Module): def forward(self, x): x, gates = x.chunk(2, dim=-1) ...
36,691
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/_get_activation_fn.py
21,22
20,26
forward
REGLU
22,26
22,26
class REGLU(nn.Module): def forward(self, x): FILL_FUNC_BODY
class REGLU(nn.Module): def forward(self, x): FILL_FUNC_BODY
x, gates = x.chunk(2, dim=-1) return x * F.gelu(gates)
x, gates = x.chunk(2, dim=-1) return x * F.gelu(gates)
9
29
38
67
import torch.nn.functional as F from torch import nn allowed_activations = [ "relu", "leaky_relu", "tanh", "gelu", "geglu", "reglu", ] class GEGLU(nn.Module): def forward(self, x): x, gates = x.chunk(2, dim=-1) return x * F.gelu(gates) class REGLU(nn.Module): def for...
import torch.nn.functional as F from torch import nn allowed_activations = [ "relu", "leaky_relu", "tanh", "gelu", "geglu", "reglu", ] class GEGLU(nn.Module): def forward(self, x): x, gates = x.chunk(2, dim=-1) return x * F.gelu(gates) class REGLU(nn.Module): def for...
36,693
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/image/_layers.py
4,12
1,29
conv_layer
12,29
12,29
from torch import nn def conv_layer( ni: int, nf: int, kernel_size: int = 3, stride: int = 1, maxpool: bool = True, adaptiveavgpool: bool = False, ): FILL_FUNC_BODY
from torch import nn def conv_layer( ni: int, nf: int, kernel_size: int = 3, stride: int = 1, maxpool: bool = True, adaptiveavgpool: bool = False, ): FILL_FUNC_BODY
layer = nn.Sequential( nn.Conv2d( ni, nf, kernel_size=kernel_size, stride=stride, bias=False, padding=kernel_size // 2, ), nn.BatchNorm2d(nf, momentum=0.01), nn.LeakyReLU(negative_slope=0.1, inplace=True), ) ...
layer = nn.Sequential( nn.Conv2d( ni, nf, kernel_size=kernel_size, stride=stride, bias=False, padding=kernel_size // 2, ), nn.BatchNorm2d(nf, momentum=0.01), nn.LeakyReLU(negative_slope=0.1, inplace=True), ) ...
30
80
212
292
from torch import nn def conv_layer( ni: int, nf: int, kernel_size: int = 3, stride: int = 1, maxpool: bool = True, adaptiveavgpool: bool = False, ): FILL_FUNC_BODY
from torch import nn def conv_layer( ni: int, nf: int, kernel_size: int = 3, stride: int = 1, maxpool: bool = True, adaptiveavgpool: bool = False, ): FILL_FUNC_BODY
36,695
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/_base_tabular_model.py
303,304
169,327
_get_embeddings
BaseTabularModelWithAttention
304,319
304,319
class BaseTabularModelWithAttention(BaseWDModelComponent): @alias("shared_embed", ["cat_embed_shared"]) def __init__( self, column_idx: Dict[str, int], input_dim: int, *, cat_embed_input: Optional[List[Tuple[str, int]]], cat_embed_dropout: Optional[float], ...
class BaseTabularModelWithAttention(BaseWDModelComponent): @alias("shared_embed", ["cat_embed_shared"]) def __init__( self, column_idx: Dict[str, int], input_dim: int, *, cat_embed_input: Optional[List[Tuple[str, int]]], cat_embed_dropout: Optional[float], ...
tensors_to_concat: List[Tensor] = [] if self.cat_embed_input is not None: x_cat = self.cat_embed(X) tensors_to_concat.append(x_cat) if self.continuous_cols is not None: x_cont = self.cont_norm((X[:, self.cont_idx].float())) if self.embed_continuou...
tensors_to_concat: List[Tensor] = [] if self.cat_embed_input is not None: x_cat = self.cat_embed(X) tensors_to_concat.append(x_cat) if self.continuous_cols is not None: x_cont = self.cont_norm((X[:, self.cont_idx].float())) if self.embed_continuou...
34
1,707
180
1,887
import warnings import numpy as np import torch import einops from torch import nn from pytorch_widedeep.wdtypes import ( Dict, List, Tuple, Union, Tensor, Literal, Optional, ) from pytorch_widedeep.utils.general_utils import alias from pytorch_widedeep.models._base_wd_model_component impo...
import warnings import numpy as np import torch import einops from torch import nn from pytorch_widedeep.wdtypes import ( Dict, List, Tuple, Union, Tensor, Literal, Optional, ) from pytorch_widedeep.utils.general_utils import alias from pytorch_widedeep.models._base_wd_model_component impo...
36,696
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/_base_tabular_model.py
151,152
33,169
_get_embeddings
BaseTabularModelWithoutAttention
152,169
152,169
class BaseTabularModelWithoutAttention(BaseWDModelComponent): def __init__( self, column_idx: Dict[str, int], *, cat_embed_input: Optional[List[Tuple[str, int, int]]], cat_embed_dropout: Optional[float], use_cat_bias: Optional[bool], cat_embed_activation: Opti...
class BaseTabularModelWithoutAttention(BaseWDModelComponent): def __init__( self, column_idx: Dict[str, int], *, cat_embed_input: Optional[List[Tuple[str, int, int]]], cat_embed_dropout: Optional[float], use_cat_bias: Optional[bool], cat_embed_activation: Opti...
tensors_to_concat: List[Tensor] = [] if self.cat_embed_input is not None: x_cat = self.cat_embed(X) tensors_to_concat.append(x_cat) if self.continuous_cols is not None: x_cont = self.cont_norm((X[:, self.cont_idx].float())) if self.embed_continuou...
tensors_to_concat: List[Tensor] = [] if self.cat_embed_input is not None: x_cat = self.cat_embed(X) tensors_to_concat.append(x_cat) if self.continuous_cols is not None: x_cont = self.cont_norm((X[:, self.cont_idx].float())) if self.embed_continuou...
44
1,487
213
1,700
import warnings import numpy as np import torch import einops from torch import nn from pytorch_widedeep.wdtypes import ( Dict, List, Tuple, Union, Tensor, Literal, Optional, ) from pytorch_widedeep.utils.general_utils import alias from pytorch_widedeep.models._base_wd_model_component impo...
import warnings import numpy as np import torch import einops from torch import nn from pytorch_widedeep.wdtypes import ( Dict, List, Tuple, Union, Tensor, Literal, Optional, ) from pytorch_widedeep.utils.general_utils import alias from pytorch_widedeep.models._base_wd_model_component impo...
36,697
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/embeddings_layers.py
120,121
90,145
reset_parameters
ContEmbeddings
121,127
121,127
class ContEmbeddings(nn.Module): def __init__( self, n_cont_cols: int, embed_dim: int, embed_dropout: float, full_embed_dropout: bool, activation_fn: Optional[str] = None, ): super(ContEmbeddings, self).__init__() self.n_cont_cols = n_cont_cols ...
class ContEmbeddings(nn.Module): def __init__( self, n_cont_cols: int, embed_dim: int, embed_dropout: float, full_embed_dropout: bool, activation_fn: Optional[str] = None, ): super(ContEmbeddings, self).__init__() self.n_cont_cols = n_cont_cols ...
# see here https://pytorch.org/docs/stable/_modules/torch/nn/modules/linear.html#Linear nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5)) fan_in, _ = nn.init._calculate_fan_in_and_fan_out(self.weight) bound = 1 / math.sqrt(fan_in) if fan_in > 0 else 0 nn.init.uniform_(self.bi...
# see here https://pytorch.org/docs/stable/_modules/torch/nn/modules/linear.html#Linear nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5)) fan_in, _ = nn.init._calculate_fan_in_and_fan_out(self.weight) bound = 1 / math.sqrt(fan_in) if fan_in > 0 else 0 nn.init.uniform_(self.bi...
24
600
135
735
""" SharedEmbeddings is inspired by the TabTransformer available in AutoGluon: https://github.com/awslabs/autogluon/tree/master/tabular/src/autogluon/tabular/models/tab_transformer PiecewiseContEmbeddings and PeriodicContEmbeddings are presented in the paper: 'On Embeddings for Numerical Features in Tabular Deep Learn...
""" SharedEmbeddings is inspired by the TabTransformer available in AutoGluon: https://github.com/awslabs/autogluon/tree/master/tabular/src/autogluon/tabular/models/tab_transformer PiecewiseContEmbeddings and PeriodicContEmbeddings are presented in the paper: 'On Embeddings for Numerical Features in Tabular Deep Learn...
36,698
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/embeddings_layers.py
376,377
328,395
forward
DiffSizeCatEmbeddings
377,395
377,395
class DiffSizeCatEmbeddings(nn.Module): def __init__( self, column_idx: Dict[str, int], embed_input: List[Tuple[str, int, int]], embed_dropout: float, use_bias: bool, activation_fn: Optional[str] = None, ): super(DiffSizeCatEmbeddings, self).__init__() ...
class DiffSizeCatEmbeddings(nn.Module): def __init__( self, column_idx: Dict[str, int], embed_input: List[Tuple[str, int, int]], embed_dropout: float, use_bias: bool, activation_fn: Optional[str] = None, ): super(DiffSizeCatEmbeddings, self).__init__() ...
embed = [ self.embed_layers["emb_layer_" + self.embed_layers_names[col]]( X[:, self.column_idx[col]].long() ) + ( self.biases["bias_" + col].unsqueeze(0) if self.use_bias else torch.zeros(1, dim, device=X.device)...
embed = [ self.embed_layers["emb_layer_" + self.embed_layers_names[col]]( X[:, self.column_idx[col]].long() ) + ( self.biases["bias_" + col].unsqueeze(0) if self.use_bias else torch.zeros(1, dim, device=X.device)...
45
544
197
741
""" SharedEmbeddings is inspired by the TabTransformer available in AutoGluon: https://github.com/awslabs/autogluon/tree/master/tabular/src/autogluon/tabular/models/tab_transformer PiecewiseContEmbeddings and PeriodicContEmbeddings are presented in the paper: 'On Embeddings for Numerical Features in Tabular Deep Learn...
""" SharedEmbeddings is inspired by the TabTransformer available in AutoGluon: https://github.com/awslabs/autogluon/tree/master/tabular/src/autogluon/tabular/models/tab_transformer PiecewiseContEmbeddings and PeriodicContEmbeddings are presented in the paper: 'On Embeddings for Numerical Features in Tabular Deep Learn...
36,699
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/embeddings_layers.py
73,74
65,86
forward
FullEmbeddingDropout
74,82
74,82
class FullEmbeddingDropout(nn.Module): def __init__(self, p: float): super(FullEmbeddingDropout, self).__init__() if p < 0 or p > 1: raise ValueError(f"p probability has to be between 0 and 1, but got {p}") self.p = p def forward(self, X: Tensor) -> Tensor: FILL_FUNC_BODY ...
class FullEmbeddingDropout(nn.Module): def __init__(self, p: float): super(FullEmbeddingDropout, self).__init__() if p < 0 or p > 1: raise ValueError(f"p probability has to be between 0 and 1, but got {p}") self.p = p def forward(self, X: Tensor) -> Tensor: FILL_FUNC_BODY ...
if self.training: mask = X.new().resize_((X.size(1), 1)).bernoulli_(1 - self.p).expand_as( X ) / (1 - self.p) return mask * X else: return X
if self.training: mask = X.new().resize_((X.size(1), 1)).bernoulli_(1 - self.p).expand_as( X ) / (1 - self.p) return mask * X else: return X
21
143
79
222
""" SharedEmbeddings is inspired by the TabTransformer available in AutoGluon: https://github.com/awslabs/autogluon/tree/master/tabular/src/autogluon/tabular/models/tab_transformer PiecewiseContEmbeddings and PeriodicContEmbeddings are presented in the paper: 'On Embeddings for Numerical Features in Tabular Deep Learn...
""" SharedEmbeddings is inspired by the TabTransformer available in AutoGluon: https://github.com/awslabs/autogluon/tree/master/tabular/src/autogluon/tabular/models/tab_transformer PiecewiseContEmbeddings and PeriodicContEmbeddings are presented in the paper: 'On Embeddings for Numerical Features in Tabular Deep Learn...
36,700
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/embeddings_layers.py
51,52
33,65
forward
NLinear
52,60
52,60
class NLinear(nn.Module): def __init__(self, n_feat: int, inp_units: int, out_units: int) -> None: super().__init__() self.n_feat = n_feat self.inp_units = inp_units self.out_units = out_units self.weights = nn.Parameter(torch.Tensor(n_feat, inp_units, out_units)) s...
class NLinear(nn.Module): def __init__(self, n_feat: int, inp_units: int, out_units: int) -> None: super().__init__() self.n_feat = n_feat self.inp_units = inp_units self.out_units = out_units self.weights = nn.Parameter(torch.Tensor(n_feat, inp_units, out_units)) s...
assert X.ndim == 3 assert X.shape[1] == self.n_feat assert X.shape[2] == self.inp_units x = (X[..., None, :] @ self.weights).squeeze(-2) x = x + self.bias return x
assert X.ndim == 3 assert X.shape[1] == self.n_feat assert X.shape[2] == self.inp_units x = (X[..., None, :] @ self.weights).squeeze(-2) x = x + self.bias return x
26
355
91
446
""" SharedEmbeddings is inspired by the TabTransformer available in AutoGluon: https://github.com/awslabs/autogluon/tree/master/tabular/src/autogluon/tabular/models/tab_transformer PiecewiseContEmbeddings and PeriodicContEmbeddings are presented in the paper: 'On Embeddings for Numerical Features in Tabular Deep Learn...
""" SharedEmbeddings is inspired by the TabTransformer available in AutoGluon: https://github.com/awslabs/autogluon/tree/master/tabular/src/autogluon/tabular/models/tab_transformer PiecewiseContEmbeddings and PeriodicContEmbeddings are presented in the paper: 'On Embeddings for Numerical Features in Tabular Deep Learn...
36,701
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep
/home/hieuvd/dung_repo/raw/stars_02/jrzaurin_pytorch-widedeep/pytorch-widedeep/pytorch_widedeep/models/tabular/embeddings_layers.py
280,281
232,298
reset_parameters
PeriodicContEmbeddings
281,284
281,284
class PeriodicContEmbeddings(nn.Module): def __init__( self, n_cont_cols: int, embed_dim: int, embed_dropout: float, full_embed_dropout: bool, n_frequencies: int, sigma: float, share_last_layer: bool, activation_fn: Optional[str] = None, ) ...
class PeriodicContEmbeddings(nn.Module): def __init__( self, n_cont_cols: int, embed_dim: int, embed_dropout: float, full_embed_dropout: bool, n_frequencies: int, sigma: float, share_last_layer: bool, activation_fn: Optional[str] = None, ) ...
bound = self.sigma * 3 nn.init.trunc_normal_(self.weight_perdiodic, 0.0, self.sigma, a=-bound, b=bound)
bound = self.sigma * 3 nn.init.trunc_normal_(self.weight_perdiodic, 0.0, self.sigma, a=-bound, b=bound)
10
707
53
760
""" SharedEmbeddings is inspired by the TabTransformer available in AutoGluon: https://github.com/awslabs/autogluon/tree/master/tabular/src/autogluon/tabular/models/tab_transformer PiecewiseContEmbeddings and PeriodicContEmbeddings are presented in the paper: 'On Embeddings for Numerical Features in Tabular Deep Learn...
""" SharedEmbeddings is inspired by the TabTransformer available in AutoGluon: https://github.com/awslabs/autogluon/tree/master/tabular/src/autogluon/tabular/models/tab_transformer PiecewiseContEmbeddings and PeriodicContEmbeddings are presented in the paper: 'On Embeddings for Numerical Features in Tabular Deep Learn...