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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
42,619 | /home/hieuvd/dung_repo/raw/stars_03/1nchaos_adata/adata | /home/hieuvd/dung_repo/raw/stars_03/1nchaos_adata/adata/adata/common/exception/handler.py | 12,13 | 1,20 | handler_null | 13,20 | 13,20 | # -*- coding: utf-8 -*-
"""
@desc: readme
@author: 1nchaos
@time: 2023/8/14
@log: change log
"""
import pandas as pd
def handler_null(func):
FILL_FUNC_BODY | # -*- coding: utf-8 -*-
"""
@desc: readme
@author: 1nchaos
@time: 2023/8/14
@log: change log
"""
import pandas as pd
def handler_null(func):
FILL_FUNC_BODY | def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception:
return pd.DataFrame(data=[], columns=[])
return wrapper
| def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception:
return pd.DataFrame(data=[], columns=[])
return wrapper
| 14 | 80 | 58 | 138 | # -*- coding: utf-8 -*-
"""
@desc: readme
@author: 1nchaos
@time: 2023/8/14
@log: change log
"""
import pandas as pd
def handler_null(func):
FILL_FUNC_BODY | # -*- coding: utf-8 -*-
"""
@desc: readme
@author: 1nchaos
@time: 2023/8/14
@log: change log
"""
import pandas as pd
def handler_null(func):
FILL_FUNC_BODY | |
42,620 | /home/hieuvd/dung_repo/raw/stars_03/1nchaos_adata/adata | /home/hieuvd/dung_repo/raw/stars_03/1nchaos_adata/adata/adata/common/utils/code_utils.py | 10,11 | 1,24 | compile_exchange_by_stock_code | 12,24 | 11,24 | # -*- coding: utf-8 -*-
"""
@desc: readme
@author: yinchao
@time: 2023/12/4
@log: change log
"""
def compile_exchange_by_stock_code(stock_code):
FILL_FUNC_BODY | # -*- coding: utf-8 -*-
"""
@desc: readme
@author: yinchao
@time: 2023/12/4
@log: change log
"""
def compile_exchange_by_stock_code(stock_code):
"""根据股票代码补全市场后缀"""
FILL_FUNC_BODY | exchange_suffix = {
'0': '.SZ',
'3': '.SZ',
'6': '.SH',
'9': '.SH',
'4': '.BJ',
'8': '.BJ'
}
prefix = stock_code[0]
if prefix in exchange_suffix:
return stock_code + exchange_suffix[prefix]
return stock_code
| """根据股票代码补全市场后缀"""
exchange_suffix = {
'0': '.SZ',
'3': '.SZ',
'6': '.SH',
'9': '.SH',
'4': '.BJ',
'8': '.BJ'
}
prefix = stock_code[0]
if prefix in exchange_suffix:
return stock_code + exchange_suffix[prefix]
return stock_code
| 29 | 94 | 115 | 209 | # -*- coding: utf-8 -*-
"""
@desc: readme
@author: yinchao
@time: 2023/12/4
@log: change log
"""
def compile_exchange_by_stock_code(stock_code):
FILL_FUNC_BODY | # -*- coding: utf-8 -*-
"""
@desc: readme
@author: yinchao
@time: 2023/12/4
@log: change log
"""
def compile_exchange_by_stock_code(stock_code):
"""根据股票代码补全市场后缀"""
FILL_FUNC_BODY | |
42,621 | /home/hieuvd/dung_repo/raw/stars_03/1nchaos_adata/adata | /home/hieuvd/dung_repo/raw/stars_03/1nchaos_adata/adata/adata/common/utils/cookie.py | 21,22 | 1,36 | get_file_content_ths | 27,34 | 22,34 | # -*- coding: utf-8 -*-
"""
@desc: 获取cookie的工具类
@author: 1nchaos
@time: 2023/5/5
@log: change log
"""
import os
from py_mini_racer import py_mini_racer
def ths_cookie(js_path="ths.js"):
"""获取同花顺cookie"""
js_code = py_mini_racer.MiniRacer()
js_content = get_file_content_ths(file_path=js_path)
js_code.... | # -*- coding: utf-8 -*-
"""
@desc: 获取cookie的工具类
@author: 1nchaos
@time: 2023/5/5
@log: change log
"""
import os
from py_mini_racer import py_mini_racer
def ths_cookie(js_path="ths.js"):
"""获取同花顺cookie"""
js_code = py_mini_racer.MiniRacer()
js_content = get_file_content_ths(file_path=js_path)
js_code.... | _curpath = os.path.normpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
f_path = _curpath.replace('utils', 'js/') + file_path
with open(f_path) as f:
file_data = f.read()
return file_data
| """
获取 JS 文件的内容
:param file_path: JS 文件名
:return: 文件内容
"""
_curpath = os.path.normpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
f_path = _curpath.replace('utils', 'js/') + file_path
with open(f_path) as f:
file_data = f.read()
return file_data
| 19 | 268 | 94 | 362 | # -*- coding: utf-8 -*-
"""
@desc: 获取cookie的工具类
@author: 1nchaos
@time: 2023/5/5
@log: change log
"""
import os
from py_mini_racer import py_mini_racer
def ths_cookie(js_path="ths.js"):
"""获取同花顺cookie"""
js_code = py_mini_racer.MiniRacer()
js_content = get_file_content_ths(file_path=js_path)
js_code.... | # -*- coding: utf-8 -*-
"""
@desc: 获取cookie的工具类
@author: 1nchaos
@time: 2023/5/5
@log: change log
"""
import os
from py_mini_racer import py_mini_racer
def ths_cookie(js_path="ths.js"):
"""获取同花顺cookie"""
js_code = py_mini_racer.MiniRacer()
js_content = get_file_content_ths(file_path=js_path)
js_code.... | |
42,622 | /home/hieuvd/dung_repo/raw/stars_03/1nchaos_adata/adata | /home/hieuvd/dung_repo/raw/stars_03/1nchaos_adata/adata/adata/common/utils/sunrequests.py | 38,40 | 17,44 | delete | SunProxy | 40,44 | 40,44 | class SunProxy(object):
_data = {}
_instance_lock = threading.Lock()
def __init__(self):
pass
def __new__(cls, *args, **kwargs):
if not hasattr(SunProxy, "_instance"):
with SunProxy._instance_lock:
if not hasattr(SunProxy, "_instance"):
S... | class SunProxy(object):
_data = {}
_instance_lock = threading.Lock()
def __init__(self):
pass
def __new__(cls, *args, **kwargs):
if not hasattr(SunProxy, "_instance"):
with SunProxy._instance_lock:
if not hasattr(SunProxy, "_instance"):
S... | if key in cls._data:
del cls._data[key]
| if key in cls._data:
del cls._data[key]
| 6 | 183 | 26 | 209 | # -*- coding: utf-8 -*-
"""
代理:https://jahttp.zhimaruanjian.com/getapi/
@desc: adata 请求工具类
@author: 1nchaos
@time:2023/3/30
@log: 封装请求次数
"""
import threading
import time
import requests
class SunProxy(object):
_data = {}
_instance_lock = threading.Lock()
def __init__(self):
pass
def __new... | # -*- coding: utf-8 -*-
"""
代理:https://jahttp.zhimaruanjian.com/getapi/
@desc: adata 请求工具类
@author: 1nchaos
@time:2023/3/30
@log: 封装请求次数
"""
import threading
import time
import requests
class SunProxy(object):
_data = {}
_instance_lock = threading.Lock()
def __init__(self):
pass
def __new... |
42,623 | /home/hieuvd/dung_repo/raw/stars_03/1nchaos_adata/adata | /home/hieuvd/dung_repo/raw/stars_03/1nchaos_adata/adata/adata/common/utils/sunrequests.py | 76,77 | 44,93 | __get_proxies | SunRequests | 80,93 | 77,93 | class SunRequests(object):
def __init__(self, sun_proxy: SunProxy = None) -> None:
super().__init__()
self.sun_proxy = sun_proxy
def request(self, method='get', url=None, times=3, retry_wait_time=1588, proxies=None, wait_time=None, **kwargs):
"""
简单封装的请求,参考requests,增加循环次数和次数之间的等... | class SunRequests(object):
def __init__(self, sun_proxy: SunProxy = None) -> None:
super().__init__()
self.sun_proxy = sun_proxy
def request(self, method='get', url=None, times=3, retry_wait_time=1588, proxies=None, wait_time=None, **kwargs):
"""
简单封装的请求,参考requests,增加循环次数和次数之间的等... | if proxies is None:
proxies = {}
is_proxy = SunProxy.get('is_proxy')
ip = SunProxy.get('ip')
proxy_url = SunProxy.get('proxy_url')
if not ip and is_proxy and proxy_url:
ip = requests.get(url=proxy_url).text.replace('\r\n', '') \
.replace('\... | """
获取代理配置
"""
if proxies is None:
proxies = {}
is_proxy = SunProxy.get('is_proxy')
ip = SunProxy.get('ip')
proxy_url = SunProxy.get('proxy_url')
if not ip and is_proxy and proxy_url:
ip = requests.get(url=proxy_url).text.replace('\... | 44 | 451 | 179 | 630 | # -*- coding: utf-8 -*-
"""
代理:https://jahttp.zhimaruanjian.com/getapi/
@desc: adata 请求工具类
@author: 1nchaos
@time:2023/3/30
@log: 封装请求次数
"""
import threading
import time
import requests
class SunProxy(object):
_data = {}
_instance_lock = threading.Lock()
def __init__(self):
pass
def __new... | # -*- coding: utf-8 -*-
"""
代理:https://jahttp.zhimaruanjian.com/getapi/
@desc: adata 请求工具类
@author: 1nchaos
@time:2023/3/30
@log: 封装请求次数
"""
import threading
import time
import requests
class SunProxy(object):
_data = {}
_instance_lock = threading.Lock()
def __init__(self):
pass
def __new... |
42,624 | /home/hieuvd/dung_repo/raw/stars_03/1nchaos_adata/adata | /home/hieuvd/dung_repo/raw/stars_03/1nchaos_adata/adata/setup.py | 28,29 | 1,66 | setup_package | 29,64 | 29,64 | # -*- coding: utf-8 -*-
"""
@desc: setup
@author: 1nchaos
@time: 2023/04/05
"""
import os
from setuptools import find_packages
here = os.path.abspath(os.path.dirname(__file__))
about = {}
with open(os.path.join(here, "adata", "__version__.py"), "r") as f:
exec(f.read(), about)
with open("README.md", "r", encodi... | # -*- coding: utf-8 -*-
"""
@desc: setup
@author: 1nchaos
@time: 2023/04/05
"""
import os
from setuptools import find_packages
here = os.path.abspath(os.path.dirname(__file__))
about = {}
with open(os.path.join(here, "adata", "__version__.py"), "r") as f:
exec(f.read(), about)
with open("README.md", "r", encodi... | metadata = dict(
name=about["__title__"],
version=about["__version__"],
description=about["__description__"],
long_description=readme,
long_description_content_type="text/markdown",
url=about["__url__"],
author=about["__author__"],
author_email=about["... | metadata = dict(
name=about["__title__"],
version=about["__version__"],
description=about["__description__"],
long_description=readme,
long_description_content_type="text/markdown",
url=about["__url__"],
author=about["__author__"],
author_email=about["... | 87 | 257 | 377 | 634 | # -*- coding: utf-8 -*-
"""
@desc: setup
@author: 1nchaos
@time: 2023/04/05
"""
import os
from setuptools import find_packages
here = os.path.abspath(os.path.dirname(__file__))
about = {}
with open(os.path.join(here, "adata", "__version__.py"), "r") as f:
exec(f.read(), about)
with open("README.md", "r", encodi... | # -*- coding: utf-8 -*-
"""
@desc: setup
@author: 1nchaos
@time: 2023/04/05
"""
import os
from setuptools import find_packages
here = os.path.abspath(os.path.dirname(__file__))
about = {}
with open(os.path.join(here, "adata", "__version__.py"), "r") as f:
exec(f.read(), about)
with open("README.md", "r", encodi... | |
42,630 | /home/hieuvd/dung_repo/raw/stars_03/3ndG4me_AutoBlue-MS17-010/AutoBlue-MS17-010 | /home/hieuvd/dung_repo/raw/stars_03/3ndG4me_AutoBlue-MS17-010/AutoBlue-MS17-010/eternal_checker.py | 31,32 | 1,90 | main | 32,89 | 32,89 | from mysmb import MYSMB
from impacket import smb, smbconnection, nt_errors
from impacket.uuid import uuidtup_to_bin
from impacket.dcerpc.v5.rpcrt import DCERPCException
from struct import pack
import sys
import argparse
'''
Script for
- check target if MS17-010 is patched or not.
- find accessible named pipe
'''
de... | from mysmb import MYSMB
from impacket import smb, smbconnection, nt_errors
from impacket.uuid import uuidtup_to_bin
from impacket.dcerpc.v5.rpcrt import DCERPCException
from struct import pack
import sys
import argparse
'''
Script for
- check target if MS17-010 is patched or not.
- find accessible named pipe
'''
de... | parser = argparse.ArgumentParser()
parser.add_argument('target', action='store',
help='[[domain/]username[:password]@]<targetName or address>')
group = parser.add_argument_group('connection')
group.add_argument('-target-ip', action='store', metavar="ip address",
help='IP Address of the ta... | parser = argparse.ArgumentParser()
parser.add_argument('target', action='store',
help='[[domain/]username[:password]@]<targetName or address>')
group = parser.add_argument_group('connection')
group.add_argument('-target-ip', action='store', metavar="ip address",
help='IP Address of the ta... | 171 | 324 | 724 | 1,048 | from mysmb import MYSMB
from impacket import smb, smbconnection, nt_errors
from impacket.uuid import uuidtup_to_bin
from impacket.dcerpc.v5.rpcrt import DCERPCException
from struct import pack
import sys
import argparse
'''
Script for
- check target if MS17-010 is patched or not.
- find accessible named pipe
'''
de... | from mysmb import MYSMB
from impacket import smb, smbconnection, nt_errors
from impacket.uuid import uuidtup_to_bin
from impacket.dcerpc.v5.rpcrt import DCERPCException
from struct import pack
import sys
import argparse
'''
Script for
- check target if MS17-010 is patched or not.
- find accessible named pipe
'''
de... | |
42,632 | /home/hieuvd/dung_repo/raw/stars_03/8080labs_pyforest/pyforest | /home/hieuvd/dung_repo/raw/stars_03/8080labs_pyforest/pyforest/src/pyforest/_importable.py | 116,117 | 1,125 | _get_import_statements | 117,125 | 117,125 | # Attention: LazyImport uses __double_dunder_methods__ instead of _var
# because we want to minimize the risk of collision.
# Collision happens if the imported module/object has an attribute with the same name.
# The result of collision is that the attribute of the imported module/object is masked.
# So, we are trading... | # Attention: LazyImport uses __double_dunder_methods__ instead of _var
# because we want to minimize the risk of collision.
# Collision happens if the imported module/object has an attribute with the same name.
# The result of collision is that the attribute of the imported module/object is masked.
# So, we are trading... | statements = []
for _, symbol in symbol_dict.items():
if isinstance(symbol, LazyImport) and (symbol.__was_imported__ == was_imported):
statements.append(symbol.__import_statement__)
# remove potential duplicates, e.g. when user_symbols are passed
statements = list(set(statements))
... | statements = []
for _, symbol in symbol_dict.items():
if isinstance(symbol, LazyImport) and (symbol.__was_imported__ == was_imported):
statements.append(symbol.__import_statement__)
# remove potential duplicates, e.g. when user_symbols are passed
statements = list(set(statements))
... | 30 | 1,348 | 99 | 1,447 | # Attention: LazyImport uses __double_dunder_methods__ instead of _var
# because we want to minimize the risk of collision.
# Collision happens if the imported module/object has an attribute with the same name.
# The result of collision is that the attribute of the imported module/object is masked.
# So, we are trading... | # Attention: LazyImport uses __double_dunder_methods__ instead of _var
# because we want to minimize the risk of collision.
# Collision happens if the imported module/object has an attribute with the same name.
# The result of collision is that the attribute of the imported module/object is masked.
# So, we are trading... | |
42,634 | /home/hieuvd/dung_repo/raw/stars_03/8080labs_pyforest/pyforest | /home/hieuvd/dung_repo/raw/stars_03/8080labs_pyforest/pyforest/src/pyforest/auto_import.py | 17,18 | 1,50 | _write_into_startup_file | 18,36 | 18,36 | from pathlib import Path
IPYTHON_STARTUP_FOLDER = Path.home() / ".ipython" / "profile_default" / "startup"
STARTUP_FILE = IPYTHON_STARTUP_FOLDER / "pyforest_autoimport.py"
def _create_or_reset_startup_file():
if STARTUP_FILE.exists():
STARTUP_FILE.unlink() # deletes the old file
# this is impor... | from pathlib import Path
IPYTHON_STARTUP_FOLDER = Path.home() / ".ipython" / "profile_default" / "startup"
STARTUP_FILE = IPYTHON_STARTUP_FOLDER / "pyforest_autoimport.py"
def _create_or_reset_startup_file():
if STARTUP_FILE.exists():
STARTUP_FILE.unlink() # deletes the old file
# this is impor... | with STARTUP_FILE.open("w") as file:
file.write(
f"""
# HOW TO DEACTIVATE AUTO-IMPORT:
# if you dont want to auto-import pyforest, you have two options:
# 0) if you only want to disable the auto-import temporarily and activate it later,
# you can uncomment the import statement below
# 1) if y... | with STARTUP_FILE.open("w") as file:
file.write(
f"""
# HOW TO DEACTIVATE AUTO-IMPORT:
# if you dont want to auto-import pyforest, you have two options:
# 0) if you only want to disable the auto-import temporarily and activate it later,
# you can uncomment the import statement below
# 1) if y... | 81 | 336 | 176 | 512 | from pathlib import Path
IPYTHON_STARTUP_FOLDER = Path.home() / ".ipython" / "profile_default" / "startup"
STARTUP_FILE = IPYTHON_STARTUP_FOLDER / "pyforest_autoimport.py"
def _create_or_reset_startup_file():
if STARTUP_FILE.exists():
STARTUP_FILE.unlink() # deletes the old file
# this is impor... | from pathlib import Path
IPYTHON_STARTUP_FOLDER = Path.home() / ".ipython" / "profile_default" / "startup"
STARTUP_FILE = IPYTHON_STARTUP_FOLDER / "pyforest_autoimport.py"
def _create_or_reset_startup_file():
if STARTUP_FILE.exists():
STARTUP_FILE.unlink() # deletes the old file
# this is impor... | |
42,635 | /home/hieuvd/dung_repo/raw/stars_03/8080labs_pyforest/pyforest | /home/hieuvd/dung_repo/raw/stars_03/8080labs_pyforest/pyforest/src/pyforest/user_specific_imports.py | 70,73 | 1,75 | _load_user_specific_imports | 73,75 | 73,75 | from ._importable import LazyImport
from pathlib import Path
USER_IMPORTS_PATH = Path.home() / ".pyforest" / "user_imports.py"
TEMPLATE_TEXT = """# Add your imports here, line by line
# e.g
# import pandas as pd
# from pathlib import Path
# import re
"""
def _clean_line(x: str) -> str:
return x.replace("\n", ""... | from ._importable import LazyImport
from pathlib import Path
USER_IMPORTS_PATH = Path.home() / ".pyforest" / "user_imports.py"
TEMPLATE_TEXT = """# Add your imports here, line by line
# e.g
# import pandas as pd
# from pathlib import Path
# import re
"""
def _clean_line(x: str) -> str:
return x.replace("\n", ""... | import_statements = _get_imports_from_user_settings(user_imports_path)
_assign_imports_to_globals(import_statements, globals_)
| import_statements = _get_imports_from_user_settings(user_imports_path)
_assign_imports_to_globals(import_statements, globals_)
| 5 | 787 | 49 | 836 | from ._importable import LazyImport
from pathlib import Path
USER_IMPORTS_PATH = Path.home() / ".pyforest" / "user_imports.py"
TEMPLATE_TEXT = """# Add your imports here, line by line
# e.g
# import pandas as pd
# from pathlib import Path
# import re
"""
def _clean_line(x: str) -> str:
return x.replace("\n", ""... | from ._importable import LazyImport
from pathlib import Path
USER_IMPORTS_PATH = Path.home() / ".pyforest" / "user_imports.py"
TEMPLATE_TEXT = """# Add your imports here, line by line
# e.g
# import pandas as pd
# from pathlib import Path
# import re
"""
def _clean_line(x: str) -> str:
return x.replace("\n", ""... | |
42,636 | /home/hieuvd/dung_repo/raw/stars_03/8080labs_pyforest/pyforest | /home/hieuvd/dung_repo/raw/stars_03/8080labs_pyforest/pyforest/src/pyforest/utils.py | 45,46 | 1,71 | install_labextension | 46,71 | 46,71 | def get_user_symbols():
import inspect
for index, item in enumerate(inspect.stack()):
try:
name = item[0].f_globals["__name__"]
if name == "__main__":
return item[0].f_globals
except: # __name__ attribute does not exist
pass
return {}
d... | def get_user_symbols():
import inspect
for index, item in enumerate(inspect.stack()):
try:
name = item[0].f_globals["__name__"]
if name == "__main__":
return item[0].f_globals
except: # __name__ attribute does not exist
pass
return {}
d... | print("Trying to install pyforest labextension...")
try:
from jupyterlab import commands
except ImportError:
print(
"Could not install pyforest Jupyter Lab extension because Jupyter Lab is not available"
)
return
from pathlib import Path
dir = Path(__fi... | print("Trying to install pyforest labextension...")
try:
from jupyterlab import commands
except ImportError:
print(
"Could not install pyforest Jupyter Lab extension because Jupyter Lab is not available"
)
return
from pathlib import Path
dir = Path(__fi... | 62 | 399 | 217 | 616 | def get_user_symbols():
import inspect
for index, item in enumerate(inspect.stack()):
try:
name = item[0].f_globals["__name__"]
if name == "__main__":
return item[0].f_globals
except: # __name__ attribute does not exist
pass
return {}
d... | def get_user_symbols():
import inspect
for index, item in enumerate(inspect.stack()):
try:
name = item[0].f_globals["__name__"]
if name == "__main__":
return item[0].f_globals
except: # __name__ attribute does not exist
pass
return {}
d... | |
42,717 | /home/hieuvd/dung_repo/raw/stars_03/DeppWang_youdaonote-pull/youdaonote-pull | /home/hieuvd/dung_repo/raw/stars_03/DeppWang_youdaonote-pull/youdaonote-pull/core/api.py | 44,45 | 6,137 | login_by_cookies | YoudaoNoteApi | 49,63 | 45,63 | class YoudaoNoteApi(object):
"""
有道云笔记 API 封装
原理:https://depp.wang/2020/06/11/how-to-find-the-api-of-a-website-eg-note-youdao-com/
"""
ROOT_ID_URL = "https://note.youdao.com/yws/api/personal/file?method=getByPath&keyfrom=web&cstk={cstk}"
DIR_MES_URL = (
"https://note.youdao.com/yws/api/... | class YoudaoNoteApi(object):
"""
有道云笔记 API 封装
原理:https://depp.wang/2020/06/11/how-to-find-the-api-of-a-website-eg-note-youdao-com/
"""
ROOT_ID_URL = "https://note.youdao.com/yws/api/personal/file?method=getByPath&keyfrom=web&cstk={cstk}"
DIR_MES_URL = (
"https://note.youdao.com/yws/api/... | try:
cookies = self._covert_cookies()
except Exception as err:
return format(err)
for cookie in cookies:
self.session.cookies.set(
name=cookie[0], value=cookie[1], domain=cookie[2], path=cookie[3]
)
self.cstk = (
... | """
使用 Cookies 登录,其实就是设置 Session 的 Cookies
:return: error_msg
"""
try:
cookies = self._covert_cookies()
except Exception as err:
return format(err)
for cookie in cookies:
self.session.cookies.set(
name=cookie[0],... | 40 | 1,549 | 173 | 1,722 | import json
import requests
class YoudaoNoteApi(object):
"""
有道云笔记 API 封装
原理:https://depp.wang/2020/06/11/how-to-find-the-api-of-a-website-eg-note-youdao-com/
"""
ROOT_ID_URL = "https://note.youdao.com/yws/api/personal/file?method=getByPath&keyfrom=web&cstk={cstk}"
DIR_MES_URL = (
"h... | import json
import requests
class YoudaoNoteApi(object):
"""
有道云笔记 API 封装
原理:https://depp.wang/2020/06/11/how-to-find-the-api-of-a-website-eg-note-youdao-com/
"""
ROOT_ID_URL = "https://note.youdao.com/yws/api/personal/file?method=getByPath&keyfrom=web&cstk={cstk}"
DIR_MES_URL = (
"h... |
42,718 | /home/hieuvd/dung_repo/raw/stars_03/DeppWang_youdaonote-pull/youdaonote-pull | /home/hieuvd/dung_repo/raw/stars_03/DeppWang_youdaonote-pull/youdaonote-pull/core/covert.py | 298,299 | 167,324 | convert_t_func | JsonConvert | 302,324 | 299,324 | class JsonConvert(object):
"""
json 转换规则
"""
def _get_common_text(self, content: dict) -> Tuple[list, str]:
"""获取通常文本
:return
text(text): 文本内容
"""
text = ""
# 5 内容
five_contents = content.get("5")
# 判断是否是普通文本
if five_contents:
... | class JsonConvert(object):
"""
json 转换规则
"""
def _get_common_text(self, content: dict) -> Tuple[list, str]:
"""获取通常文本
:return
text(text): 文本内容
"""
text = ""
# 5 内容
five_contents = content.get("5")
# 判断是否是普通文本
if five_contents:
... | nl = "\r\n" # 考虑 Windows 系统,换行符设为 \r\n
tr_list = content["5"]
table_lines = ""
for index, tc in enumerate(tr_list):
table_content_list = tc["5"]
table_content_len = len(table_content_list)
if index == 1:
table_line = "| -- " * table_c... | """
表格转换
"""
nl = "\r\n" # 考虑 Windows 系统,换行符设为 \r\n
tr_list = content["5"]
table_lines = ""
for index, tc in enumerate(tr_list):
table_content_list = tc["5"]
table_content_len = len(table_content_list)
if index == 1:
... | 79 | 1,398 | 279 | 1,677 | import json
import logging
import os
import xml.etree.ElementTree as ET
from typing import Tuple
MARKDOWN_SUFFIX = ".md"
class XmlElementConvert(object):
"""
XML Element 转换规则
"""
@staticmethod
def convert_para_func(**kwargs):
"""正常文本(粗体、斜体、删除线、链接)"""
return kwargs.get("text")
... | import json
import logging
import os
import xml.etree.ElementTree as ET
from typing import Tuple
MARKDOWN_SUFFIX = ".md"
class XmlElementConvert(object):
"""
XML Element 转换规则
"""
@staticmethod
def convert_para_func(**kwargs):
"""正常文本(粗体、斜体、删除线、链接)"""
return kwargs.get("text")
... |
42,719 | /home/hieuvd/dung_repo/raw/stars_03/DeppWang_youdaonote-pull/youdaonote-pull | /home/hieuvd/dung_repo/raw/stars_03/DeppWang_youdaonote-pull/youdaonote-pull/core/covert.py | 38,40 | 10,167 | convert_attach_func | XmlElementConvert | 41,48 | 40,48 | class XmlElementConvert(object):
"""
XML Element 转换规则
"""
@staticmethod
def convert_para_func(**kwargs):
"""正常文本(粗体、斜体、删除线、链接)"""
return kwargs.get("text")
@staticmethod
def convert_heading_func(**kwargs):
"""标题"""
level = kwargs.get("element").attrib.get("l... | class XmlElementConvert(object):
"""
XML Element 转换规则
"""
@staticmethod
def convert_para_func(**kwargs):
"""正常文本(粗体、斜体、删除线、链接)"""
return kwargs.get("text")
@staticmethod
def convert_heading_func(**kwargs):
"""标题"""
level = kwargs.get("element").attrib.get("l... | element = kwargs.get("element")
filename = XmlElementConvert.get_text_by_key(list(element), "filename")
resource_url = XmlElementConvert.get_text_by_key(list(element), "resource")
return "[{text}]({resource_url})".format(
text=filename, resource_url=resource_url
)
| """附件"""
element = kwargs.get("element")
filename = XmlElementConvert.get_text_by_key(list(element), "filename")
resource_url = XmlElementConvert.get_text_by_key(list(element), "resource")
return "[{text}]({resource_url})".format(
text=filename, resource_url=resource_... | 16 | 1,650 | 102 | 1,752 | import json
import logging
import os
import xml.etree.ElementTree as ET
from typing import Tuple
MARKDOWN_SUFFIX = ".md"
class XmlElementConvert(object):
"""
XML Element 转换规则
"""
@staticmethod
def convert_para_func(**kwargs):
"""正常文本(粗体、斜体、删除线、链接)"""
return kwargs.get("text")
... | import json
import logging
import os
import xml.etree.ElementTree as ET
from typing import Tuple
MARKDOWN_SUFFIX = ".md"
class XmlElementConvert(object):
"""
XML Element 转换规则
"""
@staticmethod
def convert_para_func(**kwargs):
"""正常文本(粗体、斜体、删除线、链接)"""
return kwargs.get("text")
... |
42,720 | /home/hieuvd/dung_repo/raw/stars_03/DeppWang_youdaonote-pull/youdaonote-pull | /home/hieuvd/dung_repo/raw/stars_03/DeppWang_youdaonote-pull/youdaonote-pull/core/covert.py | 348,350 | 324,448 | _covert_xml_to_markdown_content | YoudaoNoteConvert | 350,376 | 350,376 | class YoudaoNoteConvert(object):
"""
有道云笔记 note 内容转换为 markdown 内容
"""
@staticmethod
def covert_html_to_markdown(file_path):
"""
转换 HTML 为 MarkDown
:param file_path:
:return:
"""
with open(file_path, "rb") as f:
content_str = f.read().decod... | class YoudaoNoteConvert(object):
"""
有道云笔记 note 内容转换为 markdown 内容
"""
@staticmethod
def covert_html_to_markdown(file_path):
"""
转换 HTML 为 MarkDown
:param file_path:
:return:
"""
with open(file_path, "rb") as f:
content_str = f.read().decod... | # 使用 xml.etree.ElementTree 将 xml 文件转换为对象
element_tree = ET.parse(file_path)
note_element = element_tree.getroot() # note Element
# list_item 的 id 与 type 的对应
list_item = {}
for child in note_element[0]:
if "list" in child.tag:
list_item[child.... | # 使用 xml.etree.ElementTree 将 xml 文件转换为对象
element_tree = ET.parse(file_path)
note_element = element_tree.getroot() # note Element
# list_item 的 id 与 type 的对应
list_item = {}
for child in note_element[0]:
if "list" in child.tag:
list_item[child.... | 82 | 1,139 | 370 | 1,509 | import json
import logging
import os
import xml.etree.ElementTree as ET
from typing import Tuple
MARKDOWN_SUFFIX = ".md"
class XmlElementConvert(object):
"""
XML Element 转换规则
"""
@staticmethod
def convert_para_func(**kwargs):
"""正常文本(粗体、斜体、删除线、链接)"""
return kwargs.get("text")
... | import json
import logging
import os
import xml.etree.ElementTree as ET
from typing import Tuple
MARKDOWN_SUFFIX = ".md"
class XmlElementConvert(object):
"""
XML Element 转换规则
"""
@staticmethod
def convert_para_func(**kwargs):
"""正常文本(粗体、斜体、删除线、链接)"""
return kwargs.get("text")
... |
42,721 | /home/hieuvd/dung_repo/raw/stars_03/DeppWang_youdaonote-pull/youdaonote-pull | /home/hieuvd/dung_repo/raw/stars_03/DeppWang_youdaonote-pull/youdaonote-pull/core/log.py | 10,11 | 1,26 | init_logging | 11,26 | 11,26 | import logging
import os
import sys
import time
LOG_FORMAT = "%(asctime)s %(levelname)s %(processName)s-%(threadName)s-%(thread)d %(filename)s:%(lineno)d %(funcName)-10s : %(message)s"
DATE_FORMAT = "%Y/%m/%d %H:%M:%S "
def init_logging():
FILL_FUNC_BODY | import logging
import os
import sys
import time
LOG_FORMAT = "%(asctime)s %(levelname)s %(processName)s-%(threadName)s-%(thread)d %(filename)s:%(lineno)d %(funcName)-10s : %(message)s"
DATE_FORMAT = "%Y/%m/%d %H:%M:%S "
def init_logging():
FILL_FUNC_BODY | log_dir = "logs"
if not os.path.exists(log_dir):
os.mkdir(log_dir)
logging.basicConfig(
handlers=[
logging.FileHandler(
"logs/pull-{}.log".format(int(time.time())), "a", encoding="utf-8"
),
logging.StreamHandler(sys.stdout),
],
... | log_dir = "logs"
if not os.path.exists(log_dir):
os.mkdir(log_dir)
logging.basicConfig(
handlers=[
logging.FileHandler(
"logs/pull-{}.log".format(int(time.time())), "a", encoding="utf-8"
),
logging.StreamHandler(sys.stdout),
],
... | 20 | 117 | 149 | 266 | import logging
import os
import sys
import time
LOG_FORMAT = "%(asctime)s %(levelname)s %(processName)s-%(threadName)s-%(thread)d %(filename)s:%(lineno)d %(funcName)-10s : %(message)s"
DATE_FORMAT = "%Y/%m/%d %H:%M:%S "
def init_logging():
FILL_FUNC_BODY | import logging
import os
import sys
import time
LOG_FORMAT = "%(asctime)s %(levelname)s %(processName)s-%(threadName)s-%(thread)d %(filename)s:%(lineno)d %(funcName)-10s : %(message)s"
DATE_FORMAT = "%Y/%m/%d %H:%M:%S "
def init_logging():
FILL_FUNC_BODY | |
43,220 | /home/hieuvd/dung_repo/raw/stars_03/GamehunterKaan_AutoPWN-Suite/AutoPWN-Suite | /home/hieuvd/dung_repo/raw/stars_03/GamehunterKaan_AutoPWN-Suite/AutoPWN-Suite/api.py | 65,72 | 13,178 | CreateScanArgs | AutoScanner | 72,100 | 72,100 | class AutoScanner:
def __init__(self) -> None:
self.scan_results = {}
def __str__(self) -> str:
return str(self.scan_results)
def InitHostInfo(self, target_key: JSON) -> JSON:
os_info = {}
try:
mac = target_key["addresses"]["mac"]
except (KeyError, Index... | class AutoScanner:
def __init__(self) -> None:
self.scan_results = {}
def __str__(self) -> str:
return str(self.scan_results)
def InitHostInfo(self, target_key: JSON) -> JSON:
os_info = {}
try:
mac = target_key["addresses"]["mac"]
except (KeyError, Index... |
scan_args = ["-sV"]
if host_timeout:
scan_args.append("--host-timeout")
scan_args.append(str(host_timeout))
if scan_speed and scan_speed in range(0, 6):
scan_args.append("-T")
scan_args.append(str(scan_speed))
elif scan_speed and not sca... |
scan_args = ["-sV"]
if host_timeout:
scan_args.append("--host-timeout")
scan_args.append(str(host_timeout))
if scan_speed and scan_speed in range(0, 6):
scan_args.append("-T")
scan_args.append(str(scan_speed))
elif scan_speed and not sca... | 68 | 1,232 | 285 | 1,517 | from json import dumps
from typing import Any, Dict, List, Type, Union
from nmap import PortScanner
from modules.nist_search import searchCVE
from modules.searchvuln import GenerateKeyword
from modules.utils import fake_logger, is_root
JSON = Union[Dict[str, Any], List[Any], int, str, float, bool, Type[None]]
clas... | from json import dumps
from typing import Any, Dict, List, Type, Union
from nmap import PortScanner
from modules.nist_search import searchCVE
from modules.searchvuln import GenerateKeyword
from modules.utils import fake_logger, is_root
JSON = Union[Dict[str, Any], List[Any], int, str, float, bool, Type[None]]
clas... |
43,221 | /home/hieuvd/dung_repo/raw/stars_03/GamehunterKaan_AutoPWN-Suite/AutoPWN-Suite | /home/hieuvd/dung_repo/raw/stars_03/GamehunterKaan_AutoPWN-Suite/AutoPWN-Suite/autopwn.py | 32,35 | 1,114 | StartScanning | 35,71 | 35,71 | from datetime import datetime
from rich.console import Console
from modules.banners import print_banner
from modules.getexploits import GetExploitsFromArray
from modules.logger import Logger
from modules.report import InitializeReport
from modules.scanner import AnalyseScanResults, DiscoverHosts, NoiseScan, PortScan
... | from datetime import datetime
from rich.console import Console
from modules.banners import print_banner
from modules.getexploits import GetExploitsFromArray
from modules.logger import Logger
from modules.report import InitializeReport
from modules.scanner import AnalyseScanResults, DiscoverHosts, NoiseScan, PortScan
... |
check_nmap(log)
if scanmode == ScanMode.Noise:
NoiseScan(targetarg, log, console, scantype, args.noise_timeout)
if not args.skip_discovery:
hosts = DiscoverHosts(targetarg, console, scantype, scanmode)
Targets = GetHostsToScan(hosts, console)
else:
Targets = [targetarg... |
check_nmap(log)
if scanmode == ScanMode.Noise:
NoiseScan(targetarg, log, console, scantype, args.noise_timeout)
if not args.skip_discovery:
hosts = DiscoverHosts(targetarg, console, scantype, scanmode)
Targets = GetHostsToScan(hosts, console)
else:
Targets = [targetarg... | 97 | 681 | 404 | 1,085 | from datetime import datetime
from rich.console import Console
from modules.banners import print_banner
from modules.getexploits import GetExploitsFromArray
from modules.logger import Logger
from modules.report import InitializeReport
from modules.scanner import AnalyseScanResults, DiscoverHosts, NoiseScan, PortScan
... | from datetime import datetime
from rich.console import Console
from modules.banners import print_banner
from modules.getexploits import GetExploitsFromArray
from modules.logger import Logger
from modules.report import InitializeReport
from modules.scanner import AnalyseScanResults, DiscoverHosts, NoiseScan, PortScan
... | |
43,222 | /home/hieuvd/dung_repo/raw/stars_03/GamehunterKaan_AutoPWN-Suite/AutoPWN-Suite | /home/hieuvd/dung_repo/raw/stars_03/GamehunterKaan_AutoPWN-Suite/AutoPWN-Suite/modules/banners.py | 9,10 | 1,41 | print_banner | 10,41 | 10,41 | from rich.align import Align
from rich.panel import Panel
from rich.text import Text
from modules.utils import get_terminal_width
# https://patorjk.com/software/taag/
def print_banner(console) -> None:
FILL_FUNC_BODY | from rich.align import Align
from rich.panel import Panel
from rich.text import Text
from modules.utils import get_terminal_width
# https://patorjk.com/software/taag/
def print_banner(console) -> None:
FILL_FUNC_BODY | width = get_terminal_width()
height = 8
banner = """\
___ __ ____ _ __ _ __ _____ _ __
/ | __ __ / /_ ____ / __ \| | / // | / / / ___/ __ __ (_)/ /_ ___
/ /| | / / / // __// __ \ / /_/ /| | /| / // |/ / \__ \ / / / // // __// _ \\
/ ___ |/ /_/ /... | width = get_terminal_width()
height = 8
banner = """\
___ __ ____ _ __ _ __ _____ _ __
/ | __ __ / /_ ____ / __ \| | / // | / / / ___/ __ __ (_)/ /_ ___
/ /| | / / / // __// __ \ / /_/ /| | /| / // |/ / \__ \ / / / // // __// _ \\
/ ___ |/ /_/ /... | 159 | 74 | 536 | 610 | from rich.align import Align
from rich.panel import Panel
from rich.text import Text
from modules.utils import get_terminal_width
# https://patorjk.com/software/taag/
def print_banner(console) -> None:
FILL_FUNC_BODY | from rich.align import Align
from rich.panel import Panel
from rich.text import Text
from modules.utils import get_terminal_width
# https://patorjk.com/software/taag/
def print_banner(console) -> None:
FILL_FUNC_BODY | |
43,223 | /home/hieuvd/dung_repo/raw/stars_03/GamehunterKaan_AutoPWN-Suite/AutoPWN-Suite | /home/hieuvd/dung_repo/raw/stars_03/GamehunterKaan_AutoPWN-Suite/AutoPWN-Suite/modules/getexploits.py | 26,27 | 1,160 | GetExploitInfo | 27,64 | 27,64 | from dataclasses import dataclass
from os import mkdir
from os.path import exists
from time import sleep
from requests import get
from requests.exceptions import ConnectionError
from modules.logger import banner
from modules.random_user_agent import random_user_agent
from modules.utils import get_terminal_width
@da... | from dataclasses import dataclass
from os import mkdir
from os.path import exists
from time import sleep
from requests import get
from requests.exceptions import ConnectionError
from modules.logger import banner
from modules.random_user_agent import random_user_agent
from modules.utils import get_terminal_width
@da... | sleep(0.75)
try:
apidata = get(
f"https://www.exploit-db.com/search?cve={CVEID}",
headers={
"X-Requested-With": "XMLHttpRequest",
"User-Agent": next(random_user_agent(log)),
},
).json()
except ConnectionError:
log.lo... | sleep(0.75)
try:
apidata = get(
f"https://www.exploit-db.com/search?cve={CVEID}",
headers={
"X-Requested-With": "XMLHttpRequest",
"User-Agent": next(random_user_agent(log)),
},
).json()
except ConnectionError:
log.lo... | 73 | 1,334 | 411 | 1,745 | from dataclasses import dataclass
from os import mkdir
from os.path import exists
from time import sleep
from requests import get
from requests.exceptions import ConnectionError
from modules.logger import banner
from modules.random_user_agent import random_user_agent
from modules.utils import get_terminal_width
@da... | from dataclasses import dataclass
from os import mkdir
from os.path import exists
from time import sleep
from requests import get
from requests.exceptions import ConnectionError
from modules.logger import banner
from modules.random_user_agent import random_user_agent
from modules.utils import get_terminal_width
@da... | |
43,224 | /home/hieuvd/dung_repo/raw/stars_03/GamehunterKaan_AutoPWN-Suite/AutoPWN-Suite | /home/hieuvd/dung_repo/raw/stars_03/GamehunterKaan_AutoPWN-Suite/AutoPWN-Suite/modules/logger.py | 9,10 | 1,62 | banner | 10,17 | 10,17 | import logging
from rich.logging import RichHandler
from rich.text import Text
from modules.utils import get_terminal_width
def banner(msg, color, console) -> None:
FILL_FUNC_BODYclass Logger:
"""
Custom logger
"""
def __init__(self, console) -> None:
logging.basicConfig(
format... | import logging
from rich.logging import RichHandler
from rich.text import Text
from modules.utils import get_terminal_width
def banner(msg, color, console) -> None:
FILL_FUNC_BODYclass Logger:
"""
Custom logger
"""
def __init__(self, console) -> None:
logging.basicConfig(
format... | term_width = get_terminal_width()
console.print("─" * term_width, style=color)
console.print(Text(msg), justify="center", style=color)
console.print("─" * term_width, style=color)
| term_width = get_terminal_width()
console.print("─" * term_width, style=color)
console.print(Text(msg), justify="center", style=color)
console.print("─" * term_width, style=color)
| 14 | 403 | 75 | 478 | import logging
from rich.logging import RichHandler
from rich.text import Text
from modules.utils import get_terminal_width
def banner(msg, color, console) -> None:
FILL_FUNC_BODYclass Logger:
"""
Custom logger
"""
def __init__(self, console) -> None:
logging.basicConfig(
format... | import logging
from rich.logging import RichHandler
from rich.text import Text
from modules.utils import get_terminal_width
def banner(msg, color, console) -> None:
FILL_FUNC_BODYclass Logger:
"""
Custom logger
"""
def __init__(self, console) -> None:
logging.basicConfig(
format... | |
43,225 | /home/hieuvd/dung_repo/raw/stars_03/GamehunterKaan_AutoPWN-Suite/AutoPWN-Suite | /home/hieuvd/dung_repo/raw/stars_03/GamehunterKaan_AutoPWN-Suite/AutoPWN-Suite/modules/logger.py | 34,39 | 17,62 | logger | Logger | 53,62 | 39,62 | class Logger:
"""
Custom logger
"""
def __init__(self, console) -> None:
logging.basicConfig(
format="%(message)s",
level=logging.INFO,
datefmt="[%X]",
handlers=[RichHandler(console=console)],
)
RichHandler.KEYWORDS = ["[+]", "[-]... | class Logger:
"""
Custom logger
"""
def __init__(self, console) -> None:
logging.basicConfig(
format="%(message)s",
level=logging.INFO,
datefmt="[%X]",
handlers=[RichHandler(console=console)],
)
RichHandler.KEYWORDS = ["[+]", "[-]... |
if exception_ == "info":
self.log.info(f"[+] {message}")
elif exception_ == "error":
self.log.error(f"[-] {message}")
elif exception_ == "warning":
self.log.warning(f"[*] {message}")
elif exception_ == "success":
self.log.info(f"[+] {messa... | """
* Log the proccesses with the passed message depending on the
* exception_ variable
@args
exception_: str, determines what type of log level to use
(1.) info
(2.) error
(3.) warning
(4.) success
... | 24 | 251 | 113 | 364 | import logging
from rich.logging import RichHandler
from rich.text import Text
from modules.utils import get_terminal_width
def banner(msg, color, console) -> None:
term_width = get_terminal_width()
console.print("─" * term_width, style=color)
console.print(Text(msg), justify="center", style=color)
... | import logging
from rich.logging import RichHandler
from rich.text import Text
from modules.utils import get_terminal_width
def banner(msg, color, console) -> None:
term_width = get_terminal_width()
console.print("─" * term_width, style=color)
console.print(Text(msg), justify="center", style=color)
... |
43,226 | /home/hieuvd/dung_repo/raw/stars_03/GamehunterKaan_AutoPWN-Suite/AutoPWN-Suite | /home/hieuvd/dung_repo/raw/stars_03/GamehunterKaan_AutoPWN-Suite/AutoPWN-Suite/modules/nist_search.py | 31,32 | 1,115 | FindVars | 32,57 | 32,57 | from dataclasses import dataclass
from time import sleep
from requests import get
cache = {}
@dataclass
class Vulnerability:
title: str
CVEID: str
description: str
severity: str
severity_score: float
details_url: str
exploitability: float
def __str__(self) -> str:
return (
... | from dataclasses import dataclass
from time import sleep
from requests import get
cache = {}
@dataclass
class Vulnerability:
title: str
CVEID: str
description: str
severity: str
severity_score: float
details_url: str
exploitability: float
def __str__(self) -> str:
return (
... | CVE_ID = vuln["cve"]["id"]
description = vuln["cve"]["descriptions"][0]["value"]
exploitability = 0.0
severity_score = 0.0
severity = "UNKNOWN"
metrics = vuln["cve"].get("metrics")
if metrics is not None and len(metrics) > 0:
# In testing this appears to contain cvssMetricV31 and cv... | CVE_ID = vuln["cve"]["id"]
description = vuln["cve"]["descriptions"][0]["value"]
exploitability = 0.0
severity_score = 0.0
severity = "UNKNOWN"
metrics = vuln["cve"].get("metrics")
if metrics is not None and len(metrics) > 0:
# In testing this appears to contain cvssMetricV31 and cv... | 101 | 733 | 389 | 1,122 | from dataclasses import dataclass
from time import sleep
from requests import get
cache = {}
@dataclass
class Vulnerability:
title: str
CVEID: str
description: str
severity: str
severity_score: float
details_url: str
exploitability: float
def __str__(self) -> str:
return (
... | from dataclasses import dataclass
from time import sleep
from requests import get
cache = {}
@dataclass
class Vulnerability:
title: str
CVEID: str
description: str
severity: str
severity_score: float
details_url: str
exploitability: float
def __str__(self) -> str:
return (
... | |
43,227 | /home/hieuvd/dung_repo/raw/stars_03/GamehunterKaan_AutoPWN-Suite/AutoPWN-Suite | /home/hieuvd/dung_repo/raw/stars_03/GamehunterKaan_AutoPWN-Suite/AutoPWN-Suite/modules/random_user_agent.py | 6,7 | 1,36 | random_user_agent | 12,36 | 7,36 | from json import loads
from os.path import dirname
from random import choice, randint
def random_user_agent(log) -> str:
FILL_FUNC_BODY | from json import loads
from os.path import dirname
from random import choice, randint
def random_user_agent(log) -> str:
"""
* Generate random user agent for headers.
? Returns the randomly generated user agent
"""
FILL_FUNC_BODY |
def fetch_data() -> list[str]:
base_dir: str = dirname(__file__)
user_agents: list[str] = []
try:
with open(
f"{base_dir}/data/user_agents.json", "r", encoding="utf-8"
) as data:
for user_agent_ in data:
user_agen... | """
* Generate random user agent for headers.
? Returns the randomly generated user agent
"""
def fetch_data() -> list[str]:
base_dir: str = dirname(__file__)
user_agents: list[str] = []
try:
with open(
f"{base_dir}/data/user_agents.json", "r",... | 60 | 75 | 250 | 325 | from json import loads
from os.path import dirname
from random import choice, randint
def random_user_agent(log) -> str:
FILL_FUNC_BODY | from json import loads
from os.path import dirname
from random import choice, randint
def random_user_agent(log) -> str:
"""
* Generate random user agent for headers.
? Returns the randomly generated user agent
"""
FILL_FUNC_BODY | |
43,228 | /home/hieuvd/dung_repo/raw/stars_03/GamehunterKaan_AutoPWN-Suite/AutoPWN-Suite | /home/hieuvd/dung_repo/raw/stars_03/GamehunterKaan_AutoPWN-Suite/AutoPWN-Suite/modules/report.py | 94,95 | 1,122 | SendWebhook | 98,114 | 95,114 | from dataclasses import dataclass
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from enum import Enum
from os import remove
from smtplib import SMTP
from requests import post
class ReportType(Enum):
"""
Enum for report types.
"""
NONE = 0
EMAIL = 1
WEBHO... | from dataclasses import dataclass
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from enum import Enum
from os import remove
from smtplib import SMTP
from requests import post
class ReportType(Enum):
"""
Enum for report types.
"""
NONE = 0
EMAIL = 1
WEBHO... | file = open("report.log", "r", encoding="utf-8")
payload = {"payload": file}
try:
req = post(url, files=payload)
file.close()
if req.status_code == 200:
log.logger("success", "Webhook report sent succesfully.")
else:
log.logger("error", "Webhook repor... | """
Send webhook report.
"""
file = open("report.log", "r", encoding="utf-8")
payload = {"payload": file}
try:
req = post(url, files=payload)
file.close()
if req.status_code == 200:
log.logger("success", "Webhook report sent succesfully.")
else:
... | 44 | 798 | 163 | 961 | from dataclasses import dataclass
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from enum import Enum
from os import remove
from smtplib import SMTP
from requests import post
class ReportType(Enum):
"""
Enum for report types.
"""
NONE = 0
EMAIL = 1
WEBHO... | from dataclasses import dataclass
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from enum import Enum
from os import remove
from smtplib import SMTP
from requests import post
class ReportType(Enum):
"""
Enum for report types.
"""
NONE = 0
EMAIL = 1
WEBHO... | |
43,230 | /home/hieuvd/dung_repo/raw/stars_03/GamehunterKaan_AutoPWN-Suite/AutoPWN-Suite | /home/hieuvd/dung_repo/raw/stars_03/GamehunterKaan_AutoPWN-Suite/AutoPWN-Suite/modules/scanner.py | 22,23 | 14,44 | colored | TargetInfo | 23,32 | 23,32 | @dataclass()
class TargetInfo:
mac: str = "Unknown"
vendor: str = "Unknown"
os: str = "Unknown"
os_accuracy: int = 0
os_type: str = "Unknown"
def colored(self) -> str:
FILL_FUNC_BODY def __str__(self) -> str:
return (
f"MAC Address : {self.mac}"
+ f" Vendor : ... | @dataclass()
class TargetInfo:
mac: str = "Unknown"
vendor: str = "Unknown"
os: str = "Unknown"
os_accuracy: int = 0
os_type: str = "Unknown"
def colored(self) -> str:
FILL_FUNC_BODY def __str__(self) -> str:
return (
f"MAC Address : {self.mac}"
+ f" Vendor : ... |
return (
f"[yellow]MAC Address :[/yellow] {self.mac}\n"
+ f"[yellow]Vendor :[/yellow] {self.vendor}\n"
+ f"[yellow]OS :[/yellow] {self.os}\n"
+ f"[yellow]Accuracy :[/yellow] {self.os_accuracy}\n"
+ f"[yellow]Type :[/yellow] {self.os_type[:20]}\n"
... |
return (
f"[yellow]MAC Address :[/yellow] {self.mac}\n"
+ f"[yellow]Vendor :[/yellow] {self.vendor}\n"
+ f"[yellow]OS :[/yellow] {self.os}\n"
+ f"[yellow]Accuracy :[/yellow] {self.os_accuracy}\n"
+ f"[yellow]Type :[/yellow] {self.os_type[:20]}\n"
... | 23 | 187 | 130 | 317 | from dataclasses import dataclass
from enum import Enum
from multiprocessing import Process
from time import sleep
from nmap import PortScanner
from rich import box
from rich.table import Table
from modules.logger import banner
from modules.utils import GetIpAdress, ScanMode, ScanType, is_root
@dataclass()
class Ta... | from dataclasses import dataclass
from enum import Enum
from multiprocessing import Process
from time import sleep
from nmap import PortScanner
from rich import box
from rich.table import Table
from modules.logger import banner
from modules.utils import GetIpAdress, ScanMode, ScanType, is_root
@dataclass()
class Ta... |
43,231 | /home/hieuvd/dung_repo/raw/stars_03/GamehunterKaan_AutoPWN-Suite/AutoPWN-Suite | /home/hieuvd/dung_repo/raw/stars_03/GamehunterKaan_AutoPWN-Suite/AutoPWN-Suite/modules/searchvuln.py | 73,74 | 1,132 | SearchSploits | 74,132 | 74,132 | from dataclasses import dataclass
from textwrap import wrap
from modules.logger import banner
from modules.nist_search import searchCVE
from modules.utils import CheckConnection, get_terminal_width
from rich.progress_bar import ProgressBar
@dataclass
class VulnerableSoftware:
title: str
CVEs: list
def Gene... | from dataclasses import dataclass
from textwrap import wrap
from modules.logger import banner
from modules.nist_search import searchCVE
from modules.utils import CheckConnection, get_terminal_width
from rich.progress_bar import ProgressBar
@dataclass
class VulnerableSoftware:
title: str
CVEs: list
def Gene... | VulnsArray = []
target = str(HostArray[0][0])
term_width = get_terminal_width()
if not CheckConnection(log):
return []
keywords = GenerateKeywords(HostArray)
if len(keywords) == 0:
log.logger("warning", f"Insufficient information for {target}")
return []
log.logge... | VulnsArray = []
target = str(HostArray[0][0])
term_width = get_terminal_width()
if not CheckConnection(log):
return []
keywords = GenerateKeywords(HostArray)
if len(keywords) == 0:
log.logger("warning", f"Insufficient information for {target}")
return []
log.logge... | 143 | 523 | 714 | 1,237 | from dataclasses import dataclass
from textwrap import wrap
from modules.logger import banner
from modules.nist_search import searchCVE
from modules.utils import CheckConnection, get_terminal_width
from rich.progress_bar import ProgressBar
@dataclass
class VulnerableSoftware:
title: str
CVEs: list
def Gene... | from dataclasses import dataclass
from textwrap import wrap
from modules.logger import banner
from modules.nist_search import searchCVE
from modules.utils import CheckConnection, get_terminal_width
from rich.progress_bar import ProgressBar
@dataclass
class VulnerableSoftware:
title: str
CVEs: list
def Gene... | |
43,232 | /home/hieuvd/dung_repo/raw/stars_03/GantMan_nsfw_model/nsfw_model | /home/hieuvd/dung_repo/raw/stars_03/GantMan_nsfw_model/nsfw_model/setup.py | 81,82 | 64,102 | run | UploadCommand | 82,102 | 82,102 | class UploadCommand(Command):
"""Support setup.py upload."""
description = 'Build and publish the package.'
user_options = []
@staticmethod
def status(s):
"""Prints things in bold."""
print('\033[1m{0}\033[0m'.format(s))
def initialize_options(self):
pass
def fina... | class UploadCommand(Command):
"""Support setup.py upload."""
description = 'Build and publish the package.'
user_options = []
@staticmethod
def status(s):
"""Prints things in bold."""
print('\033[1m{0}\033[0m'.format(s))
def initialize_options(self):
pass
def fina... | try:
self.status('Removing previous builds…')
rmtree(os.path.join(here, 'dist'))
except OSError:
pass
self.status('Building Source and Wheel (universal) distribution…')
os.system('{0} setup.py sdist bdist_wheel --universal'.format(sys.executable))
... | try:
self.status('Removing previous builds…')
rmtree(os.path.join(here, 'dist'))
except OSError:
pass
self.status('Building Source and Wheel (universal) distribution…')
os.system('{0} setup.py sdist bdist_wheel --universal'.format(sys.executable))
... | 45 | 128 | 204 | 332 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Note: To use the 'upload' functionality of this file, you must:
# $ pip install twine
import io
import os
import sys
from shutil import rmtree
from setuptools import find_packages, setup, Command
# Package meta-data.
NAME = 'nsfw_detector'
DESCRIPTION = 'NSFW Image ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Note: To use the 'upload' functionality of this file, you must:
# $ pip install twine
import io
import os
import sys
from shutil import rmtree
from setuptools import find_packages, setup, Command
# Package meta-data.
NAME = 'nsfw_detector'
DESCRIPTION = 'NSFW Image ... |
43,233 | /home/hieuvd/dung_repo/raw/stars_03/GantMan_nsfw_model/nsfw_model | /home/hieuvd/dung_repo/raw/stars_03/GantMan_nsfw_model/nsfw_model/tf1/nsfw_detector/keras_predict.py | 5,6 | 1,98 | load_images | 17,32 | 6,32 | import keras
import numpy as np
def load_images(image_paths, image_size):
FILL_FUNC_BODYclass keras_predictor():
'''
Class for loading model and running predictions.
For example on how to use take a look the if __name__ == '__main__' part.
'''
nsfw_model = None
def __init__(self, mode... | import keras
import numpy as np
def load_images(image_paths, image_size):
'''
Function for loading images into numpy arrays for passing to model.predict
inputs:
image_paths: list of image paths to load
image_size: size into which images should be resized
outputs:
loaded_im... | loaded_images = []
loaded_image_paths = []
for i, img_path in enumerate(image_paths):
try:
image = keras.preprocessing.image.load_img(img_path, target_size = image_size)
image = keras.preprocessing.image.img_to_array(image)
image /= 255
loaded_images.... | '''
Function for loading images into numpy arrays for passing to model.predict
inputs:
image_paths: list of image paths to load
image_size: size into which images should be resized
outputs:
loaded_images: loaded images on which keras model can run predictions
loaded_... | 36 | 874 | 171 | 1,045 | import keras
import numpy as np
def load_images(image_paths, image_size):
FILL_FUNC_BODYclass keras_predictor():
'''
Class for loading model and running predictions.
For example on how to use take a look the if __name__ == '__main__' part.
'''
nsfw_model = None
def __init__(self, mode... | import keras
import numpy as np
def load_images(image_paths, image_size):
'''
Function for loading images into numpy arrays for passing to model.predict
inputs:
image_paths: list of image paths to load
image_size: size into which images should be resized
outputs:
loaded_im... | |
43,234 | /home/hieuvd/dung_repo/raw/stars_03/GantMan_nsfw_model/nsfw_model | /home/hieuvd/dung_repo/raw/stars_03/GantMan_nsfw_model/nsfw_model/tf1/nsfw_detector/keras_predict.py | 46,47 | 32,86 | predict | keras_predictor | 54,86 | 47,86 | class keras_predictor():
'''
Class for loading model and running predictions.
For example on how to use take a look the if __name__ == '__main__' part.
'''
nsfw_model = None
def __init__(self, model_path):
'''
model = keras_predictor('path_to_weights')
'''
... | class keras_predictor():
'''
Class for loading model and running predictions.
For example on how to use take a look the if __name__ == '__main__' part.
'''
nsfw_model = None
def __init__(self, model_path):
'''
model = keras_predictor('path_to_weights')
'''
... | if isinstance(image_paths, str):
image_paths = [image_paths]
loaded_images, loaded_image_paths = load_images(image_paths, image_size)
if not loaded_image_paths:
return {}
model_preds = keras_predictor.nsfw_model.predict(loaded_images, batch_size = batch... | '''
inputs:
image_paths: list of image paths or can be a string too (for single image)
batch_size: batch_size for running predictions
image_size: size to which the image needs to be resized
categories: since the model predicts numbers, ... | 69 | 267 | 346 | 613 | import keras
import numpy as np
def load_images(image_paths, image_size):
'''
Function for loading images into numpy arrays for passing to model.predict
inputs:
image_paths: list of image paths to load
image_size: size into which images should be resized
outputs:
loaded_im... | import keras
import numpy as np
def load_images(image_paths, image_size):
'''
Function for loading images into numpy arrays for passing to model.predict
inputs:
image_paths: list of image paths to load
image_size: size into which images should be resized
outputs:
loaded_im... |
43,265 | /home/hieuvd/dung_repo/raw/stars_03/Jefferson-Henrique_GetOldTweets-python/GetOldTweets-python | /home/hieuvd/dung_repo/raw/stars_03/Jefferson-Henrique_GetOldTweets-python/GetOldTweets-python/Main.py | 7,8 | 1,37 | main | 8,35 | 8,35 | import sys
if sys.version_info[0] < 3:
import got
else:
import got3 as got
def main():
FILL_FUNC_BODYif __name__ == '__main__':
main()
| import sys
if sys.version_info[0] < 3:
import got
else:
import got3 as got
def main():
FILL_FUNC_BODYif __name__ == '__main__':
main()
|
def printTweet(descr, t):
print(descr)
print("Username: %s" % t.username)
print("Retweets: %d" % t.retweets)
print("Text: %s" % t.text)
print("Mentions: %s" % t.mentions)
print("Hashtags: %s\n" % t.hashtags)
# Example 1 - Get tweets by username
tweetCriteria = got.manager.TweetCriteria().setUsername('b... |
def printTweet(descr, t):
print(descr)
print("Username: %s" % t.username)
print("Retweets: %d" % t.retweets)
print("Text: %s" % t.text)
print("Mentions: %s" % t.mentions)
print("Hashtags: %s\n" % t.hashtags)
# Example 1 - Get tweets by username
tweetCriteria = got.manager.TweetCriteria().setUsername('b... | 108 | 60 | 508 | 568 | import sys
if sys.version_info[0] < 3:
import got
else:
import got3 as got
def main():
FILL_FUNC_BODYif __name__ == '__main__':
main()
| import sys
if sys.version_info[0] < 3:
import got
else:
import got3 as got
def main():
FILL_FUNC_BODYif __name__ == '__main__':
main()
| |
43,266 | /home/hieuvd/dung_repo/raw/stars_03/Jefferson-Henrique_GetOldTweets-python/GetOldTweets-python | /home/hieuvd/dung_repo/raw/stars_03/Jefferson-Henrique_GetOldTweets-python/GetOldTweets-python/got/manager/TweetCriteria.py | 7,8 | 1,38 | setUsername | TweetCriteria | 8,11 | 8,11 | class TweetCriteria:
def __init__(self):
self.maxTweets = 0
self.within = "15mi"
def setUsername(self, username):
FILL_FUNC_BODY def setSince(self, since):
self.since = since
return self
def setUntil(self, until):
self.until = until
return self
def setQuerySearch(self, querySearch):
self.que... | class TweetCriteria:
def __init__(self):
self.maxTweets = 0
self.within = "15mi"
def setUsername(self, username):
FILL_FUNC_BODY def setSince(self, since):
self.since = since
return self
def setUntil(self, until):
self.until = until
return self
def setQuerySearch(self, querySearch):
self.que... | self.username = username
return self
| self.username = username
return self
| 5 | 257 | 17 | 274 | class TweetCriteria:
def __init__(self):
self.maxTweets = 0
self.within = "15mi"
def setUsername(self, username):
FILL_FUNC_BODY def setSince(self, since):
self.since = since
return self
def setUntil(self, until):
self.until = until
return self
def setQuerySearch(self, querySearch):
self.que... | class TweetCriteria:
def __init__(self):
self.maxTweets = 0
self.within = "15mi"
def setUsername(self, username):
FILL_FUNC_BODY def setSince(self, since):
self.since = since
return self
def setUntil(self, until):
self.until = until
return self
def setQuerySearch(self, querySearch):
self.que... |
43,267 | /home/hieuvd/dung_repo/raw/stars_03/Jefferson-Henrique_GetOldTweets-python/GetOldTweets-python | /home/hieuvd/dung_repo/raw/stars_03/Jefferson-Henrique_GetOldTweets-python/GetOldTweets-python/got3/manager/TweetCriteria.py | 26,27 | 1,33 | setLang | TweetCriteria | 27,30 | 27,30 | class TweetCriteria:
def __init__(self):
self.maxTweets = 0
def setUsername(self, username):
self.username = username
return self
def setSince(self, since):
self.since = since
return self
def setUntil(self, until):
self.until = until
return self
def setQuerySearch(self, querySearch):
self.quer... | class TweetCriteria:
def __init__(self):
self.maxTweets = 0
def setUsername(self, username):
self.username = username
return self
def setSince(self, since):
self.since = since
return self
def setUntil(self, until):
self.until = until
return self
def setQuerySearch(self, querySearch):
self.quer... | self.lang = Lang
return self
| self.lang = Lang
return self
| 5 | 214 | 16 | 230 | class TweetCriteria:
def __init__(self):
self.maxTweets = 0
def setUsername(self, username):
self.username = username
return self
def setSince(self, since):
self.since = since
return self
def setUntil(self, until):
self.until = until
return self
def setQuerySearch(self, querySearch):
self.quer... | class TweetCriteria:
def __init__(self):
self.maxTweets = 0
def setUsername(self, username):
self.username = username
return self
def setSince(self, since):
self.since = since
return self
def setUntil(self, until):
self.until = until
return self
def setQuerySearch(self, querySearch):
self.quer... |
43,268 | /home/hieuvd/dung_repo/raw/stars_03/KalleHallden_ProjectInitializationAutomation/ProjectInitializationAutomation | /home/hieuvd/dung_repo/raw/stars_03/KalleHallden_ProjectInitializationAutomation/ProjectInitializationAutomation/create.py | 12,13 | 1,22 | create | 13,20 | 13,20 | import sys
import os
from github import Github
from dotenv import load_dotenv
load_dotenv()
path = os.getenv("FILEPATH")
username = os.getenv("USERNAME")
password = os.getenv("PASSWORD")
def create():
FILL_FUNC_BODYif __name__ == "__main__":
create()
| import sys
import os
from github import Github
from dotenv import load_dotenv
load_dotenv()
path = os.getenv("FILEPATH")
username = os.getenv("USERNAME")
password = os.getenv("PASSWORD")
def create():
FILL_FUNC_BODYif __name__ == "__main__":
create()
| folderName = str(sys.argv[1])
os.makedirs(path + str(folderName))
user = Github(username, password).get_user()
repo = user.create_repo(folderName)
# f strings
print(f"Succesfully created repository {folderName}")
| folderName = str(sys.argv[1])
os.makedirs(path + str(folderName))
user = Github(username, password).get_user()
repo = user.create_repo(folderName)
# f strings
print(f"Succesfully created repository {folderName}")
| 20 | 93 | 88 | 181 | import sys
import os
from github import Github
from dotenv import load_dotenv
load_dotenv()
path = os.getenv("FILEPATH")
username = os.getenv("USERNAME")
password = os.getenv("PASSWORD")
def create():
FILL_FUNC_BODYif __name__ == "__main__":
create()
| import sys
import os
from github import Github
from dotenv import load_dotenv
load_dotenv()
path = os.getenv("FILEPATH")
username = os.getenv("USERNAME")
password = os.getenv("PASSWORD")
def create():
FILL_FUNC_BODYif __name__ == "__main__":
create()
| |
43,271 | /home/hieuvd/dung_repo/raw/stars_03/Lyken17_Efficient-PyTorch/Efficient-PyTorch | /home/hieuvd/dung_repo/raw/stars_03/Lyken17_Efficient-PyTorch/Efficient-PyTorch/main.py | 307,308 | 296,314 | update | AverageMeter | 308,314 | 308,314 | class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
FILL_FUNC_BODY | class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
FILL_FUNC_BODY | self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
| self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
| 16 | 97 | 45 | 142 | import argparse
import os
import random
import shutil
import time
import warnings
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
import torchvision.transform... | import argparse
import os
import random
import shutil
import time
import warnings
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
import torchvision.transform... |
43,273 | /home/hieuvd/dung_repo/raw/stars_03/Margular_frida-skeleton/frida-skeleton | /home/hieuvd/dung_repo/raw/stars_03/Margular_frida-skeleton/frida-skeleton/frida-skeleton.py | 31,32 | 26,84 | start | FridaSkeleton | 32,73 | 32,73 | class FridaSkeleton:
def __init__(self):
self.log = logging.getLogger(self.__class__.__name__)
def start(self):
FILL_FUNC_BODY def shutdown(self, signum, frame):
if signum == signal.SIGINT:
self.log.debug('keyboard interrupt event detected')
elif signum == signal.SIGTERM... | class FridaSkeleton:
def __init__(self):
self.log = logging.getLogger(self.__class__.__name__)
def start(self):
FILL_FUNC_BODY def shutdown(self, signum, frame):
if signum == signal.SIGINT:
self.log.debug('keyboard interrupt event detected')
elif signum == signal.SIGTERM... | try:
if options.list:
for device in Adb.devices().out.split('\n')[1:]:
print(device)
sys.exit(0)
level = logging.DEBUG if options.verbose else logging.INFO
coloredlogs.install(level=level)
# set log
... | try:
if options.list:
for device in Adb.devices().out.split('\n')[1:]:
print(device)
sys.exit(0)
level = logging.DEBUG if options.verbose else logging.INFO
coloredlogs.install(level=level)
# set log
... | 79 | 141 | 400 | 541 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import os
import signal
import sys
import time
import coloredlogs
import urllib3
from lib.core.options import options
from lib.core.settings import LOG_DIR, LOG_FILENAME
from lib.core.watch_thread import WatchThread
from lib.utils.adb import Adb
# disable... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import os
import signal
import sys
import time
import coloredlogs
import urllib3
from lib.core.options import options
from lib.core.settings import LOG_DIR, LOG_FILENAME
from lib.core.watch_thread import WatchThread
from lib.utils.adb import Adb
# disable... |
43,275 | /home/hieuvd/dung_repo/raw/stars_03/Margular_frida-skeleton/frida-skeleton | /home/hieuvd/dung_repo/raw/stars_03/Margular_frida-skeleton/frida-skeleton/lib/core/port_manager.py | 22,23 | 10,39 | acquire_port | PortManager | 23,33 | 23,33 | class PortManager:
def __init__(self):
self.port_map = {}
@classmethod
def secure_rand_port(cls):
while True:
port = secrets.randbits(16)
if port < 1024:
continue
return port
def acquire_port(self, excludes=None):
FILL_FUNC_BODY de... | class PortManager:
def __init__(self):
self.port_map = {}
@classmethod
def secure_rand_port(cls):
while True:
port = secrets.randbits(16)
if port < 1024:
continue
return port
def acquire_port(self, excludes=None):
FILL_FUNC_BODY de... | with __lock__:
while True:
port = PortManager.secure_rand_port()
if port in self.port_map.keys() or port in excludes:
continue
self.port_map[port] = True
return port
| with __lock__:
while True:
port = PortManager.secure_rand_port()
if port in self.port_map.keys() or port in excludes:
continue
self.port_map[port] = True
return port
| 21 | 143 | 76 | 219 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import secrets
import threading
__lock__ = threading.Lock()
class PortManager:
def __init__(self):
self.port_map = {}
@classmethod
def secure_rand_port(cls):
while True:
port = secrets.randbits(16)
if port < 1024:
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import secrets
import threading
__lock__ = threading.Lock()
class PortManager:
def __init__(self):
self.port_map = {}
@classmethod
def secure_rand_port(cls):
while True:
port = secrets.randbits(16)
if port < 1024:
... |
43,276 | /home/hieuvd/dung_repo/raw/stars_03/Margular_frida-skeleton/frida-skeleton | /home/hieuvd/dung_repo/raw/stars_03/Margular_frida-skeleton/frida-skeleton/lib/core/project.py | 66,67 | 15,80 | load | Project | 67,80 | 67,80 | class Project:
def __init__(self, path: str, enable:bool, name: str, regexp: str, spawn: bool, priority: int):
self.log = logging.getLogger(self.__class__.__name__ + '|' + name)
self.path = path
self.enable = enable
self.name = name
self.regexp = regexp
self.spawn =... | class Project:
def __init__(self, path: str, enable:bool, name: str, regexp: str, spawn: bool, priority: int):
self.log = logging.getLogger(self.__class__.__name__ + '|' + name)
self.path = path
self.enable = enable
self.name = name
self.regexp = regexp
self.spawn =... | self.log.debug('loading script for {}...'.format(app))
js = ''
# recursively load js files
for (dirpath, dirnames, filenames) in os.walk(self.path):
for filename in filenames:
if os.path.splitext(filename)[1] != '.js':
continue
... | self.log.debug('loading script for {}...'.format(app))
js = ''
# recursively load js files
for (dirpath, dirnames, filenames) in os.walk(self.path):
for filename in filenames:
if os.path.splitext(filename)[1] != '.js':
continue
... | 36 | 545 | 137 | 682 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import os
import threading
import yaml
from lib.core.settings import ROOT_DIR, PROJECT_CONFIG_FILENAME
from thirdparty.attrdict import AttrDict
__lock__ = threading.Lock()
class Project:
def __init__(self, path: str, enable:bool, name: str, regexp: ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import os
import threading
import yaml
from lib.core.settings import ROOT_DIR, PROJECT_CONFIG_FILENAME
from thirdparty.attrdict import AttrDict
__lock__ = threading.Lock()
class Project:
def __init__(self, path: str, enable:bool, name: str, regexp: ... |
43,277 | /home/hieuvd/dung_repo/raw/stars_03/Margular_frida-skeleton/frida-skeleton | /home/hieuvd/dung_repo/raw/stars_03/Margular_frida-skeleton/frida-skeleton/lib/utils/adb.py | 48,49 | 7,50 | clear_forward | Adb | 49,50 | 49,50 | class Adb(Shell):
def __init__(self, serial):
super().__init__()
self.serial = serial
# if we are root shell
self.is_root = False
self.check_root()
@classmethod
def start_server(cls):
return Shell().exec('adb start-server', supress_error=True)
@classmet... | class Adb(Shell):
def __init__(self, serial):
super().__init__()
self.serial = serial
# if we are root shell
self.is_root = False
self.check_root()
@classmethod
def start_server(cls):
return Shell().exec('adb start-server', supress_error=True)
@classmet... | return self.exec('adb -s "{}" forward --remove tcp:{}'.format(self.serial, local_port))
| return self.exec('adb -s "{}" forward --remove tcp:{}'.format(self.serial, local_port))
| 8 | 486 | 33 | 519 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from lib.utils.shell import Shell
class Adb(Shell):
def __init__(self, serial):
super().__init__()
self.serial = serial
# if we are root shell
self.is_root = False
self.check_root()
@classmethod
def start_server(cls):... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from lib.utils.shell import Shell
class Adb(Shell):
def __init__(self, serial):
super().__init__()
self.serial = serial
# if we are root shell
self.is_root = False
self.check_root()
@classmethod
def start_server(cls):... |
43,278 | /home/hieuvd/dung_repo/raw/stars_03/Margular_frida-skeleton/frida-skeleton | /home/hieuvd/dung_repo/raw/stars_03/Margular_frida-skeleton/frida-skeleton/lib/utils/iptables.py | 15,16 | 5,22 | uninstall | Iptables | 16,19 | 16,19 | class Iptables:
def __init__(self, adb, port):
self.adb = adb
self.port = port
self.install_cmd = 'iptables -t nat -A OUTPUT -p tcp -o lo -j RETURN'
self.install_cmd2 = 'iptables -t nat -A OUTPUT -p tcp -j DNAT --to-destination 127.0.0.1:{}'.format(port)
self.uninstall_cmd =... | class Iptables:
def __init__(self, adb, port):
self.adb = adb
self.port = port
self.install_cmd = 'iptables -t nat -A OUTPUT -p tcp -o lo -j RETURN'
self.install_cmd2 = 'iptables -t nat -A OUTPUT -p tcp -j DNAT --to-destination 127.0.0.1:{}'.format(port)
self.uninstall_cmd =... | self.adb.unsafe_shell(self.uninstall_cmd, root=True)
self.adb.unsafe_shell(self.uninstall_cmd2, root=True)
| self.adb.unsafe_shell(self.uninstall_cmd, root=True)
self.adb.unsafe_shell(self.uninstall_cmd2, root=True)
| 4 | 270 | 51 | 321 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class Iptables:
def __init__(self, adb, port):
self.adb = adb
self.port = port
self.install_cmd = 'iptables -t nat -A OUTPUT -p tcp -o lo -j RETURN'
self.install_cmd2 = 'iptables -t nat -A OUTPUT -p tcp -j DNAT --to-destination 127.0.0... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class Iptables:
def __init__(self, adb, port):
self.adb = adb
self.port = port
self.install_cmd = 'iptables -t nat -A OUTPUT -p tcp -o lo -j RETURN'
self.install_cmd2 = 'iptables -t nat -A OUTPUT -p tcp -j DNAT --to-destination 127.0.0... |
43,279 | /home/hieuvd/dung_repo/raw/stars_03/Margular_frida-skeleton/frida-skeleton | /home/hieuvd/dung_repo/raw/stars_03/Margular_frida-skeleton/frida-skeleton/lib/utils/shell.py | 14,15 | 10,37 | exec | Shell | 15,37 | 15,37 | class Shell:
def __init__(self):
self.log = logging.getLogger(self.__class__.__name__)
def exec(self, cmd: str, quiet=False, supress_error=False) -> AttrDict:
FILL_FUNC_BODY | class Shell:
def __init__(self):
self.log = logging.getLogger(self.__class__.__name__)
def exec(self, cmd: str, quiet=False, supress_error=False) -> AttrDict:
FILL_FUNC_BODY | ret = AttrDict()
if not quiet:
self.log.debug(cmd)
p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE, close_fds=True)
# output processing
out = p.stdout.read().decode().strip()
ret.out = out
err = p.stderr.read().decode().strip()
ret.err =... | ret = AttrDict()
if not quiet:
self.log.debug(cmd)
p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE, close_fds=True)
# output processing
out = p.stdout.read().decode().strip()
ret.out = out
err = p.stderr.read().decode().strip()
ret.err =... | 57 | 70 | 199 | 269 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
from subprocess import Popen, PIPE
from thirdparty.attrdict import AttrDict
class Shell:
def __init__(self):
self.log = logging.getLogger(self.__class__.__name__)
def exec(self, cmd: str, quiet=False, supress_error=False) -> AttrDict:
FIL... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
from subprocess import Popen, PIPE
from thirdparty.attrdict import AttrDict
class Shell:
def __init__(self):
self.log = logging.getLogger(self.__class__.__name__)
def exec(self, cmd: str, quiet=False, supress_error=False) -> AttrDict:
FIL... |
43,280 | /home/hieuvd/dung_repo/raw/stars_03/Margular_frida-skeleton/frida-skeleton | /home/hieuvd/dung_repo/raw/stars_03/Margular_frida-skeleton/frida-skeleton/thirdparty/attrdict/default.py | 126,128 | 17,134 | _constructor | AttrDefault | 131,134 | 128,134 | class AttrDefault(MutableAttr):
"""
An implementation of MutableAttr with defaultdict support
"""
def __init__(self, default_factory=None, items=None, sequence_type=tuple,
pass_key=False):
if items is None:
items = {}
elif not isinstance(items, Mapping):
... | class AttrDefault(MutableAttr):
"""
An implementation of MutableAttr with defaultdict support
"""
def __init__(self, default_factory=None, items=None, sequence_type=tuple,
pass_key=False):
if items is None:
items = {}
elif not isinstance(items, Mapping):
... | sequence_type, default_factory, pass_key = configuration
return cls(default_factory, mapping, sequence_type=sequence_type,
pass_key=pass_key)
| """
A standardized constructor.
"""
sequence_type, default_factory, pass_key = configuration
return cls(default_factory, mapping, sequence_type=sequence_type,
pass_key=pass_key)
| 10 | 876 | 48 | 924 | """
A subclass of MutableAttr that has defaultdict support.
"""
try:
from collections import Mapping
except ImportError:
from collections.abc import Mapping
import six
from .mixins import MutableAttr
__all__ = ['AttrDefault']
class AttrDefault(MutableAttr):
"""
An implementation of MutableAttr wit... | """
A subclass of MutableAttr that has defaultdict support.
"""
try:
from collections import Mapping
except ImportError:
from collections.abc import Mapping
import six
from .mixins import MutableAttr
__all__ = ['AttrDefault']
class AttrDefault(MutableAttr):
"""
An implementation of MutableAttr wit... |
43,281 | /home/hieuvd/dung_repo/raw/stars_03/Margular_frida-skeleton/frida-skeleton | /home/hieuvd/dung_repo/raw/stars_03/Margular_frida-skeleton/frida-skeleton/thirdparty/attrdict/dictionary.py | 52,54 | 12,61 | _constructor | AttrDict | 57,61 | 54,61 | class AttrDict(dict, MutableAttr):
"""
A dict that implements MutableAttr.
"""
def __init__(self, *args, **kwargs):
super(AttrDict, self).__init__(*args, **kwargs)
self._setattr('_sequence_type', tuple)
self._setattr('_allow_invalid_attributes', False)
def _configuration(se... | class AttrDict(dict, MutableAttr):
"""
A dict that implements MutableAttr.
"""
def __init__(self, *args, **kwargs):
super(AttrDict, self).__init__(*args, **kwargs)
self._setattr('_sequence_type', tuple)
self._setattr('_allow_invalid_attributes', False)
def _configuration(se... | attr = cls(mapping)
attr._setattr('_sequence_type', configuration)
return attr
| """
A standardized constructor.
"""
attr = cls(mapping)
attr._setattr('_sequence_type', configuration)
return attr
| 7 | 351 | 32 | 383 | """
A dict that implements MutableAttr.
"""
from .mixins import MutableAttr
import six
__all__ = ['AttrDict']
class AttrDict(dict, MutableAttr):
"""
A dict that implements MutableAttr.
"""
def __init__(self, *args, **kwargs):
super(AttrDict, self).__init__(*args, **kwargs)
self._se... | """
A dict that implements MutableAttr.
"""
from .mixins import MutableAttr
import six
__all__ = ['AttrDict']
class AttrDict(dict, MutableAttr):
"""
A dict that implements MutableAttr.
"""
def __init__(self, *args, **kwargs):
super(AttrDict, self).__init__(*args, **kwargs)
self._se... |
43,282 | /home/hieuvd/dung_repo/raw/stars_03/Margular_frida-skeleton/frida-skeleton | /home/hieuvd/dung_repo/raw/stars_03/Margular_frida-skeleton/frida-skeleton/thirdparty/attrdict/mapping.py | 95,97 | 17,101 | _constructor | AttrMap | 100,101 | 97,101 | class AttrMap(MutableAttr):
"""
An implementation of MutableAttr.
"""
def __init__(self, items=None, sequence_type=tuple):
if items is None:
items = {}
elif not isinstance(items, Mapping):
items = dict(items)
self._setattr('_sequence_type', sequence_type)... | class AttrMap(MutableAttr):
"""
An implementation of MutableAttr.
"""
def __init__(self, items=None, sequence_type=tuple):
if items is None:
items = {}
elif not isinstance(items, Mapping):
items = dict(items)
self._setattr('_sequence_type', sequence_type)... | return cls(mapping, sequence_type=configuration)
| """
A standardized constructor.
"""
return cls(mapping, sequence_type=configuration)
| 3 | 615 | 15 | 630 | """
An implementation of MutableAttr.
"""
try:
from collections import Mapping
except ImportError:
from collections.abc import Mapping
import six
from .mixins import MutableAttr
__all__ = ['AttrMap']
class AttrMap(MutableAttr):
"""
An implementation of MutableAttr.
"""
def __init__(self, i... | """
An implementation of MutableAttr.
"""
try:
from collections import Mapping
except ImportError:
from collections.abc import Mapping
import six
from .mixins import MutableAttr
__all__ = ['AttrMap']
class AttrMap(MutableAttr):
"""
An implementation of MutableAttr.
"""
def __init__(self, i... |
43,283 | /home/hieuvd/dung_repo/raw/stars_03/Margular_frida-skeleton/frida-skeleton | /home/hieuvd/dung_repo/raw/stars_03/Margular_frida-skeleton/frida-skeleton/thirdparty/attrdict/merge.py | 13,14 | 1,48 | merge | 23,48 | 14,48 | """
A right-favoring Mapping merge.
"""
try:
from collections import Mapping
except ImportError:
from collections.abc import Mapping
__all__ = ['merge']
def merge(left, right):
FILL_FUNC_BODY | """
A right-favoring Mapping merge.
"""
try:
from collections import Mapping
except ImportError:
from collections.abc import Mapping
__all__ = ['merge']
def merge(left, right):
"""
Merge two mappings objects together, combining overlapping Mappings,
and favoring right-values
left: The left ... | merged = {}
left_keys = frozenset(left)
right_keys = frozenset(right)
# Items only in the left Mapping
for key in left_keys - right_keys:
merged[key] = left[key]
# Items only in the right Mapping
for key in right_keys - left_keys:
merged[key] = right[key]
# in both
... | """
Merge two mappings objects together, combining overlapping Mappings,
and favoring right-values
left: The left Mapping object.
right: The right (favored) Mapping object.
NOTE: This is not commutative (merge(a,b) != merge(b,a)).
"""
merged = {}
left_keys = frozenset(left)
ri... | 80 | 151 | 243 | 394 | """
A right-favoring Mapping merge.
"""
try:
from collections import Mapping
except ImportError:
from collections.abc import Mapping
__all__ = ['merge']
def merge(left, right):
FILL_FUNC_BODY | """
A right-favoring Mapping merge.
"""
try:
from collections import Mapping
except ImportError:
from collections.abc import Mapping
__all__ = ['merge']
def merge(left, right):
"""
Merge two mappings objects together, combining overlapping Mappings,
and favoring right-values
left: The left ... | |
43,284 | /home/hieuvd/dung_repo/raw/stars_03/Margular_frida-skeleton/frida-skeleton | /home/hieuvd/dung_repo/raw/stars_03/Margular_frida-skeleton/frida-skeleton/thirdparty/attrdict/mixins.py | 119,120 | 21,161 | _build | Attr | 131,142 | 120,142 | @six.add_metaclass(ABCMeta)
class Attr(Mapping):
"""
A mixin class for a mapping that allows for attribute-style access
of values.
A key may be used as an attribute if:
* It is a string
* It matches /^[A-Za-z][A-Za-z0-9_]*$/ (i.e., a public attribute)
* The key doesn't overlap with any c... | @six.add_metaclass(ABCMeta)
class Attr(Mapping):
"""
A mixin class for a mapping that allows for attribute-style access
of values.
A key may be used as an attribute if:
* It is a string
* It matches /^[A-Za-z][A-Za-z0-9_]*$/ (i.e., a public attribute)
* The key doesn't overlap with any c... | if isinstance(obj, Mapping):
obj = self._constructor(obj, self._configuration())
elif (isinstance(obj, Sequence) and
not isinstance(obj, (six.string_types, six.binary_type))):
sequence_type = getattr(self, '_sequence_type', None)
if sequence_type:
... | """
Conditionally convert an object to allow for recursive mapping
access.
obj: An object that was a key-value pair in the mapping. If obj
is a mapping, self._constructor(obj, self._configuration())
will be called. If obj is a non-string/bytes sequence, and
... | 31 | 1,202 | 122 | 1,324 | """
Mixin Classes for Attr-support.
"""
from abc import ABCMeta, abstractmethod
try:
from collections import Mapping, MutableMapping, Sequence
except ImportError:
from collections.abc import Mapping, MutableMapping, Sequence
import re
import six
from .merge import merge
__all__ = ['Attr', 'MutableAttr']
... | """
Mixin Classes for Attr-support.
"""
from abc import ABCMeta, abstractmethod
try:
from collections import Mapping, MutableMapping, Sequence
except ImportError:
from collections.abc import Mapping, MutableMapping, Sequence
import re
import six
from .merge import merge
__all__ = ['Attr', 'MutableAttr']
... |
43,285 | /home/hieuvd/dung_repo/raw/stars_03/Margular_frida-skeleton/frida-skeleton | /home/hieuvd/dung_repo/raw/stars_03/Margular_frida-skeleton/frida-skeleton/thirdparty/attrdict/mixins.py | 192,193 | 161,215 | _delattr | MutableAttr | 197,199 | 193,199 | @six.add_metaclass(ABCMeta)
class MutableAttr(Attr, MutableMapping):
"""
A mixin class for a mapping that allows for attribute-style access
of values.
"""
def _setattr(self, key, value):
"""
Add an attribute to the object, without attempting to add it as
a key to the mapping.... | @six.add_metaclass(ABCMeta)
class MutableAttr(Attr, MutableMapping):
"""
A mixin class for a mapping that allows for attribute-style access
of values.
"""
def _setattr(self, key, value):
"""
Add an attribute to the object, without attempting to add it as
a key to the mapping.... | super(MutableAttr, self).__delattr__(key)
| """
Delete an attribute from the object, without attempting to
remove it from the mapping.
"""
super(MutableAttr, self).__delattr__(key)
| 2 | 433 | 19 | 452 | """
Mixin Classes for Attr-support.
"""
from abc import ABCMeta, abstractmethod
try:
from collections import Mapping, MutableMapping, Sequence
except ImportError:
from collections.abc import Mapping, MutableMapping, Sequence
import re
import six
from .merge import merge
__all__ = ['Attr', 'MutableAttr']
... | """
Mixin Classes for Attr-support.
"""
from abc import ABCMeta, abstractmethod
try:
from collections import Mapping, MutableMapping, Sequence
except ImportError:
from collections.abc import Mapping, MutableMapping, Sequence
import re
import six
from .merge import merge
__all__ = ['Attr', 'MutableAttr']
... |
43,427 | /home/hieuvd/dung_repo/raw/stars_03/MilaNLProc_contextualized-topic-models/contextualized-topic-models | /home/hieuvd/dung_repo/raw/stars_03/MilaNLProc_contextualized-topic-models/contextualized-topic-models/contextualized_topic_models/evaluation/measures.py | 337,338 | 286,344 | get_centroid | CentroidDistance | 338,344 | 338,344 | class CentroidDistance(Measure):
def __init__(
self, doc_distribution_original_language,
doc_distribution_unseen_language, topics, word2vec_path=None,
binary=True, topk=10):
"""
:param doc_distribution_original_language: numpy array of the topical
distribution o... | class CentroidDistance(Measure):
def __init__(
self, doc_distribution_original_language,
doc_distribution_unseen_language, topics, word2vec_path=None,
binary=True, topk=10):
"""
:param doc_distribution_original_language: numpy array of the topical
distribution o... | vector_list = []
for word in word_list:
if word in self.wv.index_to_key:
vector_list.append(self.wv.get_vector(word))
vec = sum(vector_list)
return vec / np.linalg.norm(vec)
| vector_list = []
for word in word_list:
if word in self.wv.index_to_key:
vector_list.append(self.wv.get_vector(word))
vec = sum(vector_list)
return vec / np.linalg.norm(vec)
| 19 | 658 | 84 | 742 | from gensim.corpora.dictionary import Dictionary
from gensim.models.coherencemodel import CoherenceModel
from gensim.models import KeyedVectors
import gensim.downloader as api
from scipy.spatial.distance import cosine
import abc
from contextualized_topic_models.evaluation.rbo import rbo
import numpy as np
import itert... | from gensim.corpora.dictionary import Dictionary
from gensim.models.coherencemodel import CoherenceModel
from gensim.models import KeyedVectors
import gensim.downloader as api
from scipy.spatial.distance import cosine
import abc
from contextualized_topic_models.evaluation.rbo import rbo
import numpy as np
import itert... |
43,428 | /home/hieuvd/dung_repo/raw/stars_03/MilaNLProc_contextualized-topic-models/contextualized-topic-models | /home/hieuvd/dung_repo/raw/stars_03/MilaNLProc_contextualized-topic-models/contextualized-topic-models/contextualized_topic_models/evaluation/measures.py | 133,134 | 129,153 | score | CoherenceCV | 140,153 | 134,153 | class CoherenceCV(Coherence):
def __init__(self, topics, texts):
super().__init__(topics, texts)
def score(self, topk=10, per_topic=False):
FILL_FUNC_BODY | class CoherenceCV(Coherence):
def __init__(self, topics, texts):
super().__init__(topics, texts)
def score(self, topk=10, per_topic=False):
"""
:param topk: how many most likely words to consider in the evaluation
:param per_topic: if True, returns the coherence value for each t... | if topk > len(self.topics[0]):
raise Exception('Words in topics are less than topk')
else:
cv = CoherenceModel(
topics=self.topics, texts=self.texts,
dictionary=self.dictionary,
coherence='c_v', topn=topk)
if per_topic:
... | """
:param topk: how many most likely words to consider in the evaluation
:param per_topic: if True, returns the coherence value for each topic
(default: False)
:return: C_V coherence
"""
if topk > len(self.topics[0]):
raise Exception('Words in topics ... | 28 | 122 | 137 | 259 | from gensim.corpora.dictionary import Dictionary
from gensim.models.coherencemodel import CoherenceModel
from gensim.models import KeyedVectors
import gensim.downloader as api
from scipy.spatial.distance import cosine
import abc
from contextualized_topic_models.evaluation.rbo import rbo
import numpy as np
import itert... | from gensim.corpora.dictionary import Dictionary
from gensim.models.coherencemodel import CoherenceModel
from gensim.models import KeyedVectors
import gensim.downloader as api
from scipy.spatial.distance import cosine
import abc
from contextualized_topic_models.evaluation.rbo import rbo
import numpy as np
import itert... |
43,429 | /home/hieuvd/dung_repo/raw/stars_03/MilaNLProc_contextualized-topic-models/contextualized-topic-models | /home/hieuvd/dung_repo/raw/stars_03/MilaNLProc_contextualized-topic-models/contextualized-topic-models/contextualized_topic_models/evaluation/measures.py | 61,62 | 57,81 | score | CoherenceNPMI | 68,81 | 62,81 | class CoherenceNPMI(Coherence):
def __init__(self, topics, texts):
super().__init__(topics, texts)
def score(self, topk=10, per_topic=False):
FILL_FUNC_BODY | class CoherenceNPMI(Coherence):
def __init__(self, topics, texts):
super().__init__(topics, texts)
def score(self, topk=10, per_topic=False):
"""
:param topk: how many most likely words to consider in the evaluation
:param per_topic: if True, returns the coherence value for each... | if topk > len(self.topics[0]):
raise Exception('Words in topics are less than topk')
else:
npmi = CoherenceModel(
topics=self.topics, texts=self.texts,
dictionary=self.dictionary,
coherence='c_npmi', topn=topk)
if per_to... | """
:param topk: how many most likely words to consider in the evaluation
:param per_topic: if True, returns the coherence value for each topic
(default: False)
:return: NPMI coherence
"""
if topk > len(self.topics[0]):
raise Exception('Words in topic... | 28 | 123 | 141 | 264 | from gensim.corpora.dictionary import Dictionary
from gensim.models.coherencemodel import CoherenceModel
from gensim.models import KeyedVectors
import gensim.downloader as api
from scipy.spatial.distance import cosine
import abc
from contextualized_topic_models.evaluation.rbo import rbo
import numpy as np
import itert... | from gensim.corpora.dictionary import Dictionary
from gensim.models.coherencemodel import CoherenceModel
from gensim.models import KeyedVectors
import gensim.downloader as api
from scipy.spatial.distance import cosine
import abc
from contextualized_topic_models.evaluation.rbo import rbo
import numpy as np
import itert... |
43,430 | /home/hieuvd/dung_repo/raw/stars_03/MilaNLProc_contextualized-topic-models/contextualized-topic-models | /home/hieuvd/dung_repo/raw/stars_03/MilaNLProc_contextualized-topic-models/contextualized-topic-models/contextualized_topic_models/evaluation/measures.py | 109,110 | 105,129 | score | CoherenceUCI | 116,129 | 110,129 | class CoherenceUCI(Coherence):
def __init__(self, topics, texts):
super().__init__(topics, texts)
def score(self, topk=10, per_topic=False):
FILL_FUNC_BODY | class CoherenceUCI(Coherence):
def __init__(self, topics, texts):
super().__init__(topics, texts)
def score(self, topk=10, per_topic=False):
"""
:param topk: how many most likely words to consider in the evaluation
:param per_topic: if True, returns the coherence value for each ... | if topk > len(self.topics[0]):
raise Exception('Words in topics are less than topk')
else:
uci = CoherenceModel(
topics=self.topics, texts=self.texts,
dictionary=self.dictionary,
coherence='c_uci', topn=topk)
if per_topi... | """
:param topk: how many most likely words to consider in the evaluation
:param per_topic: if True, returns the coherence value for each topic
(default: False)
:return: UCI coherence
"""
if topk > len(self.topics[0]):
raise Exception('Words in topics... | 28 | 122 | 141 | 263 | from gensim.corpora.dictionary import Dictionary
from gensim.models.coherencemodel import CoherenceModel
from gensim.models import KeyedVectors
import gensim.downloader as api
from scipy.spatial.distance import cosine
import abc
from contextualized_topic_models.evaluation.rbo import rbo
import numpy as np
import itert... | from gensim.corpora.dictionary import Dictionary
from gensim.models.coherencemodel import CoherenceModel
from gensim.models import KeyedVectors
import gensim.downloader as api
from scipy.spatial.distance import cosine
import abc
from contextualized_topic_models.evaluation.rbo import rbo
import numpy as np
import itert... |
43,431 | /home/hieuvd/dung_repo/raw/stars_03/MilaNLProc_contextualized-topic-models/contextualized-topic-models | /home/hieuvd/dung_repo/raw/stars_03/MilaNLProc_contextualized-topic-models/contextualized-topic-models/contextualized_topic_models/evaluation/measures.py | 85,86 | 81,105 | score | CoherenceUMASS | 92,105 | 86,105 | class CoherenceUMASS(Coherence):
def __init__(self, topics, texts):
super().__init__(topics, texts)
def score(self, topk=10, per_topic=False):
FILL_FUNC_BODY | class CoherenceUMASS(Coherence):
def __init__(self, topics, texts):
super().__init__(topics, texts)
def score(self, topk=10, per_topic=False):
"""
:param topk: how many most likely words to consider in the evaluation
:param per_topic: if True, returns the coherence value for eac... | if topk > len(self.topics[0]):
raise Exception('Words in topics are less than topk')
else:
umass = CoherenceModel(
topics=self.topics, texts=self.texts,
dictionary=self.dictionary,
coherence='u_mass', topn=topk)
if per_t... | """
:param topk: how many most likely words to consider in the evaluation
:param per_topic: if True, returns the coherence value for each topic
(default: False)
:return: UMass coherence
"""
if topk > len(self.topics[0]):
raise Exception('Words in topi... | 28 | 123 | 137 | 260 | from gensim.corpora.dictionary import Dictionary
from gensim.models.coherencemodel import CoherenceModel
from gensim.models import KeyedVectors
import gensim.downloader as api
from scipy.spatial.distance import cosine
import abc
from contextualized_topic_models.evaluation.rbo import rbo
import numpy as np
import itert... | from gensim.corpora.dictionary import Dictionary
from gensim.models.coherencemodel import CoherenceModel
from gensim.models import KeyedVectors
import gensim.downloader as api
from scipy.spatial.distance import cosine
import abc
from contextualized_topic_models.evaluation.rbo import rbo
import numpy as np
import itert... |
43,432 | /home/hieuvd/dung_repo/raw/stars_03/MilaNLProc_contextualized-topic-models/contextualized-topic-models | /home/hieuvd/dung_repo/raw/stars_03/MilaNLProc_contextualized-topic-models/contextualized-topic-models/contextualized_topic_models/evaluation/measures.py | 171,172 | 153,192 | score | CoherenceWordEmbeddings | 176,192 | 172,192 | class CoherenceWordEmbeddings(Measure):
def __init__(self, topics, word2vec_path=None, binary=False):
"""
:param topics: a list of lists of the top-n most likely words
:param word2vec_path: if word2vec_file is specified, it retrieves the
word embeddings file (in word2vec format) to ... | class CoherenceWordEmbeddings(Measure):
def __init__(self, topics, word2vec_path=None, binary=False):
"""
:param topics: a list of lists of the top-n most likely words
:param word2vec_path: if word2vec_file is specified, it retrieves the
word embeddings file (in word2vec format) to ... | if topk > len(self.topics[0]):
raise Exception('Words in topics are less than topk')
else:
arrays = []
for index, topic in enumerate(self.topics):
if len(topic) > 0:
local_simi = []
for word1, word2 in itertools.... | """
:param topk: how many most likely words to consider in the evaluation
:return: topic coherence computed on the word embeddings similarities
"""
if topk > len(self.topics[0]):
raise Exception('Words in topics are less than topk')
else:
arrays = ... | 48 | 290 | 199 | 489 | from gensim.corpora.dictionary import Dictionary
from gensim.models.coherencemodel import CoherenceModel
from gensim.models import KeyedVectors
import gensim.downloader as api
from scipy.spatial.distance import cosine
import abc
from contextualized_topic_models.evaluation.rbo import rbo
import numpy as np
import itert... | from gensim.corpora.dictionary import Dictionary
from gensim.models.coherencemodel import CoherenceModel
from gensim.models import KeyedVectors
import gensim.downloader as api
from scipy.spatial.distance import cosine
import abc
from contextualized_topic_models.evaluation.rbo import rbo
import numpy as np
import itert... |
43,433 | /home/hieuvd/dung_repo/raw/stars_03/MilaNLProc_contextualized-topic-models/contextualized-topic-models | /home/hieuvd/dung_repo/raw/stars_03/MilaNLProc_contextualized-topic-models/contextualized-topic-models/contextualized_topic_models/evaluation/measures.py | 200,201 | 192,217 | score | InvertedRBO | 207,217 | 201,217 | class InvertedRBO(Measure):
def __init__(self, topics):
"""
:param topics: a list of lists of words
"""
super().__init__()
self.topics = topics
def score(self, topk=10, weight=0.9):
FILL_FUNC_BODY | class InvertedRBO(Measure):
def __init__(self, topics):
"""
:param topics: a list of lists of words
"""
super().__init__()
self.topics = topics
def score(self, topk=10, weight=0.9):
"""
:param weight: p (float), default 1.0: Weight of each agreement at
... | if topk > len(self.topics[0]):
raise Exception('Words in topics are less than topk')
else:
collect = []
for list1, list2 in itertools.combinations(self.topics, 2):
rbo_val = rbo.rbo(list1[:topk], list2[:topk], p=weight)[2]
collect.appen... | """
:param weight: p (float), default 1.0: Weight of each agreement at
depth d: p**(d-1). When set to 1.0, there is no weight, the rbo
returns to average overlap.
:return: rank_biased_overlap over the topics
"""
if topk > len(self.topics[0]):
raise E... | 32 | 160 | 130 | 290 | from gensim.corpora.dictionary import Dictionary
from gensim.models.coherencemodel import CoherenceModel
from gensim.models import KeyedVectors
import gensim.downloader as api
from scipy.spatial.distance import cosine
import abc
from contextualized_topic_models.evaluation.rbo import rbo
import numpy as np
import itert... | from gensim.corpora.dictionary import Dictionary
from gensim.models.coherencemodel import CoherenceModel
from gensim.models import KeyedVectors
import gensim.downloader as api
from scipy.spatial.distance import cosine
import abc
from contextualized_topic_models.evaluation.rbo import rbo
import numpy as np
import itert... |
43,434 | /home/hieuvd/dung_repo/raw/stars_03/MilaNLProc_contextualized-topic-models/contextualized-topic-models | /home/hieuvd/dung_repo/raw/stars_03/MilaNLProc_contextualized-topic-models/contextualized-topic-models/contextualized_topic_models/evaluation/measures.py | 270,271 | 250,280 | score | KLDivergence | 274,280 | 271,280 | class KLDivergence(Measure):
def __init__(
self, doc_distribution_original_language,
doc_distribution_unseen_language):
"""
:param doc_distribution_original_language: numpy array of the topical
distribution of the documents in the original language
(dim: num do... | class KLDivergence(Measure):
def __init__(
self, doc_distribution_original_language,
doc_distribution_unseen_language):
"""
:param doc_distribution_original_language: numpy array of the topical
distribution of the documents in the original language
(dim: num do... | kl_mean = 0
for d1, d2 in zip(self.orig_lang_docs, self.unseen_lang_docs):
kl_mean = kl_mean + kl_div(d1, d2)
return kl_mean/len(self.unseen_lang_docs)
| """
:return: average kullback leibler divergence between the distributions
"""
kl_mean = 0
for d1, d2 in zip(self.orig_lang_docs, self.unseen_lang_docs):
kl_mean = kl_mean + kl_div(d1, d2)
return kl_mean/len(self.unseen_lang_docs)
| 17 | 263 | 86 | 349 | from gensim.corpora.dictionary import Dictionary
from gensim.models.coherencemodel import CoherenceModel
from gensim.models import KeyedVectors
import gensim.downloader as api
from scipy.spatial.distance import cosine
import abc
from contextualized_topic_models.evaluation.rbo import rbo
import numpy as np
import itert... | from gensim.corpora.dictionary import Dictionary
from gensim.models.coherencemodel import CoherenceModel
from gensim.models import KeyedVectors
import gensim.downloader as api
from scipy.spatial.distance import cosine
import abc
from contextualized_topic_models.evaluation.rbo import rbo
import numpy as np
import itert... |
43,435 | /home/hieuvd/dung_repo/raw/stars_03/MilaNLProc_contextualized-topic-models/contextualized-topic-models | /home/hieuvd/dung_repo/raw/stars_03/MilaNLProc_contextualized-topic-models/contextualized-topic-models/contextualized_topic_models/evaluation/measures.py | 237,238 | 217,250 | score | Matches | 243,250 | 238,250 | class Matches(Measure):
def __init__(
self, doc_distribution_original_language,
doc_distribution_unseen_language):
"""
:param doc_distribution_original_language: numpy array of the topical
distribution of the documents in the original language
(dim: num docs x ... | class Matches(Measure):
def __init__(
self, doc_distribution_original_language,
doc_distribution_unseen_language):
"""
:param doc_distribution_original_language: numpy array of the topical
distribution of the documents in the original language
(dim: num docs x ... | matches = 0
for d1, d2 in zip(self.orig_lang_docs, self.unseen_lang_docs):
if np.argmax(d1) == np.argmax(d2):
matches = matches + 1
return matches/len(self.unseen_lang_docs)
| """
:return: proportion of matches between the predicted topic in the
original language and the predicted topic in the unseen language of
the document distributions
"""
matches = 0
for d1, d2 in zip(self.orig_lang_docs, self.unseen_lang_docs):
if np.... | 20 | 277 | 85 | 362 | from gensim.corpora.dictionary import Dictionary
from gensim.models.coherencemodel import CoherenceModel
from gensim.models import KeyedVectors
import gensim.downloader as api
from scipy.spatial.distance import cosine
import abc
from contextualized_topic_models.evaluation.rbo import rbo
import numpy as np
import itert... | from gensim.corpora.dictionary import Dictionary
from gensim.models.coherencemodel import CoherenceModel
from gensim.models import KeyedVectors
import gensim.downloader as api
from scipy.spatial.distance import cosine
import abc
from contextualized_topic_models.evaluation.rbo import rbo
import numpy as np
import itert... |
43,436 | /home/hieuvd/dung_repo/raw/stars_03/MilaNLProc_contextualized-topic-models/contextualized-topic-models | /home/hieuvd/dung_repo/raw/stars_03/MilaNLProc_contextualized-topic-models/contextualized-topic-models/contextualized_topic_models/evaluation/measures.py | 26,27 | 21,41 | score | TopicDiversity | 31,41 | 27,41 | class TopicDiversity(Measure):
def __init__(self, topics):
super().__init__()
self.topics = topics
def score(self, topk=25):
FILL_FUNC_BODY | class TopicDiversity(Measure):
def __init__(self, topics):
super().__init__()
self.topics = topics
def score(self, topk=25):
"""
:param topk: topk words on which the topic diversity will be computed
:return:
"""
FILL_FUNC_BODY | if topk > len(self.topics[0]):
raise Exception('Words in topics are less than topk')
else:
unique_words = set()
for t in self.topics:
unique_words = unique_words.union(set(t[:topk]))
td = len(unique_words) / (topk * len(self.topics))
... | """
:param topk: topk words on which the topic diversity will be computed
:return:
"""
if topk > len(self.topics[0]):
raise Exception('Words in topics are less than topk')
else:
unique_words = set()
for t in self.topics:
... | 32 | 88 | 110 | 198 | from gensim.corpora.dictionary import Dictionary
from gensim.models.coherencemodel import CoherenceModel
from gensim.models import KeyedVectors
import gensim.downloader as api
from scipy.spatial.distance import cosine
import abc
from contextualized_topic_models.evaluation.rbo import rbo
import numpy as np
import itert... | from gensim.corpora.dictionary import Dictionary
from gensim.models.coherencemodel import CoherenceModel
from gensim.models import KeyedVectors
import gensim.downloader as api
from scipy.spatial.distance import cosine
import abc
from contextualized_topic_models.evaluation.rbo import rbo
import numpy as np
import itert... |
43,438 | /home/hieuvd/dung_repo/raw/stars_03/MilaNLProc_contextualized-topic-models/contextualized-topic-models | /home/hieuvd/dung_repo/raw/stars_03/MilaNLProc_contextualized-topic-models/contextualized-topic-models/contextualized_topic_models/models/kitty_classifier.py | 27,40 | 11,191 | train | Kitty | 54,99 | 40,99 | class Kitty:
"""
Kitty is a utility to generate a simple classifiers from a topic model. It first run
a CTM instance on the data for you and you can then select a set of topics of interest. Once
this is done, you can apply this selection to a wider range of documents.
"""
def __init__(self, show... | class Kitty:
"""
Kitty is a utility to generate a simple classifiers from a topic model. It first run
a CTM instance on the data for you and you can then select a set of topics of interest. Once
this is done, you can apply this selection to a wider range of documents.
"""
def __init__(self, show... | if embedding_model is None and custom_embeddings is None:
raise Exception('Either embedding_model or custom_embeddings must be defined')
if custom_embeddings is not None:
if type(custom_embeddings).__module__ != 'numpy':
raise TypeError("custom_embeddings must be... | """
:param documents: list of documents to train the topic model
:param embedding_model: the embedding model used to create the embeddings
:param custom_embeddings: np.ndarray type object to use custom embeddings (optional).
:param stopwords_list: list of the stopwords to use
... | 143 | 1,411 | 635 | 2,046 | from contextualized_topic_models.models.ctm import ZeroShotTM
from contextualized_topic_models.utils.preprocessing import WhiteSpacePreprocessingStopwords
from contextualized_topic_models.utils.data_preparation import TopicModelDataPreparation
import numpy as np
import pickle
import warnings
import ipywidgets as widget... | from contextualized_topic_models.models.ctm import ZeroShotTM
from contextualized_topic_models.utils.preprocessing import WhiteSpacePreprocessingStopwords
from contextualized_topic_models.utils.data_preparation import TopicModelDataPreparation
import numpy as np
import pickle
import warnings
import ipywidgets as widget... |
43,440 | /home/hieuvd/dung_repo/raw/stars_03/MilaNLProc_contextualized-topic-models/contextualized-topic-models | /home/hieuvd/dung_repo/raw/stars_03/MilaNLProc_contextualized-topic-models/contextualized-topic-models/contextualized_topic_models/networks/inference_network.py | 127,128 | 75,145 | forward | CombinedInferenceNetwork | 129,145 | 128,145 | class CombinedInferenceNetwork(nn.Module):
"""Inference Network."""
def __init__(self, input_size, bert_size, output_size, hidden_sizes,
activation='softplus', dropout=0.2, label_size=0):
"""
Initialize InferenceNetwork.
Args
input_size : int, dimension of... | class CombinedInferenceNetwork(nn.Module):
"""Inference Network."""
def __init__(self, input_size, bert_size, output_size, hidden_sizes,
activation='softplus', dropout=0.2, label_size=0):
"""
Initialize InferenceNetwork.
Args
input_size : int, dimension of... | x_bert = self.adapt_bert(x_bert)
x = torch.cat((x, x_bert), 1)
if labels is not None:
x = torch.cat((x, labels), 1)
x = self.input_layer(x)
x = self.activation(x)
x = self.hiddens(x)
x = self.dropout_enc(x)
mu = self.f_mu_batchnorm(self.f_m... | """Forward pass."""
x_bert = self.adapt_bert(x_bert)
x = torch.cat((x, x_bert), 1)
if labels is not None:
x = torch.cat((x, labels), 1)
x = self.input_layer(x)
x = self.activation(x)
x = self.hiddens(x)
x = self.dropout_enc(x)
mu = ... | 39 | 723 | 179 | 902 | from collections import OrderedDict
from torch import nn
import torch
class ContextualInferenceNetwork(nn.Module):
"""Inference Network."""
def __init__(self, input_size, bert_size, output_size, hidden_sizes,
activation='softplus', dropout=0.2, label_size=0):
"""
# TODO: che... | from collections import OrderedDict
from torch import nn
import torch
class ContextualInferenceNetwork(nn.Module):
"""Inference Network."""
def __init__(self, input_size, bert_size, output_size, hidden_sizes,
activation='softplus', dropout=0.2, label_size=0):
"""
# TODO: che... |
43,441 | /home/hieuvd/dung_repo/raw/stars_03/MilaNLProc_contextualized-topic-models/contextualized-topic-models | /home/hieuvd/dung_repo/raw/stars_03/MilaNLProc_contextualized-topic-models/contextualized-topic-models/contextualized_topic_models/networks/inference_network.py | 57,58 | 6,75 | forward | ContextualInferenceNetwork | 59,75 | 58,75 | class ContextualInferenceNetwork(nn.Module):
"""Inference Network."""
def __init__(self, input_size, bert_size, output_size, hidden_sizes,
activation='softplus', dropout=0.2, label_size=0):
"""
# TODO: check dropout in main caller
Initialize InferenceNetwork.
... | class ContextualInferenceNetwork(nn.Module):
"""Inference Network."""
def __init__(self, input_size, bert_size, output_size, hidden_sizes,
activation='softplus', dropout=0.2, label_size=0):
"""
# TODO: check dropout in main caller
Initialize InferenceNetwork.
... |
x = x_bert
if labels:
x = torch.cat((x_bert, labels), 1)
x = self.input_layer(x)
x = self.activation(x)
x = self.hiddens(x)
x = self.dropout_enc(x)
mu = self.f_mu_batchnorm(self.f_mu(x))
log_sigma = self.f_sigma_batchnorm(self.f_sigma(x))
... | """Forward pass."""
x = x_bert
if labels:
x = torch.cat((x_bert, labels), 1)
x = self.input_layer(x)
x = self.activation(x)
x = self.hiddens(x)
x = self.dropout_enc(x)
mu = self.f_mu_batchnorm(self.f_mu(x))
log_sigma = self.f_sigma_b... | 31 | 706 | 152 | 858 | from collections import OrderedDict
from torch import nn
import torch
class ContextualInferenceNetwork(nn.Module):
"""Inference Network."""
def __init__(self, input_size, bert_size, output_size, hidden_sizes,
activation='softplus', dropout=0.2, label_size=0):
"""
# TODO: che... | from collections import OrderedDict
from torch import nn
import torch
class ContextualInferenceNetwork(nn.Module):
"""Inference Network."""
def __init__(self, input_size, bert_size, output_size, hidden_sizes,
activation='softplus', dropout=0.2, label_size=0):
"""
# TODO: che... |
43,443 | /home/hieuvd/dung_repo/raw/stars_03/MilaNLProc_contextualized-topic-models/contextualized-topic-models | /home/hieuvd/dung_repo/raw/stars_03/MilaNLProc_contextualized-topic-models/contextualized-topic-models/contextualized_topic_models/utils/data_preparation.py | 82,83 | 70,224 | load | TopicModelDataPreparation | 83,90 | 83,90 | class TopicModelDataPreparation:
def __init__(
self, contextualized_model=None, show_warning=True, max_seq_length=128
):
self.contextualized_model = contextualized_model
self.vocab = []
self.id2token = {}
self.vectorizer = None
self.label_encoder = None
se... | class TopicModelDataPreparation:
def __init__(
self, contextualized_model=None, show_warning=True, max_seq_length=128
):
self.contextualized_model = contextualized_model
self.vocab = []
self.id2token = {}
self.vectorizer = None
self.label_encoder = None
se... | return CTMDataset(
X_contextual=contextualized_embeddings,
X_bow=bow_embeddings,
idx2token=id2token,
labels=labels,
)
| return CTMDataset(
X_contextual=contextualized_embeddings,
X_bow=bow_embeddings,
idx2token=id2token,
labels=labels,
)
| 7 | 1,617 | 60 | 1,677 | import numpy as np
from sentence_transformers import SentenceTransformer
import scipy.sparse
import warnings
from contextualized_topic_models.datasets.dataset import CTMDataset
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.preprocessing import OneHotEncoder
def get_bag_of_words(data, min_le... | import numpy as np
from sentence_transformers import SentenceTransformer
import scipy.sparse
import warnings
from contextualized_topic_models.datasets.dataset import CTMDataset
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.preprocessing import OneHotEncoder
def get_bag_of_words(data, min_le... |
43,444 | /home/hieuvd/dung_repo/raw/stars_03/MilaNLProc_contextualized-topic-models/contextualized-topic-models | /home/hieuvd/dung_repo/raw/stars_03/MilaNLProc_contextualized-topic-models/contextualized-topic-models/contextualized_topic_models/utils/early_stopping/early_stopping.py | 54,55 | 5,62 | save_checkpoint | EarlyStopping | 56,62 | 55,62 | class EarlyStopping:
"""Early stops the training if validation loss doesn't improve after a given patience.
Source code: https://github.com/Bjarten/early-stopping-pytorch """
def __init__(self, patience=7, verbose=False, delta=0, path='checkpoint.pt', trace_func=print):
"""
Args:
... | class EarlyStopping:
"""Early stops the training if validation loss doesn't improve after a given patience.
Source code: https://github.com/Bjarten/early-stopping-pytorch """
def __init__(self, patience=7, verbose=False, delta=0, path='checkpoint.pt', trace_func=print):
"""
Args:
... | if self.verbose:
self.trace_func(f'Validation loss decreased ({self.val_loss_min:.6f} --> {val_loss:.6f}). Saving model ...')
model.save(self.path)
self.val_loss_min = val_loss
| """Saves model when validation loss decrease."""
if self.verbose:
self.trace_func(f'Validation loss decreased ({self.val_loss_min:.6f} --> {val_loss:.6f}). Saving model ...')
model.save(self.path)
self.val_loss_min = val_loss
| 15 | 555 | 81 | 636 | import numpy as np
import torch
class EarlyStopping:
"""Early stops the training if validation loss doesn't improve after a given patience.
Source code: https://github.com/Bjarten/early-stopping-pytorch """
def __init__(self, patience=7, verbose=False, delta=0, path='checkpoint.pt', trace_func=print):
... | import numpy as np
import torch
class EarlyStopping:
"""Early stops the training if validation loss doesn't improve after a given patience.
Source code: https://github.com/Bjarten/early-stopping-pytorch """
def __init__(self, patience=7, verbose=False, delta=0, path='checkpoint.pt', trace_func=print):
... |
43,461 | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/analyze/clseval.py | 563,564 | 549,574 | update | AverageMeter | 564,569 | 564,569 | class AverageMeter:
"""Computes and stores the average and current value"""
def __init__(self, name, fmt=":f"):
self.name = name
self.fmt = fmt
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, ... | class AverageMeter:
"""Computes and stores the average and current value"""
def __init__(self, name, fmt=":f"):
self.name = name
self.fmt = fmt
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, ... | self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
| self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
| 16 | 176 | 43 | 219 | #!/usr/bin/env python
# Copyright (c) Meta Platforms, Inc. and affiliates.
# https://github.com/facebookresearch/moco/blob/main/main_lincls.py
import argparse
import builtins
import os
import random
import shutil
import time
import warnings
import torch
import torch.backends.cudnn as cudnn
import torch.distributed a... | #!/usr/bin/env python
# Copyright (c) Meta Platforms, Inc. and affiliates.
# https://github.com/facebookresearch/moco/blob/main/main_lincls.py
import argparse
import builtins
import os
import random
import shutil
import time
import warnings
import torch
import torch.backends.cudnn as cudnn
import torch.distributed a... |
43,462 | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/analyze/clseval.py | 580,581 | 574,591 | display | ProgressMeter | 581,585 | 581,585 | class ProgressMeter:
def __init__(self, num_batches, meters, prefix=""):
self.batch_fmtstr = self._get_batch_fmtstr(num_batches)
self.meters = meters
self.prefix = prefix
def display(self, batch):
FILL_FUNC_BODY def _get_batch_fmtstr(self, num_batches):
num_digits = len(str(n... | class ProgressMeter:
def __init__(self, num_batches, meters, prefix=""):
self.batch_fmtstr = self._get_batch_fmtstr(num_batches)
self.meters = meters
self.prefix = prefix
def display(self, batch):
FILL_FUNC_BODY def _get_batch_fmtstr(self, num_batches):
num_digits = len(str(n... | entries = [self.prefix + self.batch_fmtstr.format(batch)]
entries += [str(meter) for meter in self.meters]
print("\t".join(entries))
| entries = [self.prefix + self.batch_fmtstr.format(batch)]
entries += [str(meter) for meter in self.meters]
print("\t".join(entries))
| 13 | 167 | 54 | 221 | #!/usr/bin/env python
# Copyright (c) Meta Platforms, Inc. and affiliates.
# https://github.com/facebookresearch/moco/blob/main/main_lincls.py
import argparse
import builtins
import os
import random
import shutil
import time
import warnings
import torch
import torch.backends.cudnn as cudnn
import torch.distributed a... | #!/usr/bin/env python
# Copyright (c) Meta Platforms, Inc. and affiliates.
# https://github.com/facebookresearch/moco/blob/main/main_lincls.py
import argparse
import builtins
import os
import random
import shutil
import time
import warnings
import torch
import torch.backends.cudnn as cudnn
import torch.distributed a... |
43,463 | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/analyze/convnexts4nd/extensions/kernels/tune_cauchy.py | 10,11 | 1,64 | forward_params_list | 11,28 | 11,28 | import math
import json
import argparse
import itertools
from pathlib import Path
from tuner import KernelTuner
def forward_params_list(N):
FILL_FUNC_BODYdef backward_params_list(L):
thread_value_supported = [8, 16, 32, 64, 128]
thread_params = ('ITEMS_PER_THREAD_SYM_BWD_VALUE', [v for v in thread_value_supp... | import math
import json
import argparse
import itertools
from pathlib import Path
from tuner import KernelTuner
def forward_params_list(N):
FILL_FUNC_BODYdef backward_params_list(L):
thread_value_supported = [8, 16, 32, 64, 128]
thread_params = ('ITEMS_PER_THREAD_SYM_BWD_VALUE', [v for v in thread_value_supp... | blocksize_params = ('MAX_BLOCK_SIZE_VALUE', [64, 128, 256, 512, 1024])
thread_value_default = [2, 4, 8, 16, 32, 32, 32, 32, 32, 32]
thread_values_supported = [2, 4, 8, 16, 32, 64, 128]
log_N_half = int(math.log2(N)) - 1
thread_values = []
for val in thread_values_supported:
if val <= N /... | blocksize_params = ('MAX_BLOCK_SIZE_VALUE', [64, 128, 256, 512, 1024])
thread_value_default = [2, 4, 8, 16, 32, 32, 32, 32, 32, 32]
thread_values_supported = [2, 4, 8, 16, 32, 64, 128]
log_N_half = int(math.log2(N)) - 1
thread_values = []
for val in thread_values_supported:
if val <= N /... | 85 | 579 | 338 | 917 | import math
import json
import argparse
import itertools
from pathlib import Path
from tuner import KernelTuner
def forward_params_list(N):
FILL_FUNC_BODYdef backward_params_list(L):
thread_value_supported = [8, 16, 32, 64, 128]
thread_params = ('ITEMS_PER_THREAD_SYM_BWD_VALUE', [v for v in thread_value_supp... | import math
import json
import argparse
import itertools
from pathlib import Path
from tuner import KernelTuner
def forward_params_list(N):
FILL_FUNC_BODYdef backward_params_list(L):
thread_value_supported = [8, 16, 32, 64, 128]
thread_params = ('ITEMS_PER_THREAD_SYM_BWD_VALUE', [v for v in thread_value_supp... | |
43,464 | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/analyze/convnexts4nd/src/dataloaders/datasets/adding.py | 26,27 | 1,31 | adding_static_dataset | 27,31 | 27,31 | """Implementation of standard Adding dataset.
Originally used in Arjovsky's Unitary RNN, maybe earlier?
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
def torch_adding_data(L, batch_shape=()):
assert L >= 2
mid = L//2
idx0 = torch.randint(low=0, high=mid, size=batch_shape)
id... | """Implementation of standard Adding dataset.
Originally used in Arjovsky's Unitary RNN, maybe earlier?
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
def torch_adding_data(L, batch_shape=()):
assert L >= 2
mid = L//2
idx0 = torch.randint(low=0, high=mid, size=batch_shape)
id... | all_x, all_y = torch_adding_data(L, batch_shape=(samples,))
print("Constructing Adding dataset of shape", all_x.shape)
ds = torch.utils.data.TensorDataset(all_x, all_y)
return ds
| all_x, all_y = torch_adding_data(L, batch_shape=(samples,))
print("Constructing Adding dataset of shape", all_x.shape)
ds = torch.utils.data.TensorDataset(all_x, all_y)
return ds
| 17 | 314 | 78 | 392 | """Implementation of standard Adding dataset.
Originally used in Arjovsky's Unitary RNN, maybe earlier?
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
def torch_adding_data(L, batch_shape=()):
assert L >= 2
mid = L//2
idx0 = torch.randint(low=0, high=mid, size=batch_shape)
id... | """Implementation of standard Adding dataset.
Originally used in Arjovsky's Unitary RNN, maybe earlier?
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
def torch_adding_data(L, batch_shape=()):
assert L >= 2
mid = L//2
idx0 = torch.randint(low=0, high=mid, size=batch_shape)
id... | |
43,465 | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/analyze/convnexts4nd/src/dataloaders/utils/signal.py | 5,6 | 1,35 | whitesignal | 11,35 | 6,35 | """Data utilities for generating signals."""
import numpy as np
def whitesignal(period, dt, freq, rms=0.5, batch_shape=()):
FILL_FUNC_BODY | """Data utilities for generating signals."""
import numpy as np
def whitesignal(period, dt, freq, rms=0.5, batch_shape=()):
"""
Produces output signal of length period / dt, band-limited to frequency freq
Output shape (*batch_shape, period/dt)
Adapted from the nengo library
"""
FILL_FUNC_BODY |
if freq is not None and freq < 1. / period:
raise ValueError(f"Make ``{freq=} >= 1. / {period=}`` to produce a non-zero signal",)
nyquist_cutoff = 0.5 / dt
if freq > nyquist_cutoff:
raise ValueError(f"{freq} must not exceed the Nyquist frequency for the given dt ({nyquist_cutoff:0.3f})")
... | """
Produces output signal of length period / dt, band-limited to frequency freq
Output shape (*batch_shape, period/dt)
Adapted from the nengo library
"""
if freq is not None and freq < 1. / period:
raise ValueError(f"Make ``{freq=} >= 1. / {period=}`` to produce a non-zero signal",)
... | 131 | 101 | 429 | 530 | """Data utilities for generating signals."""
import numpy as np
def whitesignal(period, dt, freq, rms=0.5, batch_shape=()):
FILL_FUNC_BODY | """Data utilities for generating signals."""
import numpy as np
def whitesignal(period, dt, freq, rms=0.5, batch_shape=()):
"""
Produces output signal of length period / dt, band-limited to frequency freq
Output shape (*batch_shape, period/dt)
Adapted from the nengo library
"""
FILL_FUNC_BODY | |
43,467 | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/analyze/convnexts4nd/src/models/baselines/nonaka/basic_conv1d.py | 127,128 | 115,131 | attrib | AdaptiveConcatPool1d | 128,131 | 128,131 | class AdaptiveConcatPool1d(nn.Module):
"Layer that concats `AdaptiveAvgPool1d` and `AdaptiveMaxPool1d`."
def __init__(self, sz: Optional[int] = None):
"Output will be 2*sz or 2 if sz is None"
super().__init__()
sz = sz or 1
self.ap, self.mp = nn.AdaptiveAvgPool1d(sz), nn.Adaptiv... | class AdaptiveConcatPool1d(nn.Module):
"Layer that concats `AdaptiveAvgPool1d` and `AdaptiveMaxPool1d`."
def __init__(self, sz: Optional[int] = None):
"Output will be 2*sz or 2 if sz is None"
super().__init__()
sz = sz or 1
self.ap, self.mp = nn.AdaptiveAvgPool1d(sz), nn.Adaptiv... | return attrib_adaptiveconcatpool(self, relevant, irrelevant)
| return attrib_adaptiveconcatpool(self, relevant, irrelevant)
| 4 | 197 | 23 | 220 | import torch
import torch.nn as nn
import torch.nn.functional as F
import math
from typing import Optional, Collection
##############################################################################################################################################
# utility functions
def listify(p=None, q=None):
#... | import torch
import torch.nn as nn
import torch.nn.functional as F
import math
from typing import Optional, Collection
##############################################################################################################################################
# utility functions
def listify(p=None, q=None):
#... |
43,468 | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/analyze/convnexts4nd/src/models/baselines/nonaka/basic_conv1d.py | 53,54 | 52,57 | forward | Flatten | 54,57 | 54,57 | class Flatten(nn.Module):
def forward(self, x):
FILL_FUNC_BODY | class Flatten(nn.Module):
def forward(self, x):
FILL_FUNC_BODY | return x.view(x.size(0), -1)
| return x.view(x.size(0), -1)
| 3 | 28 | 21 | 49 | import torch
import torch.nn as nn
import torch.nn.functional as F
import math
from typing import Optional, Collection
##############################################################################################################################################
# utility functions
def listify(p=None, q=None):
#... | import torch
import torch.nn as nn
import torch.nn.functional as F
import math
from typing import Optional, Collection
##############################################################################################################################################
# utility functions
def listify(p=None, q=None):
#... |
43,469 | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/analyze/convnexts4nd/src/models/baselines/nonaka/basic_conv1d.py | 144,145 | 131,156 | forward | SqueezeExcite1d | 145,156 | 145,156 | class SqueezeExcite1d(nn.Module):
"""squeeze excite block as used for example in LSTM FCN"""
def __init__(self, channels, reduction=16):
super().__init__()
channels_reduced = channels // reduction
self.w1 = torch.nn.Parameter(
torch.randn(channels_reduced, channels).unsqueez... | class SqueezeExcite1d(nn.Module):
"""squeeze excite block as used for example in LSTM FCN"""
def __init__(self, channels, reduction=16):
super().__init__()
channels_reduced = channels // reduction
self.w1 = torch.nn.Parameter(
torch.randn(channels_reduced, channels).unsqueez... | # input is bs,ch,seq
z = torch.mean(x, dim=2, keepdim=True) # bs,ch
intermed = F.relu(
torch.matmul(self.w1, z)
) # (1,ch_red,ch * bs,ch,1) = (bs, ch_red, 1)
s = F.sigmoid(
torch.matmul(self.w2, intermed)
) # (1,ch,ch_red * bs, ch_red, 1=bs, ch,... | # input is bs,ch,seq
z = torch.mean(x, dim=2, keepdim=True) # bs,ch
intermed = F.relu(
torch.matmul(self.w1, z)
) # (1,ch_red,ch * bs,ch,1) = (bs, ch_red, 1)
s = F.sigmoid(
torch.matmul(self.w2, intermed)
) # (1,ch,ch_red * bs, ch_red, 1=bs, ch,... | 50 | 168 | 193 | 361 | import torch
import torch.nn as nn
import torch.nn.functional as F
import math
from typing import Optional, Collection
##############################################################################################################################################
# utility functions
def listify(p=None, q=None):
#... | import torch
import torch.nn as nn
import torch.nn.functional as F
import math
from typing import Optional, Collection
##############################################################################################################################################
# utility functions
def listify(p=None, q=None):
#... |
43,470 | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/analyze/convnexts4nd/src/models/baselines/nonaka/basic_conv1d.py | 308,309 | 206,317 | set_output_layer | basic_conv1d | 309,317 | 309,317 | class basic_conv1d(nn.Sequential):
"""basic conv1d"""
def __init__(
self,
filters=[128, 128, 128, 128],
kernel_size=3,
stride=2,
dilation=1,
pool=0,
pool_stride=1,
squeeze_excite_reduction=0,
num_classes=2,
input_channels=8,
... | class basic_conv1d(nn.Sequential):
"""basic conv1d"""
def __init__(
self,
filters=[128, 128, 128, 128],
kernel_size=3,
stride=2,
dilation=1,
pool=0,
pool_stride=1,
squeeze_excite_reduction=0,
num_classes=2,
input_channels=8,
... | if self.headless is False:
self[-1][-1] = x
############################################################################################
# convenience functions for basic convolutional architectures
| if self.headless is False:
self[-1][-1] = x
############################################################################################
# convenience functions for basic convolutional architectures
| 15 | 1,090 | 49 | 1,139 | import torch
import torch.nn as nn
import torch.nn.functional as F
import math
from typing import Optional, Collection
##############################################################################################################################################
# utility functions
def listify(p=None, q=None):
#... | import torch
import torch.nn as nn
import torch.nn.functional as F
import math
from typing import Optional, Collection
##############################################################################################################################################
# utility functions
def listify(p=None, q=None):
#... |
43,472 | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/analyze/convnexts4nd/src/models/baselines/resnet_timm.py | 352,353 | 313,378 | forward | BasicBlock | 353,378 | 353,378 | class BasicBlock(nn.Module):
expansion = 1
def __init__(
self, inplanes, planes, stride=1, downsample=None, cardinality=1, base_width=64,
reduce_first=1, dilation=1, first_dilation=None, act_layer=nn.ReLU, norm_layer=nn.BatchNorm2d,
attn_layer=None, aa_layer=None, drop_block... | class BasicBlock(nn.Module):
expansion = 1
def __init__(
self, inplanes, planes, stride=1, downsample=None, cardinality=1, base_width=64,
reduce_first=1, dilation=1, first_dilation=None, act_layer=nn.ReLU, norm_layer=nn.BatchNorm2d,
attn_layer=None, aa_layer=None, drop_block... | shortcut = x
x = self.conv1(x)
x = self.bn1(x)
x = self.drop_block(x)
x = self.act1(x)
x = self.aa(x)
x = self.conv2(x)
x = self.bn2(x)
if self.se is not None:
x = self.se(x)
if self.drop_path is not None:
x = se... | shortcut = x
x = self.conv1(x)
x = self.bn1(x)
x = self.drop_block(x)
x = self.act1(x)
x = self.aa(x)
x = self.conv2(x)
x = self.bn2(x)
if self.se is not None:
x = self.se(x)
if self.drop_path is not None:
x = se... | 56 | 586 | 202 | 788 | """PyTorch ResNet implementations.
This started as a copy of https://github.com/pytorch/vision 'resnet.py' (BSD-3-Clause) with
additional dropout and dynamic global avg/max pool.
ResNeXt, SE-ResNeXt, SENet, and MXNet Gluon stem/downsample variants, tiered stems added by Ross Wightman
Copyright 2019, Ross Wightman
"""
... | """PyTorch ResNet implementations.
This started as a copy of https://github.com/pytorch/vision 'resnet.py' (BSD-3-Clause) with
additional dropout and dynamic global avg/max pool.
ResNeXt, SE-ResNeXt, SENet, and MXNet Gluon stem/downsample variants, tiered stems added by Ross Wightman
Copyright 2019, Ross Wightman
"""
... |
43,473 | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/analyze/convnexts4nd/src/models/baselines/resnet_timm.py | 419,420 | 378,449 | forward | Bottleneck | 420,449 | 420,449 | class Bottleneck(nn.Module):
expansion = 4
def __init__(
self, inplanes, planes, stride=1, downsample=None, cardinality=1, base_width=64,
reduce_first=1, dilation=1, first_dilation=None, act_layer=nn.ReLU, norm_layer=nn.BatchNorm2d,
attn_layer=None, aa_layer=None, drop_block... | class Bottleneck(nn.Module):
expansion = 4
def __init__(
self, inplanes, planes, stride=1, downsample=None, cardinality=1, base_width=64,
reduce_first=1, dilation=1, first_dilation=None, act_layer=nn.ReLU, norm_layer=nn.BatchNorm2d,
attn_layer=None, aa_layer=None, drop_block... | shortcut = x
x = self.conv1(x)
x = self.bn1(x)
x = self.act1(x)
x = self.conv2(x)
x = self.bn2(x)
x = self.drop_block(x)
x = self.act2(x)
x = self.aa(x)
x = self.conv3(x)
x = self.bn3(x)
if self.se is not None:
... | shortcut = x
x = self.conv1(x)
x = self.bn1(x)
x = self.act1(x)
x = self.conv2(x)
x = self.bn2(x)
x = self.drop_block(x)
x = self.act2(x)
x = self.aa(x)
x = self.conv3(x)
x = self.bn3(x)
if self.se is not None:
... | 65 | 628 | 240 | 868 | """PyTorch ResNet implementations.
This started as a copy of https://github.com/pytorch/vision 'resnet.py' (BSD-3-Clause) with
additional dropout and dynamic global avg/max pool.
ResNeXt, SE-ResNeXt, SENet, and MXNet Gluon stem/downsample variants, tiered stems added by Ross Wightman
Copyright 2019, Ross Wightman
"""
... | """PyTorch ResNet implementations.
This started as a copy of https://github.com/pytorch/vision 'resnet.py' (BSD-3-Clause) with
additional dropout and dynamic global avg/max pool.
ResNeXt, SE-ResNeXt, SENet, and MXNet Gluon stem/downsample variants, tiered stems added by Ross Wightman
Copyright 2019, Ross Wightman
"""
... |
43,476 | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/analyze/convnexts4nd/src/models/baselines/transformer.py | 78,79 | 24,86 | _reset_parameters | ClassificationTransformer | 79,86 | 79,86 | class ClassificationTransformer(Module):
def __init__(
self,
d_input,
d_output,
d_model: int = 512,
nhead: int = 8,
num_encoder_layers: int = 6,
dim_feedforward: int = 2048,
dropout: float = 0.1,
activation:... | class ClassificationTransformer(Module):
def __init__(
self,
d_input,
d_output,
d_model: int = 512,
nhead: int = 8,
num_encoder_layers: int = 6,
dim_feedforward: int = 2048,
dropout: float = 0.1,
activation:... | r"""Initiate parameters in the transformer model."""
for p in self.parameters():
if p.dim() > 1:
xavier_uniform_(p)
| r"""Initiate parameters in the transformer model."""
for p in self.parameters():
if p.dim() > 1:
xavier_uniform_(p)
| 15 | 473 | 50 | 523 | """End-to-end classification Transformer adapted from PyTorch examples.
The isotropic model backbone should subsume this architecture. See config configs/model/transformer.yaml
"""
import copy
from typing import Optional, Any
from typing import Tuple
import torch
from torch import Tensor
from torch.nn import Module
... | """End-to-end classification Transformer adapted from PyTorch examples.
The isotropic model backbone should subsume this architecture. See config configs/model/transformer.yaml
"""
import copy
from typing import Optional, Any
from typing import Tuple
import torch
from torch import Tensor
from torch.nn import Module
... |
43,477 | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/analyze/convnexts4nd/src/models/baselines/transformer.py | 828,832 | 814,843 | forward | InProjContainer | 832,843 | 832,843 | class InProjContainer(torch.nn.Module):
def __init__(self, query_proj, key_proj, value_proj):
r"""A in-proj container to process inputs.
Args:
query_proj: a proj layer for query.
key_proj: a proj layer for key.
value_proj: a proj layer for value.
"""
... | class InProjContainer(torch.nn.Module):
def __init__(self, query_proj, key_proj, value_proj):
r"""A in-proj container to process inputs.
Args:
query_proj: a proj layer for query.
key_proj: a proj layer for key.
value_proj: a proj layer for value.
"""
... | r"""Projects the input sequences using in-proj layers.
Args:
query, key, value (Tensors): sequence to be projected
Shape:
- query, key, value: :math:`(S, N, E)`
- Output: :math:`(S, N, E)`
where S is the sequence length, N is the batch size, and E ... | r"""Projects the input sequences using in-proj layers.
Args:
query, key, value (Tensors): sequence to be projected
Shape:
- query, key, value: :math:`(S, N, E)`
- Output: :math:`(S, N, E)`
where S is the sequence length, N is the batch size, and E ... | 51 | 214 | 144 | 358 | """End-to-end classification Transformer adapted from PyTorch examples.
The isotropic model backbone should subsume this architecture. See config configs/model/transformer.yaml
"""
import copy
from typing import Optional, Any
from typing import Tuple
import torch
from torch import Tensor
from torch.nn import Module
... | """End-to-end classification Transformer adapted from PyTorch examples.
The isotropic model backbone should subsume this architecture. See config configs/model/transformer.yaml
"""
import copy
from typing import Optional, Any
from typing import Tuple
import torch
from torch import Tensor
from torch.nn import Module
... |
43,478 | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/analyze/convnexts4nd/src/models/baselines/transformer.py | 625,626 | 572,633 | forward | MultiheadAttention | 626,633 | 626,633 | class MultiheadAttention(torch.nn.Module):
def __init__(self, embed_dim, num_heads, dropout=0., bias=True, add_bias_kv=False, add_zero_attn=False, kdim=None,
vdim=None, share_qk=False):
super(MultiheadAttention, self).__init__()
self.embed_dim = embed_dim
self.kdim = kdim if... | class MultiheadAttention(torch.nn.Module):
def __init__(self, embed_dim, num_heads, dropout=0., bias=True, add_bias_kv=False, add_zero_attn=False, kdim=None,
vdim=None, share_qk=False):
super(MultiheadAttention, self).__init__()
self.embed_dim = embed_dim
self.kdim = kdim if... | if attn_mask is not None:
if attn_mask.dim() == 2:
attn_mask = attn_mask.view(-1, attn_mask.size(0), attn_mask.size(1))
attn_mask = attn_mask.bool()
return self.multihead_attention(query, key, value, types, attn_mask, self.bias_k, self.bias_v)
| if attn_mask is not None:
if attn_mask.dim() == 2:
attn_mask = attn_mask.view(-1, attn_mask.size(0), attn_mask.size(1))
attn_mask = attn_mask.bool()
return self.multihead_attention(query, key, value, types, attn_mask, self.bias_k, self.bias_v)
| 25 | 859 | 118 | 977 | """End-to-end classification Transformer adapted from PyTorch examples.
The isotropic model backbone should subsume this architecture. See config configs/model/transformer.yaml
"""
import copy
from typing import Optional, Any
from typing import Tuple
import torch
from torch import Tensor
from torch.nn import Module
... | """End-to-end classification Transformer adapted from PyTorch examples.
The isotropic model backbone should subsume this architecture. See config configs/model/transformer.yaml
"""
import copy
from typing import Optional, Any
from typing import Tuple
import torch
from torch import Tensor
from torch.nn import Module
... |
43,479 | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/analyze/convnexts4nd/src/models/baselines/transformer.py | 664,669 | 633,709 | forward | MultiheadAttentionContainer | 669,709 | 669,709 | class MultiheadAttentionContainer(torch.nn.Module):
def __init__(self, nhead, in_proj_container, attention_layer, out_proj):
r""" A multi-head attention container
Args:
nhead: the number of heads in the multiheadattention model
in_proj_container: A container of multi-head in-... | class MultiheadAttentionContainer(torch.nn.Module):
def __init__(self, nhead, in_proj_container, attention_layer, out_proj):
r""" A multi-head attention container
Args:
nhead: the number of heads in the multiheadattention model
in_proj_container: A container of multi-head in-... | r"""
Args:
query, key, value (Tensor): map a query and a set of key-value pairs to an output.
See "Attention Is All You Need" for more details.
attn_mask, bias_k and bias_v (Tensor, optional): keyword arguments passed to the attention layer.
See th... | r"""
Args:
query, key, value (Tensor): map a query and a set of key-value pairs to an output.
See "Attention Is All You Need" for more details.
attn_mask, bias_k and bias_v (Tensor, optional): keyword arguments passed to the attention layer.
See th... | 247 | 585 | 745 | 1,330 | """End-to-end classification Transformer adapted from PyTorch examples.
The isotropic model backbone should subsume this architecture. See config configs/model/transformer.yaml
"""
import copy
from typing import Optional, Any
from typing import Tuple
import torch
from torch import Tensor
from torch.nn import Module
... | """End-to-end classification Transformer adapted from PyTorch examples.
The isotropic model backbone should subsume this architecture. See config configs/model/transformer.yaml
"""
import copy
from typing import Optional, Any
from typing import Tuple
import torch
from torch import Tensor
from torch.nn import Module
... |
43,480 | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/analyze/convnexts4nd/src/models/baselines/transformer.py | 727,732 | 709,804 | forward | ScaledDotProduct | 732,804 | 732,804 | class ScaledDotProduct(torch.nn.Module):
def __init__(self, dropout=0.0):
r"""Processes a projected query and key-value pair to apply
scaled dot product attention.
Args:
dropout (float): probability of dropping an attention weight.
Examples::
>>> SDP = torcht... | class ScaledDotProduct(torch.nn.Module):
def __init__(self, dropout=0.0):
r"""Processes a projected query and key-value pair to apply
scaled dot product attention.
Args:
dropout (float): probability of dropping an attention weight.
Examples::
>>> SDP = torcht... | r"""Uses a scaled dot product with the projected key-value pair to update
the projected query.
Args:
query (Tensor): Projected query
key (Tensor): Projected key
value (Tensor): Projected value
attn_mask (BoolTensor, optional): 3D mask that prevents... | r"""Uses a scaled dot product with the projected key-value pair to update
the projected query.
Args:
query (Tensor): Projected query
key (Tensor): Projected key
value (Tensor): Projected value
attn_mask (BoolTensor, optional): 3D mask that prevents... | 433 | 373 | 1,356 | 1,729 | """End-to-end classification Transformer adapted from PyTorch examples.
The isotropic model backbone should subsume this architecture. See config configs/model/transformer.yaml
"""
import copy
from typing import Optional, Any
from typing import Tuple
import torch
from torch import Tensor
from torch.nn import Module
... | """End-to-end classification Transformer adapted from PyTorch examples.
The isotropic model backbone should subsume this architecture. See config configs/model/transformer.yaml
"""
import copy
from typing import Optional, Any
from typing import Tuple
import torch
from torch import Tensor
from torch.nn import Module
... |
43,481 | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/analyze/convnexts4nd/src/models/baselines/transformer.py | 810,811 | 804,814 | forward | SharedQK_Proj | 811,814 | 811,814 | class SharedQK_Proj(torch.nn.Module):
def __init__(self, qk_proj, v_proj):
super(SharedQK_Proj, self).__init__()
self.qk_proj = qk_proj
self.v_proj = qk_proj
def forward(self, q, k, v):
FILL_FUNC_BODY | class SharedQK_Proj(torch.nn.Module):
def __init__(self, qk_proj, v_proj):
super(SharedQK_Proj, self).__init__()
self.qk_proj = qk_proj
self.v_proj = qk_proj
def forward(self, q, k, v):
FILL_FUNC_BODY | return self.qk_proj(q), self.qk_proj(k), self.v_proj(v)
| return self.qk_proj(q), self.qk_proj(k), self.v_proj(v)
| 4 | 100 | 34 | 134 | """End-to-end classification Transformer adapted from PyTorch examples.
The isotropic model backbone should subsume this architecture. See config configs/model/transformer.yaml
"""
import copy
from typing import Optional, Any
from typing import Tuple
import torch
from torch import Tensor
from torch.nn import Module
... | """End-to-end classification Transformer adapted from PyTorch examples.
The isotropic model backbone should subsume this architecture. See config configs/model/transformer.yaml
"""
import copy
from typing import Optional, Any
from typing import Tuple
import torch
from torch import Tensor
from torch.nn import Module
... |
43,483 | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/analyze/convnexts4nd/src/models/baselines/transformer.py | 269,272 | 248,297 | forward | TransformerDecoder | 272,297 | 272,297 | class TransformerDecoder(Module):
r"""TransformerDecoder is a stack of N decoder layers
Args:
decoder_layer: an instance of the TransformerDecoderLayer() class (required).
num_layers: the number of sub-decoder-layers in the decoder (required).
norm: the layer normalization component (opt... | class TransformerDecoder(Module):
r"""TransformerDecoder is a stack of N decoder layers
Args:
decoder_layer: an instance of the TransformerDecoderLayer() class (required).
num_layers: the number of sub-decoder-layers in the decoder (required).
norm: the layer normalization component (opt... | r"""Pass the inputs (and mask) through the decoder layer in turn.
Args:
tgt: the sequence to the decoder (required).
memory: the sequence from the last layer of the encoder (required).
tgt_mask: the mask for the tgt sequence (optional).
memory_mask: the ma... | r"""Pass the inputs (and mask) through the decoder layer in turn.
Args:
tgt: the sequence to the decoder (required).
memory: the sequence from the last layer of the encoder (required).
tgt_mask: the mask for the tgt sequence (optional).
memory_mask: the ma... | 100 | 399 | 290 | 689 | """End-to-end classification Transformer adapted from PyTorch examples.
The isotropic model backbone should subsume this architecture. See config configs/model/transformer.yaml
"""
import copy
from typing import Optional, Any
from typing import Tuple
import torch
from torch import Tensor
from torch.nn import Module
... | """End-to-end classification Transformer adapted from PyTorch examples.
The isotropic model backbone should subsume this architecture. See config configs/model/transformer.yaml
"""
import copy
from typing import Optional, Any
from typing import Tuple
import torch
from torch import Tensor
from torch.nn import Module
... |
43,484 | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/analyze/convnexts4nd/src/models/baselines/transformer.py | 426,430 | 382,455 | forward | TransformerDecoderLayer | 430,455 | 430,455 | class TransformerDecoderLayer(Module):
r"""TransformerDecoderLayer is made up of self-attn, multi-head-attn and feedforward network.
This standard decoder layer is based on the paper "Attention Is All You Need".
Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez,
Luka... | class TransformerDecoderLayer(Module):
r"""TransformerDecoderLayer is made up of self-attn, multi-head-attn and feedforward network.
This standard decoder layer is based on the paper "Attention Is All You Need".
Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez,
Luka... | r"""Pass the inputs (and mask) through the decoder layer.
Args:
tgt: the sequence to the decoder layer (required).
memory: the sequence from the last layer of the encoder (required).
tgt_mask: the mask for the tgt sequence (optional).
memory_mask: the mask... | r"""Pass the inputs (and mask) through the decoder layer.
Args:
tgt: the sequence to the decoder layer (required).
memory: the sequence from the last layer of the encoder (required).
tgt_mask: the mask for the tgt sequence (optional).
memory_mask: the mask... | 116 | 810 | 402 | 1,212 | """End-to-end classification Transformer adapted from PyTorch examples.
The isotropic model backbone should subsume this architecture. See config configs/model/transformer.yaml
"""
import copy
from typing import Optional, Any
from typing import Tuple
import torch
from torch import Tensor
from torch.nn import Module
... | """End-to-end classification Transformer adapted from PyTorch examples.
The isotropic model backbone should subsume this architecture. See config configs/model/transformer.yaml
"""
import copy
from typing import Optional, Any
from typing import Tuple
import torch
from torch import Tensor
from torch.nn import Module
... |
43,485 | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/analyze/convnexts4nd/src/models/baselines/transformer.py | 228,230 | 208,248 | forward | TransformerEncoder | 230,248 | 230,248 | class TransformerEncoder(Module):
r"""TransformerEncoder is a stack of N encoder layers
Args:
encoder_layer: an instance of the TransformerEncoderLayer() class (required).
num_layers: the number of sub-encoder-layers in the encoder (required).
norm: the layer normalization component (opt... | class TransformerEncoder(Module):
r"""TransformerEncoder is a stack of N encoder layers
Args:
encoder_layer: an instance of the TransformerEncoderLayer() class (required).
num_layers: the number of sub-encoder-layers in the encoder (required).
norm: the layer normalization component (opt... | r"""Pass the input through the encoder layers in turn.
Args:
src: the sequence to the encoder (required).
mask: the mask for the src sequence (optional).
src_key_padding_mask: the mask for the src keys per batch (optional).
Shape:
see the docs in T... | r"""Pass the input through the encoder layers in turn.
Args:
src: the sequence to the encoder (required).
mask: the mask for the src sequence (optional).
src_key_padding_mask: the mask for the src keys per batch (optional).
Shape:
see the docs in T... | 66 | 328 | 178 | 506 | """End-to-end classification Transformer adapted from PyTorch examples.
The isotropic model backbone should subsume this architecture. See config configs/model/transformer.yaml
"""
import copy
from typing import Optional, Any
from typing import Tuple
import torch
from torch import Tensor
from torch.nn import Module
... | """End-to-end classification Transformer adapted from PyTorch examples.
The isotropic model backbone should subsume this architecture. See config configs/model/transformer.yaml
"""
import copy
from typing import Optional, Any
from typing import Tuple
import torch
from torch import Tensor
from torch.nn import Module
... |
43,486 | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/analyze/convnexts4nd/src/models/baselines/transformer.py | 346,348 | 297,382 | forward | TransformerEncoderLayer | 348,382 | 348,382 | class TransformerEncoderLayer(Module):
r"""TransformerEncoderLayer is made up of self-attn and feedforward network.
This standard encoder layer is based on the paper "Attention Is All You Need".
Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez,
Lukasz Kaiser, and Il... | class TransformerEncoderLayer(Module):
r"""TransformerEncoderLayer is made up of self-attn and feedforward network.
This standard encoder layer is based on the paper "Attention Is All You Need".
Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez,
Lukasz Kaiser, and Il... | r"""Pass the input through the encoder layer.
Args:
src: the sequence to the encoder layer (required).
src_mask: the mask for the src sequence (optional).
src_key_padding_mask: the mask for the src keys per batch (optional).
Shape:
see the docs in ... | r"""Pass the input through the encoder layer.
Args:
src: the sequence to the encoder layer (required).
src_mask: the mask for the src sequence (optional).
src_key_padding_mask: the mask for the src keys per batch (optional).
Shape:
see the docs in ... | 114 | 725 | 439 | 1,164 | """End-to-end classification Transformer adapted from PyTorch examples.
The isotropic model backbone should subsume this architecture. See config configs/model/transformer.yaml
"""
import copy
from typing import Optional, Any
from typing import Tuple
import torch
from torch import Tensor
from torch.nn import Module
... | """End-to-end classification Transformer adapted from PyTorch examples.
The isotropic model backbone should subsume this architecture. See config configs/model/transformer.yaml
"""
import copy
from typing import Optional, Any
from typing import Tuple
import torch
from torch import Tensor
from torch.nn import Module
... |
43,487 | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/analyze/convnexts4nd/src/models/nn/activation.py | 80,81 | 1,94 | laplace | 81,84 | 81,84 | """Utilities for activation functions."""
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
def Activation(activation=None, size=None, dim=-1):
if activation in [ None, 'id', 'identity', 'linear', 'none' ]:
return nn.Identity()
elif activation == 'tanh':
return nn.... | """Utilities for activation functions."""
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
def Activation(activation=None, size=None, dim=-1):
if activation in [ None, 'id', 'identity', 'linear', 'none' ]:
return nn.Identity()
elif activation == 'tanh':
return nn.... | x = (x - mu).div(sigma * math.sqrt(2.0))
return 0.5 * (1.0 + torch.erf(x))
| x = (x - mu).div(sigma * math.sqrt(2.0))
return 0.5 * (1.0 + torch.erf(x))
| 13 | 941 | 46 | 987 | """Utilities for activation functions."""
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
def Activation(activation=None, size=None, dim=-1):
if activation in [ None, 'id', 'identity', 'linear', 'none' ]:
return nn.Identity()
elif activation == 'tanh':
return nn.... | """Utilities for activation functions."""
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
def Activation(activation=None, size=None, dim=-1):
if activation in [ None, 'id', 'identity', 'linear', 'none' ]:
return nn.Identity()
elif activation == 'tanh':
return nn.... | |
43,488 | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/analyze/convnexts4nd/src/models/nn/activation.py | 49,50 | 42,53 | forward | GLU | 50,53 | 50,53 | class GLU(nn.Module):
def __init__(self, dim=-1, activation='sigmoid'):
super().__init__()
assert not activation.startswith('glu')
self.dim = dim
self.activation_fn = Activation(activation)
def forward(self, x):
FILL_FUNC_BODY | class GLU(nn.Module):
def __init__(self, dim=-1, activation='sigmoid'):
super().__init__()
assert not activation.startswith('glu')
self.dim = dim
self.activation_fn = Activation(activation)
def forward(self, x):
FILL_FUNC_BODY | x, g = torch.split(x, x.size(self.dim)//2, dim=self.dim)
return x * self.activation_fn(g)
| x, g = torch.split(x, x.size(self.dim)//2, dim=self.dim)
return x * self.activation_fn(g)
| 10 | 93 | 48 | 141 | """Utilities for activation functions."""
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
def Activation(activation=None, size=None, dim=-1):
if activation in [ None, 'id', 'identity', 'linear', 'none' ]:
return nn.Identity()
elif activation == 'tanh':
return nn.... | """Utilities for activation functions."""
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
def Activation(activation=None, size=None, dim=-1):
if activation in [ None, 'id', 'identity', 'linear', 'none' ]:
return nn.Identity()
elif activation == 'tanh':
return nn.... |
43,489 | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/analyze/convnexts4nd/src/models/nn/activation.py | 90,91 | 84,94 | forward | Laplace | 91,94 | 91,94 | class Laplace(nn.Module):
def __init__(self, mu=0.707107, sigma=0.282095):
super().__init__()
self.mu = mu
self.sigma = sigma
def forward(self, x):
FILL_FUNC_BODY | class Laplace(nn.Module):
def __init__(self, mu=0.707107, sigma=0.282095):
super().__init__()
self.mu = mu
self.sigma = sigma
def forward(self, x):
FILL_FUNC_BODY | return laplace(x, mu=self.mu, sigma=self.sigma)
| return laplace(x, mu=self.mu, sigma=self.sigma)
| 4 | 83 | 26 | 109 | """Utilities for activation functions."""
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
def Activation(activation=None, size=None, dim=-1):
if activation in [ None, 'id', 'identity', 'linear', 'none' ]:
return nn.Identity()
elif activation == 'tanh':
return nn.... | """Utilities for activation functions."""
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
def Activation(activation=None, size=None, dim=-1):
if activation in [ None, 'id', 'identity', 'linear', 'none' ]:
return nn.Identity()
elif activation == 'tanh':
return nn.... |
43,490 | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/analyze/convnexts4nd/src/models/nn/activation.py | 66,67 | 53,75 | forward | ModReLU | 67,75 | 67,75 | class ModReLU(nn.Module):
# Adapted from https://github.com/Lezcano/expRNN
def __init__(self, features):
# For now we just support square layers
super().__init__()
self.features = features
self.b = nn.Parameter(torch.Tensor(self.features))
self.reset_parameters()
de... | class ModReLU(nn.Module):
# Adapted from https://github.com/Lezcano/expRNN
def __init__(self, features):
# For now we just support square layers
super().__init__()
self.features = features
self.b = nn.Parameter(torch.Tensor(self.features))
self.reset_parameters()
de... | norm = torch.abs(inputs)
biased_norm = norm + self.b
magnitude = F.relu(biased_norm)
phase = torch.sign(inputs)
return phase * magnitude
| norm = torch.abs(inputs)
biased_norm = norm + self.b
magnitude = F.relu(biased_norm)
phase = torch.sign(inputs)
return phase * magnitude
| 18 | 149 | 67 | 216 | """Utilities for activation functions."""
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
def Activation(activation=None, size=None, dim=-1):
if activation in [ None, 'id', 'identity', 'linear', 'none' ]:
return nn.Identity()
elif activation == 'tanh':
return nn.... | """Utilities for activation functions."""
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
def Activation(activation=None, size=None, dim=-1):
if activation in [ None, 'id', 'identity', 'linear', 'none' ]:
return nn.Identity()
elif activation == 'tanh':
return nn.... |
43,491 | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/analyze/convnexts4nd/src/models/nn/activation.py | 76,77 | 75,80 | forward | SquaredReLU | 77,80 | 77,80 | class SquaredReLU(nn.Module):
def forward(self, x):
FILL_FUNC_BODY | class SquaredReLU(nn.Module):
def forward(self, x):
FILL_FUNC_BODY | # return F.relu(x)**2
return torch.square(F.relu(x)) # Could this be faster?
| # return F.relu(x)**2
return torch.square(F.relu(x)) # Could this be faster?
| 10 | 32 | 39 | 71 | """Utilities for activation functions."""
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
def Activation(activation=None, size=None, dim=-1):
if activation in [ None, 'id', 'identity', 'linear', 'none' ]:
return nn.Identity()
elif activation == 'tanh':
return nn.... | """Utilities for activation functions."""
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
def Activation(activation=None, size=None, dim=-1):
if activation in [ None, 'id', 'identity', 'linear', 'none' ]:
return nn.Identity()
elif activation == 'tanh':
return nn.... |
43,492 | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/analyze/convnexts4nd/src/models/nn/gate.py | 58,59 | 9,136 | forward | Gate | 59,125 | 59,125 | class Gate(nn.Module):
"""Implements gating mechanisms.
LSSL paper elaborates on the most import connection: A standard sigmoid gate
is equivalent to an exponential parameterization + Backwards Euler disc.
Mechanisms:
N - No gate
G - Standard sigmoid gate
UR - Uniform refine gates
R ... | class Gate(nn.Module):
"""Implements gating mechanisms.
LSSL paper elaborates on the most import connection: A standard sigmoid gate
is equivalent to an exponential parameterization + Backwards Euler disc.
Mechanisms:
N - No gate
G - Standard sigmoid gate
UR - Uniform refine gates
R ... | if self.mechanism == 'N':
return 1.0
if self.mechanism == 'G':
g_preact = self.W_g(*inputs)
g = torch.sigmoid(g_preact)
if self.mechanism == 'U':
g_preact = self.W_g(*inputs) + self.b_g
g = torch.sigmoid(g_preact)
elif self.mec... | if self.mechanism == 'N':
return 1.0
if self.mechanism == 'G':
g_preact = self.W_g(*inputs)
g = torch.sigmoid(g_preact)
if self.mechanism == 'U':
g_preact = self.W_g(*inputs) + self.b_g
g = torch.sigmoid(g_preact)
elif self.mec... | 229 | 794 | 979 | 1,773 | """Defines flexible gating mechanisms.
Based on ideas from LSSL paper and UR-LSTM paper (https://arxiv.org/abs/1910.09890).
"""
import torch
import torch.nn as nn
class Gate(nn.Module):
"""Implements gating mechanisms.
LSSL paper elaborates on the most import connection: A standard sigmoid gate
is equiv... | """Defines flexible gating mechanisms.
Based on ideas from LSSL paper and UR-LSTM paper (https://arxiv.org/abs/1910.09890).
"""
import torch
import torch.nn as nn
class Gate(nn.Module):
"""Implements gating mechanisms.
LSSL paper elaborates on the most import connection: A standard sigmoid gate
is equiv... |
43,493 | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/analyze/convnexts4nd/src/models/nn/initialization.py | 52,53 | 1,75 | weights_init_embedding | 53,75 | 53,75 | """Original from Transformer-XL as a hook for their initialization. Currently not used."""
import torch
from torch import nn
def init_weight(weight, init_cfg):
if init_cfg.init == 'uniform':
nn.init.uniform_(weight, -init_cfg.init_range, init_cfg.init_range)
elif init_cfg.init == 'normal':
nn.... | """Original from Transformer-XL as a hook for their initialization. Currently not used."""
import torch
from torch import nn
def init_weight(weight, init_cfg):
if init_cfg.init == 'uniform':
nn.init.uniform_(weight, -init_cfg.init_range, init_cfg.init_range)
elif init_cfg.init == 'normal':
nn.... | classname = m.__class__.__name__
if classname.find('AdaptiveEmbedding') != -1:
if hasattr(m, 'emb_projs'):
for i in range(len(m.emb_projs)):
if m.emb_projs[i] is not None:
nn.init.normal_(m.emb_projs[i], 0.0, init_cfg.proj_init_std)
elif classname.find... | classname = m.__class__.__name__
if classname.find('AdaptiveEmbedding') != -1:
if hasattr(m, 'emb_projs'):
for i in range(len(m.emb_projs)):
if m.emb_projs[i] is not None:
nn.init.normal_(m.emb_projs[i], 0.0, init_cfg.proj_init_std)
elif classname.find... | 84 | 732 | 438 | 1,170 | """Original from Transformer-XL as a hook for their initialization. Currently not used."""
import torch
from torch import nn
def init_weight(weight, init_cfg):
if init_cfg.init == 'uniform':
nn.init.uniform_(weight, -init_cfg.init_range, init_cfg.init_range)
elif init_cfg.init == 'normal':
nn.... | """Original from Transformer-XL as a hook for their initialization. Currently not used."""
import torch
from torch import nn
def init_weight(weight, init_cfg):
if init_cfg.init == 'uniform':
nn.init.uniform_(weight, -init_cfg.init_range, init_cfg.init_range)
elif init_cfg.init == 'normal':
nn.... | |
43,494 | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/analyze/convnexts4nd/src/models/nn/residual.py | 48,49 | 30,54 | forward | Affine | 49,54 | 49,54 | class Affine(Residual):
"""Residual with learnable scalar multipliers on the main branch.
Arguments:
- scalar: Single scalar multiplier, or one per dimension
- scale, power: Initialize to scale * layer_num**(-power)
"""
def __init__(self, *args, scalar=True, gamma=0.0, **kwargs):
# pri... | class Affine(Residual):
"""Residual with learnable scalar multipliers on the main branch.
Arguments:
- scalar: Single scalar multiplier, or one per dimension
- scale, power: Initialize to scale * layer_num**(-power)
"""
def __init__(self, *args, scalar=True, gamma=0.0, **kwargs):
# pri... | c = self.affine
if transposed: c = c.unsqueeze(-1)
return self.alpha * x + c * y
| c = self.affine
if transposed: c = c.unsqueeze(-1)
return self.alpha * x + c * y
| 16 | 225 | 44 | 269 | """Implementations of different types of residual functions."""
import torch
from torch import nn
class Residual(nn.Module):
"""Residual connection with constant affine weights.
Can simulate standard residual, no residual, and "constant gates".
"""
def __init__(self, i_layer, d_input, d_model, alpha... | """Implementations of different types of residual functions."""
import torch
from torch import nn
class Residual(nn.Module):
"""Residual connection with constant affine weights.
Can simulate standard residual, no residual, and "constant gates".
"""
def __init__(self, i_layer, d_input, d_model, alpha... |
43,495 | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/analyze/convnexts4nd/src/models/nn/residual.py | 90,91 | 81,99 | forward | DecayResidual | 91,99 | 91,99 | class DecayResidual(Residual):
""" Residual connection that can decay the linear combination depending on depth. """
def __init__(self, *args, power=0.5, l2=True):
# print("DecayResidual extra kwargs", kwargs)
super().__init__(*args)
self.power = power
self.l2 = l2
def forw... | class DecayResidual(Residual):
""" Residual connection that can decay the linear combination depending on depth. """
def __init__(self, *args, power=0.5, l2=True):
# print("DecayResidual extra kwargs", kwargs)
super().__init__(*args)
self.power = power
self.l2 = l2
def forw... | beta = self.i_layer ** (-self.power)
if self.l2:
alpha = (1. - beta**2)**0.5
else:
alpha = 1. - beta
return alpha * x + beta * y
| beta = self.i_layer ** (-self.power)
if self.l2:
alpha = (1. - beta**2)**0.5
else:
alpha = 1. - beta
return alpha * x + beta * y
| 26 | 119 | 71 | 190 | """Implementations of different types of residual functions."""
import torch
from torch import nn
class Residual(nn.Module):
"""Residual connection with constant affine weights.
Can simulate standard residual, no residual, and "constant gates".
"""
def __init__(self, i_layer, d_input, d_model, alpha... | """Implementations of different types of residual functions."""
import torch
from torch import nn
class Residual(nn.Module):
"""Residual connection with constant affine weights.
Can simulate standard residual, no residual, and "constant gates".
"""
def __init__(self, i_layer, d_input, d_model, alpha... |
43,496 | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/analyze/convnexts4nd/src/models/nn/residual.py | 71,72 | 60,81 | forward | Highway | 72,81 | 72,81 | class Highway(Residual):
def __init__(self, *args, scaling_correction=False, elemwise=False):
super().__init__(*args)
self.scaling_correction = 1.732 if scaling_correction else 1.0 # TODO
self.elemwise = elemwise
self.Wx = nn.Linear(self.d_input, self.d_input)
if self.elemwis... | class Highway(Residual):
def __init__(self, *args, scaling_correction=False, elemwise=False):
super().__init__(*args)
self.scaling_correction = 1.732 if scaling_correction else 1.0 # TODO
self.elemwise = elemwise
self.Wx = nn.Linear(self.d_input, self.d_input)
if self.elemwis... | if self.elemwise:
y = self.Wy * y
else:
y = self.Wy(y)
r = torch.sigmoid(self.Wx(x) + y)
z = self.scaling_correction * (1.-r) * x + r * y
return z
| if self.elemwise:
y = self.Wy * y
else:
y = self.Wy(y)
r = torch.sigmoid(self.Wx(x) + y)
z = self.scaling_correction * (1.-r) * x + r * y
return z
| 29 | 192 | 92 | 284 | """Implementations of different types of residual functions."""
import torch
from torch import nn
class Residual(nn.Module):
"""Residual connection with constant affine weights.
Can simulate standard residual, no residual, and "constant gates".
"""
def __init__(self, i_layer, d_input, d_model, alpha... | """Implementations of different types of residual functions."""
import torch
from torch import nn
class Residual(nn.Module):
"""Residual connection with constant affine weights.
Can simulate standard residual, no residual, and "constant gates".
"""
def __init__(self, i_layer, d_input, d_model, alpha... |
43,497 | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/analyze/convnexts4nd/src/models/nn/residual.py | 26,27 | 6,30 | forward | Residual | 27,30 | 27,30 | class Residual(nn.Module):
"""Residual connection with constant affine weights.
Can simulate standard residual, no residual, and "constant gates".
"""
def __init__(self, i_layer, d_input, d_model, alpha=1.0, beta=1.0):
# print("ConstantResidual extra kwargs", kwargs)
super().__init__()... | class Residual(nn.Module):
"""Residual connection with constant affine weights.
Can simulate standard residual, no residual, and "constant gates".
"""
def __init__(self, i_layer, d_input, d_model, alpha=1.0, beta=1.0):
# print("ConstantResidual extra kwargs", kwargs)
super().__init__()... | y = self.beta*y if self.beta != 1.0 else y
return self.alpha * x + y if self.alpha else y
| y = self.beta*y if self.beta != 1.0 else y
return self.alpha * x + y if self.alpha else y
| 19 | 216 | 40 | 256 | """Implementations of different types of residual functions."""
import torch
from torch import nn
class Residual(nn.Module):
"""Residual connection with constant affine weights.
Can simulate standard residual, no residual, and "constant gates".
"""
def __init__(self, i_layer, d_input, d_model, alpha... | """Implementations of different types of residual functions."""
import torch
from torch import nn
class Residual(nn.Module):
"""Residual connection with constant affine weights.
Can simulate standard residual, no residual, and "constant gates".
"""
def __init__(self, i_layer, d_input, d_model, alpha... |
43,498 | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/analyze/convnexts4nd/src/models/sequence/base.py | 91,92 | 1,133 | TransposedModule | 93,110 | 92,110 | """Defines base class SequenceModule, a modular interface for sequence models."""
from torch import nn
import functools
class SequenceModule(nn.Module):
"""Abstract sequence model class. All models must adhere to this interface.
A SequenceModule is generally a model that transforms an input of shape
(n_ba... | """Defines base class SequenceModule, a modular interface for sequence models."""
from torch import nn
import functools
class SequenceModule(nn.Module):
"""Abstract sequence model class. All models must adhere to this interface.
A SequenceModule is generally a model that transforms an input of shape
(n_ba... | # https://stackoverflow.com/a/65470430/1980685
@functools.wraps(module, updated=())
class TransposedModule(module):
def __init__(self, *args, transposed=False, **kwargs):
super().__init__(*args, **kwargs)
self.transposed = transposed
def forward(self, x, state=None, ... | """Wrap a SequenceModule class to accept transposed parameter, handle state, absorb kwargs."""
# https://stackoverflow.com/a/65470430/1980685
@functools.wraps(module, updated=())
class TransposedModule(module):
def __init__(self, *args, transposed=False, **kwargs):
super().__init__(*... | 69 | 1,184 | 282 | 1,466 | """Defines base class SequenceModule, a modular interface for sequence models."""
from torch import nn
import functools
class SequenceModule(nn.Module):
"""Abstract sequence model class. All models must adhere to this interface.
A SequenceModule is generally a model that transforms an input of shape
(n_ba... | """Defines base class SequenceModule, a modular interface for sequence models."""
from torch import nn
import functools
class SequenceModule(nn.Module):
"""Abstract sequence model class. All models must adhere to this interface.
A SequenceModule is generally a model that transforms an input of shape
(n_ba... | |
43,499 | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/analyze/convnexts4nd/src/models/sequence/base.py | 131,132 | 110,133 | step | SequenceIdentity | 132,133 | 132,133 | @TransposedModule
class SequenceIdentity(SequenceModule):
"""Simple SequenceModule for testing purposes."""
def __init__(self, d_model, dropout=0.0, **kwargs):
"""Default interface for SequenceModule
d_model: input dimension (sometimes denoted H for hidden dimension)
transposed: if Tru... | @TransposedModule
class SequenceIdentity(SequenceModule):
"""Simple SequenceModule for testing purposes."""
def __init__(self, d_model, dropout=0.0, **kwargs):
"""Default interface for SequenceModule
d_model: input dimension (sometimes denoted H for hidden dimension)
transposed: if Tru... | return x, state
| return x, state
| 3 | 206 | 7 | 213 | """Defines base class SequenceModule, a modular interface for sequence models."""
from torch import nn
import functools
class SequenceModule(nn.Module):
"""Abstract sequence model class. All models must adhere to this interface.
A SequenceModule is generally a model that transforms an input of shape
(n_ba... | """Defines base class SequenceModule, a modular interface for sequence models."""
from torch import nn
import functools
class SequenceModule(nn.Module):
"""Abstract sequence model class. All models must adhere to this interface.
A SequenceModule is generally a model that transforms an input of shape
(n_ba... |
43,500 | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/analyze/convnexts4nd/src/models/sequence/base.py | 21,23 | 5,91 | d_model | SequenceModule | 28,32 | 23,32 | class SequenceModule(nn.Module):
"""Abstract sequence model class. All models must adhere to this interface.
A SequenceModule is generally a model that transforms an input of shape
(n_batch, l_sequence, d_model) to (n_batch, l_sequence, d_output)
REQUIRED methods and attributes
forward, d_model, d... | class SequenceModule(nn.Module):
"""Abstract sequence model class. All models must adhere to this interface.
A SequenceModule is generally a model that transforms an input of shape
(n_batch, l_sequence, d_model) to (n_batch, l_sequence, d_output)
REQUIRED methods and attributes
forward, d_model, d... | if getattr(self, "_d_model", None) is None:
raise NotImplementedError("SequenceModule instantiation must set d_model")
return self._d_model
| """Model dimension (generally same as input dimension).
This attribute is required for all SequenceModule instantiations.
It is used by the rest of the pipeline (e.g. model backbone, encoder) to track the internal shapes of the full model.
"""
if getattr(self, "_d_model", None) ... | 14 | 875 | 50 | 925 | """Defines base class SequenceModule, a modular interface for sequence models."""
from torch import nn
import functools
class SequenceModule(nn.Module):
"""Abstract sequence model class. All models must adhere to this interface.
A SequenceModule is generally a model that transforms an input of shape
(n_ba... | """Defines base class SequenceModule, a modular interface for sequence models."""
from torch import nn
import functools
class SequenceModule(nn.Module):
"""Abstract sequence model class. All models must adhere to this interface.
A SequenceModule is generally a model that transforms an input of shape
(n_ba... |
43,501 | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/analyze/convnexts4nd/src/models/sequence/base.py | 100,101 | 94,108 | forward | TransposedModule | 101,108 | 101,108 | @functools.wraps(module, updated=())
class TransposedModule(module):
def __init__(self, *args, transposed=False, **kwargs):
super().__init__(*args, **kwargs)
self.transposed = transposed
def forward(self, x, state=None, **kwargs):
FILL_FUNC_BODY | @functools.wraps(module, updated=())
class TransposedModule(module):
def __init__(self, *args, transposed=False, **kwargs):
super().__init__(*args, **kwargs)
self.transposed = transposed
def forward(self, x, state=None, **kwargs):
FILL_FUNC_BODY | if self.transposed: x = x.transpose(-1, -2)
x, next_state = super().forward(x, state) # Don't use kwarg because nn.LSTM
next_state = None if state is None else next_state
if self.transposed: x = x.transpose(-1,-2)
return x, next_state
# https://stackoverfl... | if self.transposed: x = x.transpose(-1, -2)
x, next_state = super().forward(x, state) # Don't use kwarg because nn.LSTM
next_state = None if state is None else next_state
if self.transposed: x = x.transpose(-1,-2)
return x, next_state
# https://stackoverfl... | 46 | 92 | 155 | 247 | """Defines base class SequenceModule, a modular interface for sequence models."""
from torch import nn
import functools
class SequenceModule(nn.Module):
"""Abstract sequence model class. All models must adhere to this interface.
A SequenceModule is generally a model that transforms an input of shape
(n_ba... | """Defines base class SequenceModule, a modular interface for sequence models."""
from torch import nn
import functools
class SequenceModule(nn.Module):
"""Abstract sequence model class. All models must adhere to this interface.
A SequenceModule is generally a model that transforms an input of shape
(n_ba... |
43,502 | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/analyze/convnexts4nd/src/utils/distributed.py | 69,70 | 1,145 | all_reduce_item | 73,103 | 70,103 | # Copyright (c) 2019-2020, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... | # Copyright (c) 2019-2020, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... | if torch.distributed.is_available() and torch.distributed.is_initialized():
if op == 'sum' or op == 'mean':
dop = torch.distributed.ReduceOp.SUM
elif op == 'min':
dop = torch.distributed.ReduceOp.MIN
elif op == 'max':
dop = torch.distributed.ReduceOp.MAX
... | """
All-reduces single scalar value if distributed is in use
"""
if torch.distributed.is_available() and torch.distributed.is_initialized():
if op == 'sum' or op == 'mean':
dop = torch.distributed.ReduceOp.SUM
elif op == 'min':
dop = torch.distributed.ReduceOp.MIN... | 85 | 1,022 | 341 | 1,363 | # Copyright (c) 2019-2020, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... | # Copyright (c) 2019-2020, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... | |
43,503 | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba | /home/hieuvd/dung_repo/raw/stars_03/MzeroMiko_VMamba/VMamba/analyze/convnexts4nd/src/utils/optim/ema.py | 8,9 | 1,52 | build_ema_optimizer | 9,50 | 9,50 | """Wrapper of optimizers in torch.optim for computation of exponential moving average of parameters.
Source: https://github.com/kamenbliznashki/pixel_models/blob/master/optim.py
"""
import torch
def build_ema_optimizer(optimizer_cls):
FILL_FUNC_BODYAdam = build_ema_optimizer(torch.optim.Adam)
RMSprop = build_ema_opt... | """Wrapper of optimizers in torch.optim for computation of exponential moving average of parameters.
Source: https://github.com/kamenbliznashki/pixel_models/blob/master/optim.py
"""
import torch
def build_ema_optimizer(optimizer_cls):
FILL_FUNC_BODYAdam = build_ema_optimizer(torch.optim.Adam)
RMSprop = build_ema_opt... | class Optimizer(optimizer_cls):
def __init__(self, *args, polyak=0.0, **kwargs):
if not 0.0 <= polyak <= 1.0:
raise ValueError("Invalid polyak decay rate: {}".format(polyak))
super().__init__(*args, **kwargs)
self.defaults['polyak'] = polyak
se... | class Optimizer(optimizer_cls):
def __init__(self, *args, polyak=0.0, **kwargs):
if not 0.0 <= polyak <= 1.0:
raise ValueError("Invalid polyak decay rate: {}".format(polyak))
super().__init__(*args, **kwargs)
self.defaults['polyak'] = polyak
se... | 131 | 122 | 461 | 583 | """Wrapper of optimizers in torch.optim for computation of exponential moving average of parameters.
Source: https://github.com/kamenbliznashki/pixel_models/blob/master/optim.py
"""
import torch
def build_ema_optimizer(optimizer_cls):
FILL_FUNC_BODYAdam = build_ema_optimizer(torch.optim.Adam)
RMSprop = build_ema_opt... | """Wrapper of optimizers in torch.optim for computation of exponential moving average of parameters.
Source: https://github.com/kamenbliznashki/pixel_models/blob/master/optim.py
"""
import torch
def build_ema_optimizer(optimizer_cls):
FILL_FUNC_BODYAdam = build_ema_optimizer(torch.optim.Adam)
RMSprop = build_ema_opt... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.